(() => {
  const color = { green: "#19D3B5", blue: "#67E8F9", yellow: "#F4B942", red: "#E85C4A", grey: "#5C6B80" };
  let statusHost = null;
  let latestAnalysis = null;
  let detailsOpen = false;

  function respond(requestId, allow, analysis) {
    window.dispatchEvent(new CustomEvent("veersec:analysis-response", { detail: { requestId, allow, analysis } }));
  }

  function esc(value) {
    return String(value ?? "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
  }

  function text(value, fallback = "not available") {
    if (value === undefined || value === null || value === "") return fallback;
    if (typeof value === "boolean") return value ? "yes" : "no";
    return String(value);
  }

  function short(value, len = 18) {
    const raw = String(value || "");
    if (!raw) return "not available";
    return raw.length > len ? `${raw.slice(0, len)}...` : raw;
  }

  function verdictFor(analysis) {
    if (analysis?.verdict && typeof analysis.verdict === "object") return analysis.verdict;
    if (typeof analysis?.verdict === "string") {
      const value = analysis.verdict;
      const risk = value === "ALLOW_INFORMATIONAL" ? "green" : value === "BLOCK_RECOMMENDED" || value === "HIGH_RISK" ? "red" : value === "ALLOW_WITH_WARNINGS" || value === "REVIEW_REQUIRED" ? "yellow" : "grey";
      return { risk, label: value.replaceAll("_", " "), reasons: analysis?.verdictReasons || analysis?.reasons || [] };
    }
    return { risk: "grey", label: "Not enough evidence", reasons: ["missing_verdict"] };
  }

  function contractAddress(analysis) {
    return analysis?.contractAddress || analysis?.request?.to || analysis?.exactContractTrust?.contract_address || null;
  }

  function primaryScoreText(analysis) {
    const check = analysis?.transaction_check || {};
    if (check.final_transaction_action_score !== undefined && check.final_transaction_action_score !== null) {
      return `Function action ${check.final_transaction_action_score} / 100`;
    }
    const primary = analysis?.primaryProtocolScore || {};
    if (analysis?.externalIts || primary.family === "ITS" || analysis?.scoreFamily === "ITS") {
      const score = analysis?.score ?? primary.effective ?? analysis?.externalIts?.score;
      const max = analysis?.maxScore || primary.maximum || analysis?.externalIts?.maximum || 530;
      return `${analysis?.label || "External Trust Evidence"} ${text(score, "pending")} / ${max}`;
    }
    if (primary.family) return `${primary.family} ${text(primary.effective, "not scored")} / ${text(primary.maximum, "?")}`;
    if (analysis?.score === null || analysis?.score === undefined) return "not scored";
    return `${analysis.score}/${analysis.maxScore || 300}`;
  }

  function primaryFacts(analysis) {
    const approval = analysis?.approval || {};
    const exact = analysis?.exactContractTrust || {};
    const primary = analysis?.primaryProtocolScore || {};
    const deployed = analysis?.deployedCodeScore || {};
    const action = analysis?.action || {};
    const functionAction = analysis?.function_action || {};
    const transactionCheck = analysis?.transaction_check || {};
    return [
      ["Contract address", contractAddress(analysis)],
      ["Chain", analysis?.request?.chainId || exact?.chain_id],
      ["Protocol", analysis?.protocolName || exact?.protocol?.name || (analysis?.knownContract ? "Known protocol" : "Unknown")],
      ["Contract", [analysis?.contractName, analysis?.contractRole].filter(Boolean).join(" / ")],
      ["Version", analysis?.versionLabel || analysis?.publicScore?.versionLabel],
      ["Primary protocol score", primary.family || analysis?.externalIts ? primaryScoreText(analysis) : null],
      ["Primary finality", primary.finality],
      ["Deployed code score", deployed.maximum ? `${text(deployed.score, "not scored")} / ${deployed.maximum}` : null],
      ["Deployed match", deployed.matchState],
      ["Score", analysis?.score === null || analysis?.score === undefined ? null : `${analysis.score} / ${analysis.maxScore || 300}`],
      ["Badge", analysis?.badge],
      ["Audit", analysis?.auditStatus],
      ["Proxy/code", analysis?.proxyStatus],
      ["Code hash", analysis?.codeHash],
      ["Risk", analysis?.riskLevel || verdictFor(analysis).risk],
      ["Package action", action.displayName || action.type],
      ["Action source", action.sourceClassification || action.source],
      ["Action", analysis?.txType],
      ["Function", functionAction.function_signature || analysis?.functionName || analysis?.request?.functionSelector],
      ["Function action score", functionAction.score?.functionActionScore != null ? `${functionAction.score.functionActionScore} / 100` : null],
      ["Transaction action score", transactionCheck.final_transaction_action_score != null ? `${transactionCheck.final_transaction_action_score} / 100` : null],
      ["Function coverage", functionAction.audit_coverage?.coverageLevel || functionAction.audit_coverage?.coverage_level],
      ["Function match", analysis?.function_action_match_status],
      ["Description verified by", [functionAction.description_verified_by?.name, functionAction.description_verified_by?.twitter].filter(Boolean).join(" · ")],
      ["Dapp", analysis?.request?.domain],
      ["Approval spender", approval.spender],
      ["Approval token", approval.tokenAddress],
      ["Unlimited approval", approval.unlimited],
    ].filter(([, value]) => value !== undefined && value !== null && value !== "");
  }

  function evidenceFacts(analysis) {
    const exact = analysis?.exactContractTrust || {};
    const publicScore = analysis?.publicScore || {};
    const noExternalRecord = !analysis?.externalIts && analysis?.knownContract === false;
    return [
      ["External Trust Evidence", analysis?.externalIts ? "present" : noExternalRecord ? "No External ITS record found" : null],
      ["External ITS state", analysis?.externalIts?.scoreState],
      ["Audit provenance", analysis?.auditProvenance?.bestStatus || (noExternalRecord ? "No audit provenance found" : null)],
      ["Audit provenance scored", analysis?.auditProvenance ? "no" : null],
      ["Scope status", analysis?.scopeStatus],
      ["Match status", analysis?.auditProvenance?.matchStatus],
      ["Codehash status", analysis?.codeHashStatus],
      ["Admin risk", analysis?.adminRisk],
      ["Exit risk", analysis?.exitRisk],
      ["Missing proof", Array.isArray(analysis?.missingProof) ? analysis.missingProof.length : null],
      ["Comments scored", analysis?.externalIts ? "no" : null],
      ["External ITS page", analysis?.detailUrl],
      ["Known in deployed DB", analysis?.knownContract],
      ["Score applies to current code", analysis?.scoreAppliesToCurrentCode],
      ["Coverage", analysis?.coverage],
      ["Reviewed at", publicScore.reviewedAt],
      ["Review status", publicScore.reviewStatus],
      ["Code hash type", analysis?.codeHashKind || publicScore.codeHashKind],
      ["Exact audited deployment", exact.exact_audited_deployment],
      ["Trust passport", exact.protocol?.public_id],
      ["Deployment review", exact.deployment_review_status],
      ["Deployment registry hash", exact.deployment_registry?.deployment_registry_hash],
      ["Authority registry", exact.authority_registry?.authority_status || exact.authority_registry?.status],
      ["Sentinel", exact.sentinel_status?.status || exact.sentinel_status],
      ["Manual registry tx", exact.manual_publication?.registry_tx_hash],
      ["Explorer", analysis?.explorerUrl],
      ["VeerSec proof", analysis?.detailUrl],
    ].filter(([, value]) => value !== undefined && value !== null && value !== "");
  }

  function externalSummaryFacts(analysis) {
    const noExternalRecord = !analysis?.externalIts && analysis?.knownContract === false;
    if (!analysis?.externalIts && !noExternalRecord) return [];
    return [
      ["Label", analysis?.label || (noExternalRecord ? "No External ITS record found" : "External Trust Evidence")],
      ["Score family", analysis?.scoreFamily || analysis?.primaryProtocolScore?.family || "ITS"],
      ["Score type", analysis?.scoreType || analysis?.primaryProtocolScore?.type || "ITS"],
      ["Score", analysis?.externalIts ? `${text(analysis?.score ?? analysis.externalIts?.score, "pending")} / ${analysis?.maxScore || analysis.externalIts?.maximum || 530}` : "pending"],
      ["Score state", analysis?.scoreState || analysis?.externalIts?.scoreState],
      ["Audit provenance", analysis?.auditProvenance?.bestStatus || (noExternalRecord ? "No audit provenance found" : null)],
      ["Scope", analysis?.scopeStatus],
      ["Match", analysis?.auditProvenance?.matchStatus],
      ["Code hash", analysis?.codeHashStatus],
      ["Admin risk", analysis?.adminRisk],
      ["Exit risk", analysis?.exitRisk],
      ["Missing proof", Array.isArray(analysis?.missingProof) ? `${analysis.missingProof.length} items` : null],
      ["Passport", analysis?.passportUrl || analysis?.detailUrl],
    ].filter(([, value]) => value !== undefined && value !== null && value !== "");
  }

  function renderFacts(facts) {
    return facts.map(([label, value]) => `
      <div class="kv">
        <span>${esc(label)}</span>
        <strong>${esc(text(value))}</strong>
      </div>
    `).join("");
  }

  function renderReasons(analysis) {
    const reasons = (analysis?.reasons || verdictFor(analysis).reasons || []).slice(0, 10);
    if (reasons.length === 0) return "<li>No verified reason was returned.</li>";
    return reasons.map((reason) => `<li>${esc(reason)}</li>`).join("");
  }

  function renderInvestorFlow(analysis) {
    const functionFlow = analysis?.function_action?.plain_english_flow || [];
    if (Array.isArray(functionFlow) && functionFlow.length > 0) {
      return `<ol>${functionFlow.slice(0, 8).map((step) => `<li>${esc(step)}</li>`).join("")}</ol>`;
    }
    const flow = analysis?.investorFlow?.graph || analysis?.action?.flowGraph || [];
    if (!Array.isArray(flow) || flow.length === 0) return "<p class=\"muted-copy\">No package flow graph returned for this request.</p>";
    return `<ol>${flow.slice(0, 8).map((step) => `<li>${esc(step.label || step)}</li>`).join("")}</ol>`;
  }

  function renderFunctionTrust(analysis) {
    const fn = analysis?.function_action;
    const check = analysis?.transaction_check || {};
    if (!fn) {
      const status = analysis?.function_action_match_status || "UNKNOWN_SELECTOR";
      return `
        <h3>Function action</h3>
        <div class="flow-box">
          <p class="muted-copy">${esc(status === "UNKNOWN_SELECTOR" ? "Unknown function selector. VeerSec has no verified explanation for this exact transaction." : status)}</p>
          ${analysis?.function_action_warning ? `<p class="warning">${esc(analysis.function_action_warning)}</p>` : ""}
        </div>
      `;
    }
    const auditors = Array.isArray(fn.audited_by) ? fn.audited_by : [];
    const paramRisks = Array.isArray(check.parameter_risks) ? check.parameter_risks : [];
    return `
      <h3>Function action</h3>
      <div class="detail-grid">
        ${renderFacts([
          ["Function", fn.function_signature],
          ["Base action score", fn.score?.functionActionScore != null ? `${fn.score.functionActionScore} / 100` : null],
          ["Transaction score", check.final_transaction_action_score != null ? `${check.final_transaction_action_score} / 100` : null],
          ["Parameter risk", check.risk_level],
          ["Coverage", fn.audit_coverage?.coverageLevel || fn.audit_coverage?.coverage_level],
          ["Verified by", [fn.description_verified_by?.name, fn.description_verified_by?.twitter].filter(Boolean).join(" · ")],
        ])}
      </div>
      <p class="warning">${esc(fn.investor_summary || "No verified summary returned.")}</p>
      ${paramRisks.length ? `<ul>${paramRisks.map((risk) => `<li>${esc(risk.explanation || risk.code)}</li>`).join("")}</ul>` : ""}
      <h3>3 month watch</h3>
      <p class="warning">${esc(fn.three_month_impact?.summary || "No 3 month impact summary published.")}</p>
      <h3>1 year watch</h3>
      <p class="warning">${esc(fn.one_year_impact?.summary || "No 1 year impact summary published.")}</p>
      <h3>Who checked this function</h3>
      ${auditors.length ? `<div class="detail-grid">${renderFacts(auditors.slice(0, 8).map((auditor) => [
        `${auditor.level || "auditor"} ${auditor.tier || ""}`.trim(),
        [auditor.name, auditor.twitter, auditor.role].filter(Boolean).join(" · "),
      ]))}</div>` : `<p class="muted-copy">No auditor layer list was returned for this function.</p>`}
    `;
  }

  function renderRuntimeCollectors(analysis) {
    const collectors = analysis?.runtimeData?.collectors || [];
    if (!Array.isArray(collectors) || collectors.length === 0) return "<p class=\"muted-copy\">No runtime collector requirements returned.</p>";
    return collectors.slice(0, 8).map((collector) => `
      <div class="kv">
        <span>${esc(collector.collector || "collector")}</span>
        <strong>${esc(text(collector.status))}</strong>
      </div>
    `).join("");
  }

  function summaryTitle(analysis) {
    if (analysis?.protocolName) return analysis.protocolName;
    if (contractAddress(analysis)) return analysis?.knownContract ? "Known contract" : "Unknown Contract";
    return analysis?.warningTitle || "Waiting for contract";
  }

  function summarySubtitle(analysis) {
    const address = contractAddress(analysis);
    if (address) return short(address, 22);
    return analysis?.request?.method === "eth_requestAccounts" ? "Wallet connected, no contract interaction yet" : "No transaction target yet";
  }

  function renderStatusPanel(analysis) {
    latestAnalysis = analysis || latestAnalysis;
    if (!latestAnalysis) return;

    if (!statusHost) {
      statusHost = document.createElement("div");
      statusHost.dataset.veersecGuard = "status";
      statusHost.style.cssText = "all:initial;position:fixed;right:16px;bottom:16px;z-index:2147483646;";
      statusHost.attachShadow({ mode: "open" });
      (document.documentElement || document.body).appendChild(statusHost);
    }

    const root = statusHost.shadowRoot;
    const verdict = verdictFor(latestAnalysis);
    const tone = color[verdict.risk] || color.grey;
    const score = primaryScoreText(latestAnalysis);
    const externalFacts = externalSummaryFacts(latestAnalysis);
    const detailLink = latestAnalysis?.detailUrl ? `
      <a class="proof-link" href="${esc(latestAnalysis.detailUrl)}" target="_blank" rel="noreferrer">Open full proof</a>
    ` : "";
    const detailView = detailsOpen ? `
      <div class="detail-backdrop">
        <section class="detail-page" role="dialog" aria-modal="true" aria-label="VeerSec contract details">
          <header>
            <div>
              <p class="eyebrow">VEERSEC CONTRACT SHIELD</p>
              <h2>${esc(summaryTitle(latestAnalysis))}</h2>
              <p class="address">${esc(summarySubtitle(latestAnalysis))}</p>
            </div>
            <button class="icon-button" data-action="close-detail" aria-label="Close details">x</button>
          </header>
          <div class="score-strip" style="border-color:${tone}">
            <div><span>Risk</span><strong style="color:${tone}">${esc(text(latestAnalysis?.riskLevel || verdict.risk))}</strong></div>
            <div><span>Score</span><strong>${esc(score)}</strong></div>
            <div><span>Badge</span><strong>${esc(text(latestAnalysis?.badge))}</strong></div>
            <div><span>Proxy/code</span><strong>${esc(text(latestAnalysis?.proxyStatus))}</strong></div>
          </div>
          <div class="detail-actions">
            ${detailLink}
            ${latestAnalysis?.explorerUrl ? `<a class="proof-link muted" href="${esc(latestAnalysis.explorerUrl)}" target="_blank" rel="noreferrer">Explorer</a>` : ""}
          </div>
          ${externalFacts.length > 0 ? `
            <h3>External Trust Evidence</h3>
            <div class="detail-grid">${renderFacts(externalFacts)}</div>
          ` : ""}
          ${renderFunctionTrust(latestAnalysis)}
          <h3>Main contract details</h3>
          <div class="detail-grid">${renderFacts(primaryFacts(latestAnalysis))}</div>
          <h3>Action flow</h3>
          <div class="flow-box">${renderInvestorFlow(latestAnalysis)}</div>
          <h3>Runtime required</h3>
          <div class="detail-grid">${renderRuntimeCollectors(latestAnalysis)}</div>
          <h3>Evidence and publication state</h3>
          <div class="detail-grid">${renderFacts(evidenceFacts(latestAnalysis))}</div>
          <h3>Reasons</h3>
          <ul>${renderReasons(latestAnalysis)}</ul>
          ${latestAnalysis?.warningText ? `<p class="warning">${esc(latestAnalysis.warningText)}</p>` : ""}
          ${latestAnalysis?.recommendation ? `<p class="recommendation">${esc(latestAnalysis.recommendation)}</p>` : ""}
        </section>
      </div>
    ` : "";

    root.innerHTML = `
      <style>
        :host{all:initial}
        *{box-sizing:border-box;font-family:Inter,Arial,sans-serif;letter-spacing:0}
        .summary{width:320px;max-width:calc(100vw - 32px);border:1px solid #2B394E;border-left:4px solid ${tone};background:#070B12;color:#F8FBFF;box-shadow:0 18px 48px rgba(2,6,14,.52);padding:12px;text-align:left;cursor:pointer}
        .top{display:flex;align-items:flex-start;justify-content:space-between;gap:10px}
        .eyebrow{margin:0;color:#92C2FF;font-size:10px;font-weight:900;text-transform:uppercase}
        .title{margin:5px 0 0;color:#F8FBFF;font-size:14px;font-weight:900;line-height:1.2}
        .sub{margin:5px 0 0;color:#94A3B8;font-size:11px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}
        .pill{border:1px solid #2B394E;color:${tone};font-size:10px;font-weight:900;text-transform:uppercase;padding:4px 6px;white-space:nowrap}
        .mini-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px;margin-top:10px}
        .mini-grid div{border:1px solid #1D2A3D;background:#0D1420;padding:7px}
        .mini-grid span,.kv span,.score-strip span{display:block;color:#5C6B80;font-size:9px;text-transform:uppercase;font-weight:900}
        .mini-grid strong,.kv strong,.score-strip strong{display:block;margin-top:3px;color:#F8FBFF;font-size:11px;font-weight:900;overflow-wrap:anywhere}
        .summary-actions{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:10px}
        .hint{color:#5C6B80;font-size:10px}
        .hide{border:0;background:transparent;color:#94A3B8;font-size:11px;font-weight:800;cursor:pointer;padding:4px}
        .detail-backdrop{position:fixed;inset:0;background:rgba(7, 11, 18,.86);display:grid;place-items:center;padding:18px;color:#F8FBFF}
        .detail-page{width:min(920px,100%);max-height:min(760px,calc(100vh - 36px));overflow:auto;border:1px solid #2B394E;border-top:4px solid ${tone};background:#070B12;box-shadow:0 26px 90px rgba(2,6,14,.68);padding:20px}
        header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}
        h2{margin:6px 0 0;color:#F8FBFF;font-size:24px;line-height:1.1;font-weight:900}
        h3{margin:18px 0 10px;color:#F8FBFF;font-size:12px;text-transform:uppercase;font-weight:900}
        .address{margin:7px 0 0;color:#94A3B8;font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}
        .icon-button{width:34px;height:34px;border:1px solid #2B394E;background:#0D1420;color:#F8FBFF;font-size:16px;font-weight:900;cursor:pointer}
        .score-strip{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px;margin-top:16px;border-left:4px solid;padding-left:10px}
        .score-strip div,.kv{border:1px solid #2B394E;background:#0D1420;padding:10px}
        .detail-actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}
        .proof-link{display:inline-flex;align-items:center;justify-content:center;border:1px solid #22D3EE;background:#083344;color:#F8FBFF;text-decoration:none;padding:8px 10px;font-size:11px;font-weight:900}
        .proof-link.muted{border-color:#2B394E;background:#0D1420;color:#D7E0EC}
        .detail-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
        .flow-box{border:1px solid #2B394E;background:#0D1420;padding:10px}
        ul{margin:0;padding-left:20px;color:#D7E0EC;font-size:12px;line-height:1.55}
        ol{margin:0;padding-left:20px;color:#D7E0EC;font-size:12px;line-height:1.55}
        .muted-copy{margin:0;color:#5C6B80;font-size:12px}
        .warning,.recommendation{margin:12px 0 0;border:1px solid #2B394E;background:#0D1420;color:#D7E0EC;padding:10px;font-size:12px;line-height:1.45}
        .recommendation{color:#F8FBFF}
        button:focus,a:focus{outline:2px solid #67E8F9;outline-offset:2px}
        @media (max-width:680px){
          .summary{width:calc(100vw - 24px)}
          .score-strip,.detail-grid{grid-template-columns:1fr}
          .detail-page{padding:16px}
        }
      </style>
      <button class="summary" data-action="details" type="button" aria-label="Open VeerSec contract details">
        <div class="top">
          <div>
            <p class="eyebrow">VeerSec live lookup</p>
            <p class="title">${esc(summaryTitle(latestAnalysis))}</p>
            <p class="sub">${esc(summarySubtitle(latestAnalysis))}</p>
          </div>
          <span class="pill">${esc(text(latestAnalysis?.riskLevel || verdict.risk))}</span>
        </div>
        <div class="mini-grid">
          <div><span>Score</span><strong>${esc(score)}</strong></div>
          <div><span>Evidence</span><strong>${esc(text(latestAnalysis?.label || latestAnalysis?.badge))}</strong></div>
          <div><span>Proxy</span><strong>${esc(text(latestAnalysis?.proxyStatus))}</strong></div>
        </div>
        <div class="summary-actions">
          <span class="hint">Click for contract details</span>
          <span class="hide" data-action="hide-panel">Hide</span>
        </div>
      </button>
      ${detailView}
    `;

    root.querySelector("[data-action=details]")?.addEventListener("click", () => {
      detailsOpen = true;
      renderStatusPanel(latestAnalysis);
    });
    root.querySelector("[data-action=hide-panel]")?.addEventListener("click", (event) => {
      event.stopPropagation();
      statusHost?.remove();
      statusHost = null;
      detailsOpen = false;
    });
    root.querySelector("[data-action=close-detail]")?.addEventListener("click", () => {
      detailsOpen = false;
      renderStatusPanel(latestAnalysis);
    });
  }

  function showDecision(requestId, analysis) {
    renderStatusPanel(analysis);
    const verdict = verdictFor(analysis);
    if (verdict.risk === "green" && verdict.action === "allow") {
      respond(requestId, true, analysis);
      return;
    }
    const host = document.createElement("div");
    host.dataset.veersecGuard = "decision";
    host.style.cssText = "all:initial;position:fixed;inset:0;z-index:2147483647;";
    const root = host.attachShadow({ mode: "open" });
    const factsHtml = renderFacts(primaryFacts(analysis).slice(0, 8));
    const detailLink = analysis?.detailUrl ? `<a class="proof-link" href="${esc(analysis.detailUrl)}" target="_blank" rel="noreferrer">Open full proof</a>` : "";
    root.innerHTML = `
      <style>
        .backdrop{position:fixed;inset:0;background:rgba(7, 11, 18,.82);display:grid;place-items:center;padding:20px;font-family:Inter,Arial,sans-serif;color:#F8FBFF}
        .panel{width:min(620px,100%);background:#070B12;border:1px solid #2B394E;border-top:4px solid ${color[verdict.risk] || color.grey};box-shadow:0 24px 80px rgba(2,6,14,.6);padding:22px}
        .brand{font-size:12px;font-weight:800;color:#92C2FF;letter-spacing:0}.title{font-size:22px;font-weight:800;margin:8px 0}.risk{color:${color[verdict.risk] || color.grey};text-transform:uppercase;font-size:12px;font-weight:800}
        .facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin:16px 0}.kv{border:1px solid #2B394E;background:#0D1420;padding:10px}.kv span{display:block;color:#5C6B80;font-size:10px;text-transform:uppercase;font-weight:800}.kv strong{display:block;color:#F8FBFF;font-size:13px;margin-top:4px;overflow-wrap:anywhere}
        ul{padding-left:20px;color:#D7E0EC;font-size:13px;line-height:1.6}.privacy{font-size:11px;color:#5C6B80;border-top:1px solid #2B394E;padding-top:12px;margin-top:14px}
        .proof-link{display:inline-flex;border:1px solid #22D3EE;background:#083344;color:#F8FBFF;text-decoration:none;padding:9px 11px;font-size:11px;font-weight:900}
        .actions{display:flex;justify-content:flex-end;align-items:center;gap:8px;margin-top:18px}button{border:1px solid #2B394E;background:#0D1420;color:#F8FBFF;padding:10px 14px;font-weight:700;cursor:pointer}
        button.primary{background:${color[verdict.risk] || color.grey};border-color:${color[verdict.risk] || color.grey};color:#FFFFFF}button:focus,a:focus{outline:2px solid #67E8F9;outline-offset:2px}
        @media (max-width:640px){.facts{grid-template-columns:1fr}.actions{flex-wrap:wrap;justify-content:flex-start}}
      </style>
      <div class="backdrop" role="dialog" aria-modal="true" aria-label="VeerSec transaction decision">
        <div class="panel">
          <div class="brand">VEERSEC CONTRACT SHIELD</div>
          <div class="risk">${esc(analysis?.riskLevel || verdict.risk)}</div>
          <div class="title">${esc(verdict.label || analysis?.warningTitle || "Wallet request check")}</div>
          <div class="facts">${factsHtml}</div>
          ${analysis?.warningText ? `<p style="color:#bac8d5;font-size:13px;line-height:1.5;margin:0 0 10px">${esc(analysis.warningText)}</p>` : ""}
          <ul>${renderReasons(analysis)}</ul>
          <div class="privacy">Wallet address, calldata, messages, signatures, and raw simulation requests are not persisted by VeerSec.</div>
          <div class="actions">
            ${detailLink}
            <button data-action="cancel">Cancel</button>
            <button class="primary" data-action="continue">${verdict.requires_explicit_override ? "Override and continue" : "Continue"}</button>
          </div>
        </div>
      </div>`;
    const finish = (allow) => {
      host.remove();
      respond(requestId, allow, analysis);
    };
    root.querySelector("[data-action=cancel]").addEventListener("click", () => finish(false));
    root.querySelector("[data-action=continue]").addEventListener("click", () => finish(true));
    (document.documentElement || document.body).appendChild(host);
  }

  window.addEventListener("veersec:analyze-request", (event) => {
    const detail = event.detail || {};
    chrome.runtime.sendMessage({ type: "veersec:analyze", payload: detail }, (analysis) => {
      const fallback = chrome.runtime.lastError
        ? { verdict: { risk: "grey", label: "Not enough evidence", action: "confirm", reasons: [chrome.runtime.lastError.message] } }
        : analysis;
      showDecision(detail.requestId, fallback);
    });
  });
})();
