/**
 * zeq-compute-widget.js — a visible ZeqVM compute box on any page (KP.5).
 *
 * Injected (ISOLATED world, so it has chrome.runtime) alongside the window.zeq
 * bridge. Gives non-developers a draggable compute panel right on the page:
 * pick an operator, enter physical inputs, get value · unit · signed ZeqProof,
 * and verify it — all against the user's machine via the SW physics bridge.
 * A footer note tells developers window.zeq is also live for scripting.
 *
 * @version 1.287.17
 * @license CC BY 4.0 — Zeq. H / Zeq 1.287 Hz Limited
 */
(() => {
  "use strict";
  if (document.getElementById("zeq-compute-root")) { document.getElementById("zeq-compute-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 root = document.createElement("div");
  root.id = "zeq-compute-root";
  root.style.cssText = "position:fixed;top:16px;right:16px;z-index:2147483647;";
  const shadow = root.attachShadow({ mode: "open" });
  shadow.innerHTML = `
    <style>
      :host,*{box-sizing:border-box;}
      .w{width:300px;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;}
      .body{padding:11px;}
      .h{font-size:10px;letter-spacing:.08em;text-transform:uppercase;color:#4d6b59;margin:0 0 4px;}
      .in{width:100%;padding:7px 9px;background:rgba(0,0,0,.5);border:1px solid #14301f;border-radius:7px;color:#e8f5ee;font-size:12px;outline:none;margin-bottom:6px;font-family:inherit;}
      .in:focus{border-color:#00ff88;}
      .row{display:flex;gap:6px;}
      .btn{width:100%;padding:9px;border-radius:8px;border:1px solid #00ff88;background:#00ff88;color:#02120a;font-weight:700;font-size:12px;cursor:pointer;}
      .btn:disabled{opacity:.5;}
      .val{font-family:'JetBrains Mono',monospace;font-size:22px;font-weight:800;color:#00ff88;word-break:break-all;margin-top:8px;}
      .unit{font-size:13px;color:#8fb8a2;}
      .eq{font-size:10px;color:#8fb8a2;margin-top:4px;font-family:'JetBrains Mono',monospace;word-break:break-word;}
      .proof{font-size:9px;color:#4d6b59;font-family:'JetBrains Mono',monospace;margin-top:6px;word-break:break-all;}.proof b{color:#00ff88;}
      .err{font-size:11px;color:#ff8a8a;margin-top:8px;line-height:1.4;}
      .vbadge{font-size:10px;font-weight:700;padding:2px 7px;border-radius:5px;margin-left:6px;}
      .vbadge.ok{background:rgba(0,255,136,.15);color:#00ff88;}.vbadge.bad{background:rgba(255,120,120,.15);color:#ff8a8a;}
      .foot{font-size:9px;color:#3d5a49;margin-top:9px;border-top:1px solid #14301f;padding-top:7px;font-family:'JetBrains Mono',monospace;}
    </style>
    <div class="w">
      <div class="bar" id="bar"><span class="mark">ZeqVM compute</span><button class="x" id="x">✕</button></div>
      <div class="body">
        <div class="h">Operator(s)</div>
        <input class="in" id="ops" value="KO42" placeholder="KO42, NM19, …">
        <div class="h">Inputs</div>
        <div class="row"><input class="in" id="k1" value="mass" placeholder="name"><input class="in" id="v1" value="1" placeholder="value"></div>
        <div class="row"><input class="in" id="k2" value="acceleration" placeholder="name"><input class="in" id="v2" value="9.8" placeholder="value"></div>
        <button class="btn" id="run">Compute → ZeqProof</button>
        <div id="out"></div>
        <div class="foot">window.zeq is live on this page — call it from the console or your code.</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])); }

  let _last = null;
  async function run() {
    const btn = $("run"); btn.disabled = true; btn.textContent = "Computing…";
    const operators = ($("ops").value || "KO42").split(",").map((s) => s.trim()).filter(Boolean);
    const inputs = {};
    [["k1", "v1"], ["k2", "v2"]].forEach(([k, v]) => { const name = $(k).value.trim(); if (name) { const n = Number($(v).value); inputs[name] = Number.isFinite(n) && $(v).value !== "" ? n : $(v).value; } });
    const r = await sw({ type: "physics", method: "compute", args: { operators, inputs } });
    btn.disabled = false; btn.textContent = "Compute → ZeqProof";
    if (!r || !r.success) {
      const d = r && r.data; const msg = (d && d.error && (d.error.message || d.error)) || (r && r.error) || ("HTTP " + (r && r.status));
      _last = null; $("out").innerHTML = '<div class="err">' + esc(String(msg)) + "</div>"; return;
    }
    const d = r.data || {}; _last = d;
    $("out").innerHTML =
      '<div class="val">' + esc(String(d.value)) + ' <span class="unit">' + esc(d.unit || "") + "</span></div>" +
      (d.equation ? '<div class="eq">' + esc(d.equation) + "</div>" : "") +
      '<div class="proof">proof <b>' + esc(String(d.zeqProof || "").slice(0, 20)) + "…</b>" +
      (d.verify_claim ? ' <button class="x" id="vbtn" style="font-size:10px;color:#00ff88;cursor:pointer;background:none;border:1px solid #14301f;border-radius:5px;padding:1px 6px">verify</button>' : "") +
      '<span id="vb"></span></div>';
    const vbtn = $("vbtn");
    if (vbtn) vbtn.addEventListener("click", async () => {
      const claim = Object.assign({ proof: d.zeqProof }, d.verify_claim);
      const vr = await sw({ type: "physics", method: "verify", args: claim });
      const ok = vr && vr.success && vr.data && (vr.data.valid ?? vr.data.ok ?? vr.data.verified);
      const vb = $("vb"); if (vb) vb.innerHTML = '<span class="vbadge ' + (ok ? "ok" : "bad") + '">' + (ok ? "✓ VALID" : "✗") + "</span>";
    });
  }
  $("run").addEventListener("click", run);
})();
