/*!
 * STONK avatar renderer — dùng chung cho /app, dashboard trong Extension và popup.
 * Chỉ dựng giao diện avatar; không đọc/ghi token, storage hoặc dữ liệu người dùng.
 */
(function installStonkAvatar(global) {
  "use strict";

  const PALETTES = [
    ["#2b1458", "#8b5cf6", "#72f2df"],
    ["#3a0f3a", "#ff176b", "#ffb21a"],
    ["#10294d", "#3b82f6", "#72f2df"],
    ["#36185a", "#d946ef", "#f9a8d4"],
    ["#173b36", "#22c55e", "#a7f3d0"],
  ];

  function hashSeed(value) {
    const source = String(value || "stonk").trim().toLowerCase();
    let hash = 2166136261;
    for (let index = 0; index < source.length; index += 1) {
      hash ^= source.charCodeAt(index);
      hash = Math.imul(hash, 16777619);
    }
    return hash >>> 0;
  }

  function escapeXml(value) {
    return String(value || "").replace(/[&<>"']/g, character => ({
      "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;",
    }[character]));
  }

  function isImageUrl(value) {
    return /^(?:https?:|data:image\/|blob:|chrome-extension:)/i.test(String(value || "").trim());
  }

  function svgMarkup(seed, label) {
    const hash = hashSeed(seed);
    const [background, primary, accent] = PALETTES[hash % PALETTES.length];
    const cells = [];
    for (let row = 0; row < 4; row += 1) {
      for (let column = 0; column < 2; column += 1) {
        const bit = (hash >>> ((row * 2 + column) % 24)) & 1;
        if (!bit) continue;
        const x = 22 + column * 7;
        const y = 20 + row * 7;
        const mirrorX = 64 - x - 6;
        cells.push(`<rect x="${x}" y="${y}" width="6" height="6" rx="2" fill="${accent}"/>`);
        if (mirrorX !== x) cells.push(`<rect x="${mirrorX}" y="${y}" width="6" height="6" rx="2" fill="${accent}"/>`);
      }
    }
    return `<svg class="stonk-account-avatar" viewBox="0 0 64 64" role="img" aria-label="${escapeXml(label || "Ảnh đại diện STONK")}">
      <rect width="64" height="64" rx="18" fill="${background}"/>
      <circle cx="50" cy="14" r="4" fill="${accent}" opacity=".95"/>
      <ellipse cx="32" cy="33" rx="24" ry="10" fill="none" stroke="${primary}" stroke-width="2.5" transform="rotate(-16 32 33)" opacity=".9"/>
      <circle cx="32" cy="33" r="16" fill="${primary}"/>
      ${cells.join("")}
      <circle cx="16" cy="48" r="2" fill="#fff" opacity=".72"/>
      <circle cx="12" cy="17" r="1.5" fill="#fff" opacity=".86"/>
    </svg>`;
  }

  function render(element, options = {}) {
    if (!element) return "missing";
    const avatar = String(options.avatar || "").trim();
    const seed = options.seed || options.label || "stonk";
    const label = options.label || "Ảnh đại diện STONK";
    element.style.backgroundImage = "none";
    if (isImageUrl(avatar)) {
      const image = document.createElement("img");
      image.className = "stonk-account-avatar";
      image.src = avatar;
      image.alt = label;
      image.referrerPolicy = "no-referrer";
      image.decoding = "async";
      image.addEventListener("error", () => {
        if (element.contains(image)) element.innerHTML = svgMarkup(seed, label);
      }, { once: true });
      element.replaceChildren(image);
      return "image";
    }
    // Preset moi (stonk:...) va emoji cu trong database deu duoc ve lai bang SVG.
    // Khong dua chuoi custom vao textContent vi emoji se phu thuoc font he dieu hanh.
    if (avatar) {
      element.innerHTML = svgMarkup(`custom:${avatar}`, label);
      return "vector-custom";
    }
    element.innerHTML = svgMarkup(seed, label);
    return "generated";
  }

  global.StonkAvatar = Object.freeze({ hashSeed, isImageUrl, render, svgMarkup });
})(globalThis);
