(function () {
  'use strict';

  if (window.__temuFetchHooked) return;
  window.__temuFetchHooked = true;
  window.__temuMainWorldHookVersion = '2.7.73';

  const originalFetch = window.fetch;
  const originalXhrOpen = window.XMLHttpRequest?.prototype?.open;
  const originalXhrSend = window.XMLHttpRequest?.prototype?.send;

  function readRequestBodyFromValue(body) {
    if (typeof body !== 'string') return null;
    try {
      return JSON.parse(body);
    } catch (_) {
      return body;
    }
  }

  function readFetchRequestBody(args) {
    return readRequestBodyFromValue(args?.[1]?.body || args?.[0]?.body || null);
  }

  function postTemuData(type, payload) {
    try {
      window.postMessage({ ...payload, type }, window.location.origin);
    } catch (_) {
      window.postMessage({ ...payload, type }, '*');
    }
  }

  function emitCapturedResponse(url, requestBody, data) {
    if (!url) return;

    const capturesProductList = url.includes('pageQuery');
    const capturesLivePhoto = url.includes('real_picture/list');
    const capturesPricing = /searchForChainSupplier|priceorder|bargain-no-bom|price-review-order|recommendedprice|baseprice/i.test(url);
    if (!capturesProductList && !capturesLivePhoto && !capturesPricing) return;

    if (capturesPricing) {
      if (data && (data.result !== undefined || data.data !== undefined || data.detail !== undefined || data.success !== undefined)) {
        postTemuData('__TEMU_PRICING_API_DATA__', { url, requestBody, data });
      }
      return;
    }
    if (capturesLivePhoto) {
      if (data && data.success && data.result) {
        postTemuData('__TEMU_LIVE_PHOTO_DATA__', { url, requestBody, data: data.result });
      }
      return;
    }
    if (data && (data.result !== undefined || data.data !== undefined)) {
      postTemuData('__TEMU_PAGE_QUERY_DATA__', { url, requestBody, data });
    }
  }

  if (typeof originalFetch === 'function') {
    window.fetch = async function temuFetchProxy(...args) {
      const response = await originalFetch.apply(this, args);
      try {
        const url = typeof args[0] === 'string' ? args[0] : (args[0]?.url || '');
        const requestBody = readFetchRequestBody(args);
        response.clone().json().then(data => {
          emitCapturedResponse(url, requestBody, data);
        }).catch(() => {});
      } catch (_) {}
      return response;
    };
  }

  if (typeof originalXhrOpen === 'function' && typeof originalXhrSend === 'function') {
    window.XMLHttpRequest.prototype.open = function temuXhrOpen(method, url, ...rest) {
      this.__temuCaptureUrl = typeof url === 'string' ? url : (url?.toString?.() || '');
      return originalXhrOpen.call(this, method, url, ...rest);
    };

    window.XMLHttpRequest.prototype.send = function temuXhrSend(body) {
      const requestBody = readRequestBodyFromValue(body);
      try {
        this.addEventListener('load', function temuXhrLoad() {
          try {
            const text = this.responseType && this.responseType !== 'text' ? '' : (this.responseText || '');
            if (!text) return;
            emitCapturedResponse(this.__temuCaptureUrl || '', requestBody, JSON.parse(text));
          } catch (_) {}
        });
      } catch (_) {}
      return originalXhrSend.call(this, body);
    };
  }
})();


