(() => {
  const BADGE_ID = "utxo-guard-surface";
  const MAX_TEXT = 12000;

  function collectPageText() {
    const title = document.title || "";
    const meta = Array.from(document.querySelectorAll("meta[name='description'], meta[property='og:description']"))
      .map((item) => item.getAttribute("content") || "")
      .join(" ");
    const visibleText = document.body?.innerText || "";
    return `${title}\n${meta}\n${visibleText}`.slice(0, MAX_TEXT);
  }

  function collectSecretPromptText() {
    const fields = Array.from(
      document.querySelectorAll("input, textarea, [contenteditable='true'], label, button, [role='button'], [aria-label]"),
    );
    return fields
      .map((item) => {
        const input = item;
        const id = input.getAttribute("id") || "";
        const label = id ? document.querySelector(`label[for="${CSS.escape(id)}"]`)?.textContent || "" : "";
        return [
          input.getAttribute("placeholder"),
          input.getAttribute("aria-label"),
          input.getAttribute("name"),
          input.getAttribute("id"),
          input.getAttribute("title"),
          label,
          input.textContent,
        ]
          .filter(Boolean)
          .join(" ");
      })
      .join("\n")
      .slice(0, 4000);
  }

  function hasSecretRequestPrompt(text) {
    const normalized = String(text || "").toLowerCase();
    const secret = "(seed phrase|recovery phrase|mnemonic|private key|wallet secret|wallet password)";
    const request = "(enter|input|paste|type|submit|provide|import|restore|unlock|verify|confirm|required)";
    return new RegExp(`${request}.{0,80}${secret}|${secret}.{0,80}${request}`, "i").test(normalized);
  }

  function collectUiSignals(text, secretPromptText) {
    const normalized = String(text || "").toLowerCase();
    const signals = [];
    if (normalized.includes("connect wallet")) signals.push("connect_wallet");
    if (normalized.includes("approve")) signals.push("approve");
    if (normalized.includes("claim")) signals.push("claim");
    if (normalized.includes("airdrop")) signals.push("airdrop");
    if (normalized.includes("swap")) signals.push("swap");
    if (normalized.includes("bridge")) signals.push("bridge");
    // Preventive security warnings must not be treated as secret-request prompts.
    if (hasSecretRequestPrompt(secretPromptText)) {
      if (/(seed phrase|recovery phrase|mnemonic)/i.test(secretPromptText)) signals.push("seed_phrase");
      if (/(private key|wallet secret|wallet password)/i.test(secretPromptText)) signals.push("private_key");
    }
    if (/unlimited/i.test(text)) signals.push("unlimited");
    return [...new Set(signals)];
  }

  function guessAction(text) {
    const normalized = String(text || "").toLowerCase();
    if (normalized.includes("approve")) return "approve";
    if (normalized.includes("bridge")) return "bridge";
    if (normalized.includes("swap")) return "swap";
    if (normalized.includes("claim")) return "claim";
    return "browse";
  }

  function guessChain(text) {
    const normalized = String(text || "").toLowerCase();
    if (normalized.includes("solana")) return "solana";
    if (normalized.includes("bitcoin") || normalized.includes("btc")) return "bitcoin";
    if (normalized.includes("polygon")) return "polygon";
    if (normalized.includes("arbitrum")) return "arbitrum";
    if (normalized.includes("optimism")) return "optimism";
    if (normalized.includes("base")) return "base";
    if (normalized.includes("ethereum") || normalized.includes("eth")) return "ethereum";
    return "";
  }

  function postAnalyze(reason = "auto") {
    const pageText = collectPageText();
    const secretPromptText = collectSecretPromptText();
    chrome.runtime.sendMessage(
      {
        type: "UTXO_ANALYZE_PAGE",
        reason,
        url: location.href,
        pageText,
        secretPromptText,
        uiSignals: collectUiSignals(pageText, secretPromptText),
        chain: guessChain(pageText),
        action: guessAction(pageText),
        language: navigator.language || "en",
      },
      (response) => {
        if (chrome.runtime.lastError || !response?.ok || !response.result) return;
        renderBadge(response.result);
      },
    );
  }

  function bridgeVestigeWalletSession() {
    const isVestigeIndex =
      /(^|\.)vestigeindex\.com$/i.test(location.hostname) ||
      location.hostname === "localhost" ||
      location.hostname === "127.0.0.1";
    if (!isVestigeIndex) return;

    try {
      const raw = localStorage.getItem("utxo:wallet-session");
      if (!raw) return;
      const session = JSON.parse(raw);
      if (!session?.isConnected || !session.address) return;
      chrome.runtime.sendMessage(
        {
          type: "UTXO_PAGE_WALLET_SESSION",
          origin: location.origin,
          session: {
            address: session.address,
            chainId: session.chainId,
            connectorName: session.connectorName,
            lastConnectedAt: session.lastConnectedAt,
          },
        },
        () => void chrome.runtime.lastError,
      );
    } catch {
      // The bridge only shares safe wallet metadata. No secrets are read or sent.
    }
  }

  function riskColor(risk) {
    if (risk === "critical") return ["#F43F5E", "Do not sign"];
    if (risk === "high") return ["#F97316", "High risk"];
    if (risk === "medium") return ["#F59E0B", "Review"];
    return ["#21E6F3", "Protected"];
  }

  function renderBadge(result) {
    const [color, label] = riskColor(result.risk);
    const riskPercent = Number.isFinite(Number(result.riskPercent)) ? `${result.riskPercent}%` : "--";
    const profileLabel = result.trustProfile?.label ? ` · ${result.trustProfile.label}` : "";
    let badge = document.getElementById(BADGE_ID);
    if (!badge) {
      badge = document.createElement("button");
      badge.id = BADGE_ID;
      badge.type = "button";
      badge.setAttribute("aria-label", "Open UTXO Guard analysis");
      badge.style.cssText = [
        "position:fixed",
        "right:18px",
        "bottom:18px",
        "z-index:2147483647",
        "display:flex",
        "align-items:center",
        "gap:10px",
        "border:1px solid rgba(255,255,255,.24)",
        "border-radius:999px",
        "padding:10px 12px",
        "background:rgba(13,18,30,.84)",
        "color:white",
        "font:600 12px/1.2 Inter, ui-sans-serif, system-ui, -apple-system, Segoe UI, sans-serif",
        "box-shadow:0 18px 46px rgba(0,0,0,.24)",
        "backdrop-filter:blur(18px)",
        "cursor:pointer",
      ].join(";");
      document.documentElement.appendChild(badge);
    }

    badge.replaceChildren();
    const dot = document.createElement("span");
    dot.style.cssText = `width:9px;height:9px;border-radius:999px;background:${color};box-shadow:0 0 18px ${color};display:inline-block`;
    const title = document.createElement("span");
    title.textContent = "UTXO Guard";
    const summary = document.createElement("span");
    summary.style.opacity = ".62";
    summary.textContent = `${label}${profileLabel}`;
    const pill = document.createElement("span");
    pill.style.cssText = "border-radius:999px;background:rgba(255,255,255,.1);padding:4px 7px";
    pill.textContent = `${riskPercent} risk`;
    badge.append(dot, title, summary, pill);
    badge.onclick = () => chrome.runtime.sendMessage({ type: "UTXO_GET_STATE" });
  }

  chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
    if (message?.type === "UTXO_ANALYSIS_RESULT") {
      renderBadge(message.result);
      sendResponse?.({ ok: true });
      return true;
    }
    if (message?.type === "UTXO_FORCE_ANALYZE") {
      postAnalyze("manual");
      sendResponse?.({ ok: true });
      return true;
    }
    return false;
  });

  const start = () => {
    bridgeVestigeWalletSession();
    window.setInterval(bridgeVestigeWalletSession, 6000);
    window.setTimeout(() => postAnalyze("auto"), 900);
  };

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", start, { once: true });
  } else {
    start();
  }
})();
