/**
 * zeq-page-bridge.js — isolated-world relay for window.zeq (KP.1).
 *
 * Runs in the content-script (ISOLATED) world, so it has chrome.runtime access
 * that the page's main world doesn't. It listens for the page API's
 * window.postMessage requests, forwards them to the service worker (which holds
 * the auth token and bypasses CORS), and posts the sanitized result back to the
 * page. The page never gets chrome.runtime or the token — only the result.
 *
 * @version 1.287.13
 * @license CC BY 4.0 — Zeq. H / Zeq 1.287 Hz Limited
 */
(() => {
  "use strict";
  if (window.__zeqBridgeInstalled) return;
  window.__zeqBridgeInstalled = true;

  const ALLOWED = new Set(["compute", "solve", "multibody", "lattice", "shift", "prove", "verify", "pulse", "operators", "modulate"]);

  window.addEventListener("message", (e) => {
    if (e.source !== window) return;
    const d = e.data;
    if (!d || d.__zeq_req !== true || typeof d.id !== "string") return;
    const reply = (payload) => { try { window.postMessage(Object.assign({ __zeq_res: true, id: d.id }, payload), window.location.origin); } catch (_) {} };
    if (!ALLOWED.has(d.method)) { reply({ ok: false, error: "zeq: unknown method " + d.method }); return; }
    try {
      // origin:"page" lets the SW rate-limit page-originated metered calls so a
      // granted site can't silently drain the user's ZEQ balance.
      chrome.runtime.sendMessage({ type: "physics", method: d.method, args: d.args || {}, origin: "page" }, (r) => {
        const lastErr = chrome.runtime.lastError;
        if (lastErr || !r) { reply({ ok: false, error: (lastErr && lastErr.message) || "zeq: extension bridge unavailable" }); return; }
        reply({ ok: !!r.success, status: r.status, data: r.data, error: r.error });
      });
    } catch (ex) { reply({ ok: false, error: "zeq: " + (ex && ex.message || ex) }); }
  });
})();
