// Content script — runs in MAIN world (page context)
// Intercepts fetch to capture TalkJS nymId from request bodies

(function() {
  if (window.__heresy_intercept) return;
  window.__heresy_intercept = true;

  const _origFetch = window.fetch;

  window.fetch = function() {
    const url = typeof arguments[0] === 'string' ? arguments[0] : (arguments[0]?.url || '');
    const opts = arguments[1] || {};

    if (url.includes('talkjs.com') && opts.body) {
      try {
        const body = typeof opts.body === 'string' ? JSON.parse(opts.body) : opts.body;
        if (body.nymId && body.nymId.endsWith('_n')) {
          console.log('[Heresy] Captured nymId:', body.nymId);
          // Post to window — bridge script in background picks it up
          window.postMessage({ type: 'HERESY_NYM', nymId: body.nymId }, '*');
          // Also try direct send to app (same-origin won't block localhost)
          try {
            var port = localStorage.getItem('heresy_port') || '3000';
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'http://127.0.0.1:' + port + '/eldorado/api/talkjs/nym', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.send(JSON.stringify({ nymId: body.nymId }));
          } catch (e) {}
        }
      } catch (e) {}
    }

    return _origFetch.apply(this, arguments);
  };

  // Also intercept XMLHttpRequest
  const _origXhrOpen = XMLHttpRequest.prototype.open;
  const _origXhrSend = XMLHttpRequest.prototype.send;

  XMLHttpRequest.prototype.open = function(method, url) {
    this.__heresy_url = url;
    return _origXhrOpen.apply(this, arguments);
  };

  XMLHttpRequest.prototype.send = function(body) {
    if (this.__heresy_url && this.__heresy_url.includes('talkjs.com') && body) {
      try {
        const parsed = typeof body === 'string' ? JSON.parse(body) : body;
        if (parsed.nymId && parsed.nymId.endsWith('_n')) {
          console.log('[Heresy] XHR captured nymId:', parsed.nymId);
          window.postMessage({ type: 'HERESY_NYM', nymId: parsed.nymId }, '*');
          try {
            var port = localStorage.getItem('heresy_port') || '3000';
            var xhr2 = new XMLHttpRequest();
            xhr2.open('POST', 'http://127.0.0.1:' + port + '/eldorado/api/talkjs/nym', true);
            xhr2.setRequestHeader('Content-Type', 'application/json');
            xhr2.send(JSON.stringify({ nymId: parsed.nymId }));
          } catch (e) {}
        }
      } catch (e) {}
    }
    return _origXhrSend.apply(this, arguments);
  };

  console.log('[Heresy] TalkJS interceptor active (MAIN world)');
})();
