// content/main-world.js — corre en contexto MAIN (mismo JS que la página Skool)
// Intercepta fetch y XHR para capturar datos de la API interna de Skool sin anti-bot.
// Se comunica con bridge.js via window.postMessage.

(function () {
  'use strict';

  if (window.__SKOOP_INJECTED__) return;
  window.__SKOOP_INJECTED__ = true;

  // ── DISPATCH al bridge ────────────────────────────────────
  function dispatch(payload) {
    const parts = location.pathname.split('/').filter(Boolean);
    const RESERVED = ['api', '_next', 'static', 'favicon', 'login', 'signup'];
    const raw = parts[0] || '';
    const pageSlug = (raw && !RESERVED.includes(raw) && !raw.startsWith('@'))
      ? raw
      : null;
    window.postMessage({ __skoop: true, payload: { ...payload, pageSlug } }, '*');
  }

  // ── FETCH INTERCEPTOR ─────────────────────────────────────
  const _fetch = window.fetch.bind(window);

  window.fetch = async function (input, init) {
    const url =
      typeof input === 'string'
        ? input
        : input instanceof URL
        ? input.href
        : input instanceof Request
        ? input.url
        : String(input);

    let response;
    try {
      response = await _fetch(input, init);
    } catch (err) {
      throw err;
    }

    // Solo interceptar llamadas de Skool (relativas o al dominio)
    const isSkool =
      url.startsWith('/') ||
      url.includes('skool.com');

    if (isSkool) {
      try {
        const contentType = response.headers.get('content-type') || '';
        if (contentType.includes('json')) {
          response.clone().json().then((data) => {
            dispatch({
              type: 'api_call',
              source: 'fetch',
              url,
              method: (init?.method || 'GET').toUpperCase(),
              status: response.status,
              data,
              ts: Date.now(),
            });
          }).catch(() => {});
        }
      } catch (_) {
        // Nunca romper el fetch original
      }
    }

    return response;
  };

  // ── XHR INTERCEPTOR ───────────────────────────────────────
  const _open = XMLHttpRequest.prototype.open;
  const _send = XMLHttpRequest.prototype.send;

  XMLHttpRequest.prototype.open = function (method, url) {
    this.__skoop_url = String(url);
    this.__skoop_method = method;
    return _open.apply(this, arguments);
  };

  XMLHttpRequest.prototype.send = function (body) {
    this.addEventListener('load', function () {
      const url = this.__skoop_url;
      if (!url) return;
      const isSkool = url.startsWith('/') || url.includes('skool.com');
      if (!isSkool) return;

      try {
        const data = JSON.parse(this.responseText);
        dispatch({
          type: 'api_call',
          source: 'xhr',
          url,
          method: (this.__skoop_method || 'GET').toUpperCase(),
          status: this.status,
          data,
          ts: Date.now(),
        });
      } catch (_) {
        // No es JSON, ignorar
      }
    });
    return _send.apply(this, arguments);
  };

  // ── INFO DE PÁGINA (para detectar slug de comunidad) ─────
  function getPageInfo() {
    const parts = location.pathname.split('/').filter(Boolean);
    return {
      type: 'page_info',
      slug: parts[0] || null,
      section: parts[1] || 'home',
      path: location.pathname,
      href: location.href,
      ts: Date.now(),
    };
  }

  // Al cargar la página
  dispatch(getPageInfo());

  // Skool es una SPA — detectar navegación sin recarga
  let _lastPath = location.pathname;
  new MutationObserver(() => {
    if (location.pathname !== _lastPath) {
      _lastPath = location.pathname;
      setTimeout(() => dispatch(getPageInfo()), 800);
    }
  }).observe(document, { subtree: true, childList: true });
})();
