/**
 * Zeq Security Check — point the ZeqVM encryption stack at the page you're on.
 *
 * Collects REAL, checkable security signals from the current site (is the
 * connection encrypted, mixed content, password fields, where forms POST,
 * third-party scripts, cross-origin frames, risky links) and sends them to the
 * ZSP scorer, which returns a verdict and SEALS it with a ZSP envelope
 * (CS47 spectral entropy + NM26 HF scan + K_temporal HMAC) — so the verdict is
 * tamper-evident and Zeqond-stamped. Same encryption machinery that protects
 * your data, used here as a security checker.
 *
 * Honest by construction: every check maps to something observed on THIS page.
 * No external "threat feed", no made-up reputation score.
 *
 * @version 1.287.7
 * @license CC BY 4.0 — Zeq. H / Zeq 1.287 Hz Limited
 */
(() => {
  "use strict";
  if (document.getElementById("zeq-seccheck-root")) { document.getElementById("zeq-seccheck-root").remove(); return; }

  function sw(msg) { return new Promise((res) => { try { chrome.runtime.sendMessage(msg, (r) => res(chrome.runtime.lastError ? null : r)); } catch (_) { res(null); } }); }
  const pageHost = location.hostname.replace(/^www\./, "");
  const sameHost = (h) => { try { return h.replace(/^www\./, "") === pageHost; } catch (_) { return false; } };
  const hostOf = (u) => { try { return new URL(u, location.href).hostname; } catch (_) { return ""; } };

  // ── Collect real signals ───────────────────────────────────────────────────
  function collect() {
    const https = location.protocol === "https:";
    const pw = !!document.querySelector("input[type=password]");

    let mixed = 0;
    if (https) {
      document.querySelectorAll("img[src],script[src],link[href],iframe[src],audio[src],video[src],source[src]").forEach((el) => {
        const v = el.getAttribute("src") || el.getAttribute("href") || "";
        if (/^http:\/\//i.test(v)) mixed++;
      });
    }

    const tp = new Set();
    document.querySelectorAll("script[src]").forEach((s) => { const h = hostOf(s.src); if (h && !sameHost(h)) tp.add(h); });

    const extForms = [];
    document.querySelectorAll("form").forEach((f) => {
      const action = f.getAttribute("action") || "";
      const ah = hostOf(action || location.href);
      if (ah && !sameHost(ah)) {
        extForms.push({ action_host: ah, has_password: !!f.querySelector("input[type=password]"), insecure: /^http:\/\//i.test(action) });
      }
    });

    let xframes = 0;
    document.querySelectorAll("iframe[src]").forEach((f) => { const h = hostOf(f.src); if (h && !sameHost(h)) xframes++; });

    const risky = [];
    document.querySelectorAll("a[href]").forEach((a) => {
      const href = a.getAttribute("href") || "";
      if (/^javascript:/i.test(href)) risky.push({ href: href.slice(0, 80), reason: "javascript" });
      else { const h = hostOf(href); if (/xn--/i.test(h)) risky.push({ href: h, reason: "punycode" }); }
    });

    return {
      url: location.href, host: pageHost, https,
      mixed_content_count: mixed, password_field: pw, password_on_http: pw && !https,
      total_scripts: document.querySelectorAll("script[src]").length,
      third_party_script_hosts: Array.from(tp).slice(0, 40),
      total_forms: document.querySelectorAll("form").length,
      external_forms: extForms.slice(0, 20),
      cross_origin_iframe_count: xframes,
      risky_links: risky.slice(0, 20),
    };
  }

  // ── Panel ────────────────────────────────────────────────────────────────
  const root = document.createElement("div");
  root.id = "zeq-seccheck-root";
  root.style.cssText = "position:fixed;top:16px;right:16px;z-index:2147483647;";
  const shadow = root.attachShadow({ mode: "open" });
  const VCOL = { SAFE: "#00ff88", CAUTION: "#ffd166", RISK: "#ff5577" };
  const SCOL = { pass: "#00ff88", warn: "#ffd166", fail: "#ff5577" };
  shadow.innerHTML = `
    <style>
      :host,*{box-sizing:border-box;}
      .w{width:330px;background:#05080d;color:#e8f5ee;border:1px solid #14301f;border-radius:12px;box-shadow:0 12px 40px rgba(0,0,0,.6);font-family:-apple-system,Inter,system-ui,sans-serif;overflow:hidden;}
      .bar{display:flex;align-items:center;gap:8px;padding:9px 11px;background:#0a1410;cursor:move;user-select:none;border-bottom:1px solid #14301f;}
      .mark{font-family:'JetBrains Mono',ui-monospace,monospace;font-weight:800;font-size:13px;background:linear-gradient(135deg,#fff,#00ff88);-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent;flex:1;}
      .x{background:none;border:none;color:#7fa791;cursor:pointer;font-size:15px;line-height:1;}
      .body{padding:12px;}
      .host{font-size:11px;color:#7fa791;margin-bottom:10px;word-break:break-all;}.host b{color:#00ff88;}
      .verdict{display:flex;align-items:baseline;gap:10px;margin-bottom:10px;}
      .vbig{font-size:24px;font-weight:800;letter-spacing:.02em;}
      .score{font-family:'JetBrains Mono',monospace;font-size:12px;color:#8fb8a2;}
      .checks{display:flex;flex-direction:column;gap:5px;}
      .chk{display:flex;gap:8px;align-items:flex-start;font-size:11.5px;line-height:1.4;border:1px solid #14301f;border-radius:7px;padding:7px 8px;background:rgba(255,255,255,.015);}
      .dot{width:8px;height:8px;border-radius:50%;flex:0 0 auto;margin-top:4px;}
      .chk b{color:#e8f5ee;font-weight:600;}.chk span{color:#8fb8a2;}
      .seal{margin-top:10px;font-size:9.5px;color:#4d6b59;font-family:'JetBrains Mono',monospace;line-height:1.5;border-top:1px solid #14301f;padding-top:8px;word-break:break-all;}
      .seal b{color:#00ff88;}
      .loading{font-size:12px;color:#8fb8a2;}
      .btn{width:100%;margin-top:9px;padding:8px;border-radius:8px;border:1px solid #14301f;background:transparent;color:#e8f5ee;font-size:11.5px;cursor:pointer;}
      .btn:hover{border-color:#00ff88;color:#00ff88;}
    </style>
    <div class="w">
      <div class="bar" id="bar"><span class="mark">ZeqVM security check</span><button class="x" id="x">✕</button></div>
      <div class="body" id="body"><div class="loading">Scanning <b>${pageHost}</b> through the ZSP analyzer…</div></div>
    </div>`;
  document.documentElement.appendChild(root);
  const $ = (id) => shadow.getElementById(id);
  $("x").addEventListener("click", () => root.remove());
  (() => { const bar = $("bar"); let sx, sy, ox, oy, drag = false;
    bar.addEventListener("mousedown", (e) => { drag = true; sx = e.clientX; sy = e.clientY; const r = root.getBoundingClientRect(); ox = r.left; oy = r.top; e.preventDefault(); });
    window.addEventListener("mousemove", (e) => { if (!drag) return; root.style.left = (ox + e.clientX - sx) + "px"; root.style.top = (oy + e.clientY - sy) + "px"; root.style.right = "auto"; });
    window.addEventListener("mouseup", () => { drag = false; });
  })();

  function esc(s) { return String(s == null ? "" : s).replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" }[c])); }

  function render(d) {
    if (!d) { $("body").innerHTML = '<div class="loading" style="color:#ff5577">Scan failed — try again.</div>'; return; }
    const vcol = VCOL[d.verdict] || "#8fb8a2";
    const checks = (d.checks || []).map((c) =>
      '<div class="chk"><span class="dot" style="background:' + (SCOL[c.status] || "#8fb8a2") + '"></span><div><b>' + esc(c.label) + "</b><br><span>" + esc(c.detail) + "</span></div></div>"
    ).join("") || '<div class="chk"><span class="dot" style="background:#00ff88"></span><div><span>No issues detected in the signals we can read.</span></div></div>';
    const seal = d.seal
      ? '<div class="seal">ZSP-sealed · z<b>' + esc(d.seal.zeqond_stamp) + "</b> · entropy " + esc(d.seal.spectral_entropy) +
        " (CS47) · HF " + (d.seal.hf_clean ? "clean" : "flag") + " (NM26)<br>tag " + esc(String(d.seal.temporal_tag).slice(0, 32)) + "…</div>"
      : "";
    const recorded = d.recorded
      ? '<div class="seal" style="border-top:none;padding-top:2px">▲ recorded to your Observer (tamper-evident)</div>'
      : "";
    $("body").innerHTML =
      '<div class="host">Checked <b>' + esc(d.host || pageHost) + "</b></div>" +
      '<div class="verdict"><span class="vbig" style="color:' + vcol + '">' + esc(d.verdict) + '</span><span class="score">' + esc(String(d.score)) + "/100</span></div>" +
      '<div class="checks">' + checks + "</div>" + seal + recorded +
      '<button class="btn" id="rescan">Re-scan</button>';
    const rs = $("rescan"); if (rs) rs.addEventListener("click", run);
  }

  async function run() {
    $("body").innerHTML = '<div class="loading">Scanning <b>' + esc(pageHost) + "</b> through the ZSP analyzer…</div>";
    const signals = collect();
    const r = await sw({ type: "securityScan", signals });
    if (r && r.success && r.data) render(r.data);
    else render(null);
  }
  run();
})();
