/**
 * TrailTab — the consent-based browser audit trail surface (K3).
 *
 * Lets the user: turn capture on/off, opt specific hosts in (add the current
 * site, list, remove), view the encrypted hash-linked trail, verify its
 * integrity, anchor its head to their machine's entangled state, and clear it.
 * Nothing is captured unless capture is ON and the host is opted in.
 *
 * Depends on: window.ZeqTrail, window.ZeqConfig, window.ZeqAuth.
 *
 * @version 1.287.6
 * @license CC BY 4.0 — Zeq. H / Zeq 1.287 Hz Limited
 */
const TrailTab = (() => {
  "use strict";

  let _cid = null;
  let _activeHost = "";
  let _msg = "";

  function esc(s) { return String(s == null ? "" : s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c])); }
  function _authed() { return typeof ZeqAuth !== "undefined" && ZeqAuth.isAuthenticated(); }

  async function _currentHost() {
    try { const [t] = await chrome.tabs.query({ active: true, currentWindow: true }); if (t && t.url) return new URL(t.url).hostname.replace(/^www\./, ""); } catch (_) {}
    return "";
  }

  const STYLE = "<style>" +
    ".ztr-wrap{padding:12px;overflow-y:auto;height:100%}" +
    ".ztr-card{background:var(--bg-secondary);border:1px solid var(--border);border-radius:10px;padding:12px;margin-bottom:10px}" +
    ".ztr-row{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:6px}" +
    ".ztr-lbl{font-size:12px;color:var(--text-secondary)}" +
    ".ztr-toggle{font-size:12px;font-weight:700;border:1px solid var(--border);border-radius:7px;padding:6px 12px;cursor:pointer;background:transparent;color:var(--text-secondary)}" +
    ".ztr-toggle.on{border-color:var(--accent-mint);color:#02120a;background:var(--accent-mint)}" +
    ".ztr-btn{font-size:11px;border:1px solid var(--border);border-radius:7px;padding:6px 10px;cursor:pointer;background:transparent;color:var(--text-primary)}" +
    ".ztr-btn.primary{border-color:var(--accent-mint);color:var(--accent-mint)}" +
    ".ztr-h{font-size:10px;letter-spacing:.1em;text-transform:uppercase;color:var(--text-muted);margin:12px 0 4px}" +
    ".ztr-host{display:flex;justify-content:space-between;align-items:center;font-size:11.5px;padding:5px 0;border-bottom:1px solid var(--border)}" +
    ".ztr-x{cursor:pointer;color:var(--accent-red);font-size:12px;border:none;background:none}" +
    ".ztr-entry{font-size:10.5px;border:1px solid var(--border);border-radius:7px;padding:7px 8px;margin-bottom:5px;background:var(--bg-secondary)}" +
    ".ztr-entry .t{color:var(--text-primary);font-weight:600}" +
    ".ztr-entry .m{color:var(--text-muted);font-family:monospace;font-size:9.5px;word-break:break-all}" +
    ".ztr-msg{font-size:11px;color:var(--accent-mint);margin-bottom:8px;min-height:14px}" +
    ".ztr-note{font-size:10.5px;color:var(--text-muted);line-height:1.5}" +
    "</style>";

  async function _render() {
    const c = document.getElementById(_cid);
    if (!c) return;
    if (!_authed()) { c.innerHTML = STYLE + '<div class="ztr-wrap"><div class="ztr-card"><p class="ztr-note">Sign in to use the encrypted browser trail — it is keyed to your identity and can be anchored to your machine.</p></div></div>'; return; }

    _activeHost = await _currentHost();
    const consent = await ZeqTrail.getConsent();
    const hosts = Object.keys(consent.hosts || {});
    const entries = await ZeqTrail.read(40);
    const n = await ZeqTrail.count();
    const curAllowed = _activeHost && consent.hosts[_activeHost];

    c.innerHTML = STYLE + '<div class="ztr-wrap">' +
      (_msg ? '<div class="ztr-msg">' + esc(_msg) + "</div>" : "") +
      '<div class="ztr-card">' +
      '<div class="ztr-row"><span class="ztr-lbl"><strong>Capture</strong> — consent-based, encrypted, on your device</span>' +
      '<button class="ztr-toggle' + (consent.enabled ? " on" : "") + '" id="ztr-toggle">' + (consent.enabled ? "ON" : "OFF") + "</button></div>" +
      '<div class="ztr-row" style="margin-top:8px"><span class="ztr-lbl">Track <strong>everything</strong> (all sites + downloads)</span>' +
      '<button class="ztr-toggle' + (consent.mode === "all" ? " on" : "") + '" id="ztr-mode">' + (consent.mode === "all" ? "ALL" : "OPT-IN") + "</button></div>" +
      '<p class="ztr-note">' + (consent.mode === "all"
        ? "Track-all is ON: every page navigation and download is recorded while Capture is ON. AES-256-GCM encrypted under your identity, hash-linked. Switch to OPT-IN to record only chosen sites."
        : "Opt-in: only sites you add below are recorded while Capture is ON. Flip to ALL to track everything. Entries hold host, title, URL, kind and time, encrypted + hash-linked.") + "</p>" +
      "</div>" +

      '<div class="ztr-card">' +
      '<div class="ztr-row"><span class="ztr-lbl">This site: <strong>' + esc(_activeHost || "—") + "</strong></span>" +
      (_activeHost ? (curAllowed
        ? '<button class="ztr-btn" id="ztr-remove-cur">Stop recording</button>'
        : '<button class="ztr-btn primary" id="ztr-add-cur">Record this site</button>') : "") + "</div>" +
      '<div class="ztr-h">Opted-in sites (' + hosts.length + ")</div>" +
      (hosts.length ? hosts.map((h) => '<div class="ztr-host"><span>' + esc(h) + '</span><button class="ztr-x" data-host="' + esc(h) + '">remove</button></div>').join("") : '<p class="ztr-note">None yet.</p>') +
      "</div>" +

      '<div class="ztr-card">' +
      '<div class="ztr-row"><span class="ztr-lbl"><strong>Trail</strong> · ' + n + " entries</span><span>" +
      '<button class="ztr-btn" id="ztr-verify">Verify</button> ' +
      '<button class="ztr-btn primary" id="ztr-anchor">Anchor</button> ' +
      '<button class="ztr-btn" id="ztr-export">Export .ZEQ</button> ' +
      '<button class="ztr-btn" id="ztr-clear">Clear</button></span></div>' +
      (entries.length ? entries.map((e) =>
        '<div class="ztr-entry"><div class="t">' + esc(e.host) + ' <span style="color:var(--text-muted);font-weight:400">' + esc((e.title || "").slice(0, 60)) + "</span></div>" +
        '<div class="m">z' + esc(String(e.zeqond)) + " φ" + (typeof e.phase === "number" ? e.phase.toFixed(3) : "?") + " · " + esc(String(e.hash).slice(0, 16)) + "…</div></div>"
      ).join("") : '<p class="ztr-note">No entries yet. Turn Capture ON and opt a site in.</p>') +
      "</div></div>";

    _bind(c);
  }

  function _flash(m) { _msg = m; _render(); setTimeout(() => { if (_msg === m) { _msg = ""; _render(); } }, 3000); }

  function _bind(c) {
    c.querySelector("#ztr-toggle")?.addEventListener("click", async () => { const cs = await ZeqTrail.getConsent(); await ZeqTrail.setEnabled(!cs.enabled); _render(); });
    c.querySelector("#ztr-mode")?.addEventListener("click", async () => { const cs = await ZeqTrail.getConsent(); await ZeqTrail.setMode(cs.mode === "all" ? "optin" : "all"); _render(); });
    c.querySelector("#ztr-add-cur")?.addEventListener("click", async () => { await ZeqTrail.allowHost(_activeHost); _flash("Recording " + _activeHost); });
    c.querySelector("#ztr-remove-cur")?.addEventListener("click", async () => { await ZeqTrail.removeHost(_activeHost); _render(); });
    c.querySelectorAll(".ztr-x[data-host]").forEach((b) => b.addEventListener("click", async () => { await ZeqTrail.removeHost(b.getAttribute("data-host")); _render(); }));
    c.querySelector("#ztr-verify")?.addEventListener("click", async () => { const v = await ZeqTrail.verify(); _flash(v.ok ? "Chain intact ✓ (" + v.length + " entries)" : "Tamper detected at #" + v.brokenAt + " — " + v.reason); });
    c.querySelector("#ztr-clear")?.addEventListener("click", async () => { await ZeqTrail.clear(); _flash("Trail cleared"); });
    c.querySelector("#ztr-export")?.addEventListener("click", async () => {
      const entries = await ZeqTrail.read();
      if (!entries.length) { _flash("Nothing to export yet"); return; }
      if (typeof HiteCrypto === "undefined") { _flash("HITE crypto not loaded"); return; }
      const pin = window.prompt("Set a PIN (4+ chars) to encrypt the .ZEQ trail export:");
      if (!pin || pin.length < 4) { _flash("PIN must be 4+ characters"); return; }
      try {
        const payload = JSON.stringify({ kind: "zeq-trail", v: 1, exported: new Date().toISOString(), entries });
        const enc = await HiteCrypto.encrypt(payload, pin, "Zeq Trail");
        const blob = new Blob([enc.blob], { type: "application/octet-stream" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a"); a.href = url; a.download = "zeq-trail-" + Date.now() + ".zeq";
        document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url);
        _flash("Exported " + entries.length + " entries (HITE-encrypted)");
      } catch (ex) { _flash("Export failed: " + (ex.message || ex)); }
    });
    c.querySelector("#ztr-anchor")?.addEventListener("click", async () => {
      const head = await ZeqTrail.head();
      if (!head) { _flash("Nothing to anchor yet"); return; }
      const u = ZeqAuth.getUser(); const slug = u && u.zid ? String(u.zid).toLowerCase() : null;
      if (!slug) { _flash("Sign in first"); return; }
      try {
        const api = await ZeqConfig.api();
        const r = await fetch(api + "/chain/" + encodeURIComponent(slug) + "/event", {
          method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, ZeqAuth.getHeaders()),
          body: JSON.stringify({ type: "browser_trail_anchor", hash: head }),
        });
        const j = await r.json().catch(() => ({}));
        if (!r.ok) throw new Error(j.error_description || j.error || ("Anchor failed (" + r.status + ")"));
        _flash("Anchored to " + slug + " ✓ — head " + head.slice(0, 12) + "…");
      } catch (ex) { _flash(ex.message || "Anchor failed"); }
    });
  }

  function init(cid) { _cid = cid; _msg = ""; _render(); }
  return { init };
})();

if (typeof module !== "undefined" && module.exports) { module.exports = TrailTab; }
