// Bridge content script — ISOLATED world on eldorado.gg / app.talkjs.com
// Two responsibilities:
//   1. Forward postMessage from MAIN world content.js to the SW (existing)
//   2. Execute fetch jobs dispatched from the SW. The SW long-polls the Lister
//      from its own context, but its own fetches to eldorado.gg get 403'd by
//      Cloudflare (different TLS fingerprint than the page). Content scripts
//      run inside the page's renderer process, so their fetches share the
//      page's TLS handshake and pass CF cleanly.

window.addEventListener('message', function(event) {
  if (event.source !== window) return;
  if (event.data && event.data.type === 'HERESY_NYM' && event.data.nymId) {
    console.log('[Heresy Bridge] Forwarding nymId to background:', event.data.nymId);
    try { chrome.runtime.sendMessage({ type: 'nymId', nymId: event.data.nymId }); } catch (_) {}
  }
});

const _isEldoradoPage = location.hostname.includes('eldorado.gg');

if (_isEldoradoPage) {
  console.log('[Heresy Bridge] fetch handler registered on', location.hostname);

  chrome.runtime.onMessage.addListener((msg, _sender, reply) => {
    if (!msg || msg.type !== 'heresy-fetch') return;
    (async () => {
      try {
        const init = {
          method: msg.method || 'GET',
          headers: msg.headers || {},
          credentials: 'include',
          cache: 'no-store',
          redirect: 'follow',
        };
        if (msg.body) init.body = msg.body;
        const r = await fetch(msg.url, init);
        const text = await r.text();
        let data;
        try { data = JSON.parse(text); } catch { data = { _raw: text.slice(0, 1000) }; }
        reply({ status: r.status, ok: r.ok, data });
      } catch (e) {
        reply({ error: String(e.message || e) });
      }
    })();
    return true; // keep channel open for async reply
  });
}
