// Zeq Mathematical Framework - ChatGPT Content Script
// Intercepts ChatGPT input and enriches queries with server-side mathematical state

(function() {
  'use strict';

  async function fetchPhase() {
    try {
      // Use service worker for phase data (avoids CORS issues on content scripts)
      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: { chatgpt: true } };
        } else if (response) {
          settings = response;
        }
      });
    } else {
      settings = { enabled: true, platforms: { chatgpt: true } };
    }
  } catch (error) {
    settings = { enabled: true, platforms: { chatgpt: 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;
  });

  async function buildMathPrompt(originalMessage) {
    if (!settings.enabled || !settings.platforms?.chatgpt) return originalMessage;
    try {
      var phaseData = await fetchPhase();
      var sys = '{"zeq_os":{"version":"1.287.6","pulse":"1.287 Hz","operators":"1,500+ catalogued"';
      if (phaseData) {
        sys += ',"phase":' + (phaseData.phase || 0);
        sys += ',"ko42":' + (phaseData.ko42 || 0);
      }
      sys += '},"query":"' + originalMessage.replace(/"/g, '\\"').substring(0, 500) + '"}';
      return sys;
    } catch (error) {
      return originalMessage;
    }
  }

  window.addEventListener('message', async (event) => {
    if (event.source !== window) return;
    if (event.data && event.data.type === 'ZEQ_PROCESS_REQUEST') {
      if (!settings.enabled || !settings.platforms?.chatgpt) {
        window.postMessage({ type: 'ZEQ_PROCESSED_RESPONSE', requestId: event.data.requestId, processedContent: event.data.originalContent }, '*');
        return;
      }
      try {
        const processed = await buildMathPrompt(event.data.originalContent);
        window.postMessage({ type: 'ZEQ_PROCESSED_RESPONSE', requestId: event.data.requestId, processedContent: processed }, '*');
      } catch (error) {
        window.postMessage({ type: 'ZEQ_PROCESSED_RESPONSE', requestId: event.data.requestId, processedContent: event.data.originalContent }, '*');
      }
    }
  });

  function findInputBox() {
    const selectors = [
      'textarea[data-id="root"]', 'textarea#prompt-textarea',
      'textarea[placeholder*="Message"]', 'textarea[placeholder*="message"]',
      'textarea[placeholder*="Ask"]', 'div[contenteditable="true"][role="textbox"]',
      'div[contenteditable="true"]', 'textarea'
    ];
    for (const selector of selectors) {
      const elements = document.querySelectorAll(selector);
      for (const element of elements) {
        if (element && element.offsetParent !== null) {
          const rect = element.getBoundingClientRect();
          if (rect.width > 100 && rect.height > 20) return element;
        }
      }
    }
    return null;
  }

  function findSubmitButton() {
    const selectors = ['button[data-testid="send-button"]', 'button[aria-label*="Send"]', 'button[aria-label*="send"]'];
    for (const selector of selectors) {
      const buttons = document.querySelectorAll(selector);
      for (const button of buttons) {
        const ariaLabel = button.getAttribute('aria-label') || '';
        if (ariaLabel.toLowerCase().includes('send') && !button.disabled) return button;
      }
    }
    return null;
  }

  function interceptEnterKey(inputBox) {
    if (inputBox.dataset.zeqEnterIntercepted) return;
    inputBox.dataset.zeqEnterIntercepted = 'true';
    inputBox.addEventListener('keydown', async (e) => {
      if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
        const originalValue = inputBox.value || inputBox.textContent || '';
        if (typeof originalValue !== 'string' || originalValue.trim().startsWith('{') || !originalValue.trim()) return;
        e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation();
        const processedMessage = await buildMathPrompt(originalValue);
        if (inputBox.tagName === 'TEXTAREA') {
          inputBox.value = processedMessage;
          try { Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set.call(inputBox, processedMessage); } catch(err) {}
          inputBox.dispatchEvent(new Event('input', { bubbles: true, cancelable: true }));
          inputBox.dispatchEvent(new Event('change', { bubbles: true, cancelable: true }));
        } else if (inputBox.contentEditable === 'true') {
          inputBox.textContent = processedMessage;
          inputBox.dispatchEvent(new Event('input', { bubbles: true, cancelable: true }));
        }
        setTimeout(() => {
          inputBox.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true }));
          setTimeout(() => { var sb = findSubmitButton(); if (sb && !sb.disabled) sb.click(); }, 50);
        }, 100);
      }
    }, true);
  }

  function initialize() {
    const inputBox = findInputBox();
    if (inputBox && !inputBox.dataset.zeqIntercepted) {
      inputBox.dataset.zeqIntercepted = 'true';
      interceptEnterKey(inputBox);
    }
  }

  const observer = new MutationObserver(() => {
    const inputBox = findInputBox();
    if (inputBox && !inputBox.dataset.zeqIntercepted) {
      inputBox.dataset.zeqIntercepted = 'true';
      interceptEnterKey(inputBox);
    }
  });

  if (document.body) {
    observer.observe(document.body, { childList: true, subtree: true });
    initialize();
  } else {
    document.addEventListener('DOMContentLoaded', () => {
      observer.observe(document.body, { childList: true, subtree: true });
      initialize();
    });
  }

})();
