// Zeq Mathematical Framework - Universal Content Script
// Generic fallback for other AI platforms (Perplexity, Groq, Poe, Gemini, etc.)
// Uses server-side API for mathematical state instead of local framework

(function() {
  'use strict';

  async function fetchPhase() {
    try {
      return await new Promise((resolve) => {
        chrome.runtime.sendMessage({ type: 'getState' }, (response) => {
          if (chrome.runtime.lastError || !response) { resolve(null); return; }
          resolve(response);
        });
      });
    } catch(e) { return null; }
  }

  let settings = { enabled: true };

  try {
    if (typeof chrome !== 'undefined' && chrome.runtime) {
      chrome.runtime.sendMessage({ action: 'getSettings' }, (response) => {
        if (chrome.runtime.lastError) {
          settings = { enabled: true, platforms: { universal: true } };
        } else if (response) {
          settings = response;
        }
      });
    } else {
      settings = { enabled: true, platforms: { universal: true } };
    }
  } catch (error) {
    settings = { enabled: true, platforms: { universal: true } };
  }

  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'settingsUpdated') {
      settings = request.settings;
      sendResponse({ success: true });
      return false;
    }
    if (request.action === 'getTransparencyStats') {
      sendResponse({ stats: { interactions: 0, verificationRate: '--' } });
      return false;
    }
    if (request.action === 'downloadTransparencyJSON') {
      sendResponse({ success: false, error: 'Transparency logger not available' });
      return false;
    }
    return false;
  });

  // Detect which AI platform we're on
  var host = location.hostname.replace('www.', '');
  var platforms = ['chatgpt.com','chat.openai.com','claude.ai','chat.deepseek.com','gemini.google.com','x.com','groq.com','poe.com','perplexity.ai'];
  var onPlatform = platforms.some(function(p) { return host.includes(p.split('.')[0]); });
  if (!onPlatform) return;

  var platformName = host.includes('chatgpt') || host.includes('openai') ? 'ChatGPT' :
    host.includes('claude') ? 'Claude' : host.includes('deepseek') ? 'DeepSeek' :
    host.includes('gemini') ? 'Gemini' : host.includes('x.com') ? 'Grok' :
    host.includes('groq') ? 'Groq' : host.includes('poe') ? 'Poe' :
    host.includes('perplexity') ? 'Perplexity' : 'AI';

  console.log('[Zeq] ' + platformName + ' interceptor active — server-side operators');

  var PHYSICS_WORDS = ['force','energy','mass','velocity','acceleration','momentum','gravity','quantum','relativity','entropy','wavelength','frequency','electron','photon','neutron','proton','newton','einstein','planck','boltzmann','maxwell','schrodinger','joule','watt','hertz','pascal','tesla','coulomb','orbit','wave','field','potential','kinetic','thermal','equation','formula','calculate','derive','temperature','pressure','volume','density','E=mc','F=ma'];

  function hasPhysics(text) {
    var lower = text.toLowerCase();
    var count = 0;
    for (var i = 0; i < PHYSICS_WORDS.length; i++) {
      if (lower.includes(PHYSICS_WORDS[i])) count++;
    }
    return count >= 2;
  }

  function findOperators(text) {
    var lower = text.toLowerCase();
    var matched = [];
    var domains = {
      'QM': { keywords: ['quantum','wavefunction','schrodinger','dirac','entanglement','superposition','tunneling','spin'], name: 'Quantum Mechanics' },
      'GR': { keywords: ['relativity','spacetime','geodesic','schwarzschild','einstein','gravitational','tensor','metric'], name: 'General Relativity' },
      'NM': { keywords: ['newton','force','acceleration','momentum','velocity','friction','torque','angular'], name: 'Newtonian Mechanics' },
      'LZ': { keywords: ['entropy','thermodynamic','boltzmann','temperature','heat','energy','carnot','gibbs'], name: 'Thermodynamics' },
      'EM': { keywords: ['electromagnetic','maxwell','electric','magnetic','coulomb','faraday','lorentz','inductance'], name: 'Electromagnetism' },
      'KO': { keywords: ['orbit','kepler','gravity','satellite','trajectory','escape velocity','period'], name: 'Kinematic Operators' },
      'CS': { keywords: ['shannon','entropy','information','encryption','cipher','hash','random','complexity'], name: 'Computer Science' }
    };
    for (var code in domains) {
      var d = domains[code];
      var hits = 0;
      for (var j = 0; j < d.keywords.length; j++) {
        if (lower.includes(d.keywords[j])) hits++;
      }
      if (hits >= 1) matched.push({ code: code, name: d.name, hits: hits });
    }
    matched.sort(function(a,b) { return b.hits - a.hits; });
    return matched.slice(0, 4);
  }

  function createBadge(operators) {
    var badge = document.createElement('div');
    badge.className = 'zeq-os-badge';
    var opText = operators.map(function(o) { return o.code; }).join(', ');
    var domainText = operators.map(function(o) { return o.name; }).join(', ');
    badge.style.cssText = 'display:flex;align-items:center;gap:8px;padding:6px 12px;margin:8px 0;border-radius:8px;font-size:12px;font-family:-apple-system,sans-serif;background:rgba(34,197,94,0.08);border:1px solid rgba(34,197,94,0.2);color:#22c55e;';
    badge.innerHTML = '<span style="font-size:16px">&#10003;</span><span><strong>Zeq</strong> \u2014 Matched: ' + opText + ' (' + domainText + ') at 1.287 Hz</span>';
    return badge;
  }

  var processed = new WeakSet();
  var debounceTimer = null;

  function scanForResponses() {
    var candidates = document.querySelectorAll('[class*="markdown"], [class*="response"], [class*="message"], [class*="prose"], [class*="content"], article, [role="article"]');
    for (var i = 0; i < candidates.length; i++) {
      var el = candidates[i];
      if (processed.has(el)) continue;
      var text = el.textContent || '';
      if (text.length < 50) continue;
      if (hasPhysics(text)) {
        processed.add(el);
        var operators = findOperators(text);
        if (operators.length > 0) {
          var badge = createBadge(operators);
          if (el.parentElement) el.parentElement.insertBefore(badge, el.nextSibling);
          chrome.runtime.sendMessage({ type: 'processQuery', text: text.substring(0, 200) }).catch(function(){});
        }
      }
    }
  }

  var observer = new MutationObserver(function() {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(scanForResponses, 800);
  });
  observer.observe(document.body, { childList: true, subtree: true, characterData: true });
  setTimeout(scanForResponses, 2000);

  chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
    if (msg.type === 'verify' && msg.text) {
      var ops = findOperators(msg.text);
      var badge = document.createElement('div');
      badge.style.cssText = 'position:fixed;top:20px;right:20px;z-index:99999;padding:12px 16px;border-radius:10px;font-size:13px;font-family:-apple-system,sans-serif;box-shadow:0 4px 20px rgba(0,0,0,0.4);background:rgba(1,2,6,0.95);border:1px solid rgba(34,211,238,0.3);color:#f8fafc;max-width:300px;';
      if (ops.length > 0) {
        badge.innerHTML = '<strong style="color:#22c55e">&#10003; Zeq &mdash; physics terms detected</strong><br><span style="color:#94a3b8;font-size:11px">' + ops.map(function(o){return o.code+' ('+o.name+')';}).join('<br>') + '</span>';
      } else {
        badge.innerHTML = '<strong style="color:#94a3b8">&#9679; Zeq</strong><br><span style="color:#64748b;font-size:11px">No physics operators detected in selection</span>';
      }
      document.body.appendChild(badge);
      setTimeout(function() { badge.remove(); }, 5000);
    }
    if (msg.type === 'getPageContext') {
      sendResponse({
        url: location.href, title: document.title,
        text: (document.querySelector('main') || document.querySelector('article') || document.body).innerText.substring(0, 3000),
        meta: (document.querySelector('meta[name="description"]') || {}).content || '',
        selectedText: (window.getSelection() || '').toString()
      });
      return true;
    }
  });
})();
