/**
 * Zeq Interceptor — Universal AI Response Validator with CKO Badges
 * Detects physics/math content in AI responses and shows verification badges
 * with CKO stability metrics when available.
 *
 * @version 1.287.3
 * @license CC BY 4.0 — Zeq. H / Zeq 1.287 Hz Limited
 */

(() => {
  'use strict';

  // ── Physics keyword patterns ──────────────────────────────────────────
  const DOMAIN_PATTERNS = {
    QM: /quantum|schrodinger|wave\s*function|superposition|entangle|planck|heisenberg|tunneling|de\s*broglie|dirac|boson|fermion|commutator/i,
    GR: /general\s*relativ|einstein|geodesic|schwarzschild|gravitational\s*wave|spacetime|metric\s*tensor|friedmann|cosmological|redshift/i,
    NM: /newton|classical\s*mechanic|momentum|kinetic\s*energy|potential\s*energy|harmonic\s*oscillat|angular\s*momentum|torque|gravitat/i,
    LZ: /entropy|thermodynamic|boltzmann|landauer|heat|temperature|energy\s*conservation/i,
    EM: /electromagnetic|maxwell|lorentz|electric\s*field|magnetic\s*field|photon|radiation/i,
    KO: /kepler|orbital|centripetal|escape\s*velocity|satellite/i,
    CS: /algorithm|complexity|shannon|kolmogorov|amdahl|big-?o\s*notation|hash|encrypt/i,
  };

  // ── State ──────────────────────────────────────────────────────────────
  let scanDebounce = null;
  let processedNodes = new WeakSet();
  let latestCKO = null;

  // ── Listen for CKO updates from service worker ────────────────────────
  if (typeof chrome !== 'undefined' && chrome.runtime?.onMessage) {
    chrome.runtime.onMessage.addListener((message) => {
      if (message.type === 'zeq_cko_update' && message.payload) {
        latestCKO = message.payload;
      }
    });
  }

  // ── Scan AI responses ─────────────────────────────────────────────────
  function scanResponses() {
    // Target common AI chat response containers
    const selectors = [
      // ChatGPT
      '[data-message-author-role="assistant"]',
      '.markdown.prose',
      // Claude
      '[class*="claude-"] .font-claude-message',
      '.contents .break-words',
      // DeepSeek
      '.ds-markdown',
      '.chat-content',
      // Grok
      '[class*="message-bubble"]',
      // Universal fallback
      '[role="assistant"]',
      '.ai-response',
      '.bot-message',
    ];

    const elements = document.querySelectorAll(selectors.join(', '));

    elements.forEach(el => {
      if (processedNodes.has(el)) return;

      const text = el.textContent || '';
      if (text.length < 30) return; // Skip very short texts

      const matched = detectDomains(text);
      if (matched.length > 0) {
        injectBadge(el, matched);
        processedNodes.add(el);
      }
    });
  }

  // ── Detect physics domains in text ────────────────────────────────────
  function detectDomains(text) {
    const matched = [];
    for (const [domain, pattern] of Object.entries(DOMAIN_PATTERNS)) {
      if (pattern.test(text)) {
        matched.push(domain);
      }
    }
    return matched;
  }

  // ── Inject verification badge ─────────────────────────────────────────
  function injectBadge(element, domains) {
    // Don't duplicate
    if (element.querySelector('.zeq-verify-badge')) return;

    const badge = document.createElement('div');
    badge.className = 'zeq-verify-badge';
    badge.style.cssText = `
      display: inline-flex;
      align-items: center;
      gap: 6px;
      margin: 8px 0 4px;
      padding: 4px 10px;
      background: #0a0a14;
      border: 1px solid #1e293b;
      border-radius: 6px;
      font-family: -apple-system, 'Inter', sans-serif;
      font-size: 11px;
      color: #94a3b8;
      cursor: pointer;
      user-select: none;
      transition: all 0.2s;
    `;

    // Domain badges
    const domainHtml = domains.map(d => {
      const colors = {
        QM: '#a78bfa', GR: '#06b6d4', NM: '#22c55e',
        LZ: '#f97316', EM: '#eab308', KO: '#ec4899', CS: '#818cf8',
      };
      return `<span style="
        background: ${colors[d]}22;
        color: ${colors[d]};
        padding: 1px 6px;
        border-radius: 3px;
        font-weight: 600;
        font-size: 10px;
      ">${d}</span>`;
    }).join('');

    // CKO stability mini-badge (if available)
    let ckoHtml = '';
    if (latestCKO?.cko) {
      const stability = latestCKO.cko.stability?.index ?? 0;
      const pct = (stability * 100).toFixed(0);
      const color = stability >= 0.8 ? '#22c55e' : stability >= 0.5 ? '#eab308' : '#ef4444';
      const ko42ok = latestCKO.cko.ko42?.compliant ? '✓' : '✗';

      ckoHtml = `
        <span style="display:inline-flex;align-items:center;gap:3px;margin-left:4px;padding-left:6px;border-left:1px solid #334155">
          <span style="width:5px;height:5px;border-radius:50%;background:${color};display:inline-block"></span>
          <span style="color:${color};font-family:monospace;font-size:10px">${pct}%</span>
          <span style="color:#64748b;font-size:9px">KO42${ko42ok}</span>
        </span>
      `;
    }

    badge.innerHTML = `
      <span style="color:#06b6d4;font-weight:700;font-size:10px">ZEQ</span>
      ${domainHtml}
      ${ckoHtml}
      <span style="color:#64748b;font-size:9px">1.287 Hz</span>
      <span class="zeq-verify-status" style="font-size:9px;color:#64748b;margin-left:6px;padding-left:6px;border-left:1px solid #334155">tap to ground ↗</span>
    `;

    // Click → ground this text through the LIVE Zeq SDK (real envelope), then
    // show the honest grounded result inline. "Grounded", never "verified".
    badge.addEventListener('click', () => {
      const text = (element.textContent || '').trim().slice(0, 500);
      if (!text) return;
      const status = badge.querySelector('.zeq-verify-status');
      if (status) { status.textContent = 'grounding…'; status.style.color = '#94a3b8'; }
      try {
        chrome.runtime.sendMessage({ type: 'verifyText', text }, (res) => {
          if (!status) return;
          if (chrome.runtime.lastError || !res || !res.success) {
            status.textContent = 'SDK offline'; status.style.color = '#ef4444'; return;
          }
          const ops = (res.operators || []).slice(0, 3).join(', ');
          const prec = res.precision != null ? ('≤' + (res.precision * 100).toFixed(2).replace(/\.?0+$/, '') + '%') : '≤0.1%';
          status.innerHTML = '<span style="color:#22c55e">grounded</span> · ' +
            '<span style="color:#06b6d4">' + (res.domain || 'Zeq') + '</span>' +
            (ops ? ' · <span style="color:#a78bfa">' + ops + '</span>' : '') +
            ' · <span style="color:#94a3b8">' + prec + '</span>';
        });
      } catch (_) { if (status) { status.textContent = 'SDK offline'; status.style.color = '#ef4444'; } }
    });

    // Hover effect
    badge.addEventListener('mouseenter', () => {
      badge.style.borderColor = '#06b6d4';
      badge.style.background = '#0f172a';
    });
    badge.addEventListener('mouseleave', () => {
      badge.style.borderColor = '#1e293b';
      badge.style.background = '#0a0a14';
    });

    // Insert after element or at end
    element.appendChild(badge);
  }

  // ── Context menu verify handler ───────────────────────────────────────
  if (typeof chrome !== 'undefined' && chrome.runtime?.onMessage) {
    chrome.runtime.onMessage.addListener((message) => {
      if (message.type === 'verify_selection' && message.text) {
        const domains = detectDomains(message.text);
        chrome.runtime.sendMessage({
          type: 'verification_result',
          text: message.text,
          domains,
          hasCKO: !!latestCKO,
          cko: latestCKO,
        });
      }
    });
  }

  // ── MutationObserver for streaming responses ──────────────────────────
  const observer = new MutationObserver(() => {
    if (scanDebounce) clearTimeout(scanDebounce);
    scanDebounce = setTimeout(scanResponses, 800);
  });

  observer.observe(document.body, {
    childList: true,
    subtree: true,
    characterData: true,
  });

  // Initial scan
  setTimeout(scanResponses, 1000);

  // ── K4 — OPT-IN silent prompt enhancement ───────────────────────────────
  // OFF by default. When the user enables "Enhance prompts" (Settings) AND the
  // per-platform toggle is on, we inject the page-context fetch/XHR interceptor
  // into MAIN world; it hands each outgoing prompt here (ISOLATED) to be wrapped
  // in the Zeq envelope built from LIVE phase/ko42, then sends it on — silently.
  const PLATFORM_PAGE_CTX = {
    chatgpt: 'chatgpt', openai: 'chatgpt', claude: 'claude', deepseek: 'deepseek', grok: 'grok', x: 'grok',
  };
  function detectPlatformFile() {
    const h = location.hostname.replace(/^www\./, '');
    for (const k in PLATFORM_PAGE_CTX) { if (h.includes(k)) return PLATFORM_PAGE_CTX[k]; }
    return null;
  }
  async function buildEnvelope(original) {
    let phase = 0, ko42 = 0;
    try { const st = await new Promise((r) => chrome.runtime.sendMessage({ type: 'getState' }, (x) => r(x || {}))); phase = st.phase || 0; ko42 = st.ko42 || 0; } catch (_) {}
    return '{"zeq_os":{"version":"1.287.6","pulse":"1.287 Hz","operators":"1,500+ catalogued","phase":' + phase + ',"ko42":' + ko42 + '},"query":"' + String(original).replace(/\\/g, '\\\\').replace(/"/g, '\\"').slice(0, 2000) + '"}';
  }
  // Bridge: MAIN-world page-context → here → back (matches *-page-context.js).
  window.addEventListener('message', async (e) => {
    if (e.source !== window || !e.data || e.data.type !== 'ZEQ_PROCESS_REQUEST') return;
    let processed = e.data.originalContent;
    try { processed = await buildEnvelope(e.data.originalContent); } catch (_) {}
    window.postMessage({ type: 'ZEQ_PROCESSED_RESPONSE', requestId: e.data.requestId, processedContent: processed }, '*');
  });
  chrome.storage?.local?.get(['zeq_prompt_enhance', 'zeq_platforms'], (r) => {
    if (!r || !r.zeq_prompt_enhance) return;              // off by default
    const plat = detectPlatformFile();
    if (!plat) return;                                    // no page-context for this site
    if (r.zeq_platforms && r.zeq_platforms[plat] === false) return; // per-platform off
    const s = document.createElement('script');
    s.src = chrome.runtime.getURL('content/' + plat + '-page-context.js');
    s.onload = () => s.remove();
    (document.head || document.documentElement).appendChild(s);
    console.log('[Zeq] Prompt enhancement ON — injected ' + plat + ' page-context');
  });

  console.log('[Zeq] Interceptor v1.287.6 loaded — physics grounding badge active');
})();
