(() => {
  if (window.__PULSE_CHAT_BALANCE_MAIN__) return;
  window.__PULSE_CHAT_BALANCE_MAIN__ = true;

  const TARGET_RE = /\/api\/chatList\/chatHistory\b/i;
  const ORIGIN = location.origin;

  window.__pulseChatHistoryMessagePrices = window.__pulseChatHistoryMessagePrices || [];
  window.__pulseChatHistoryPaidMessageIds = window.__pulseChatHistoryPaidMessageIds || [];

  function getCredits(msg, keys) {
    for (const k of keys) {
      if (msg[k] !== void 0 && msg[k] !== null) return msg[k];
    }
    return void 0;
  }

  function safePost(type, payload) {
    try {
      window.postMessage({ type, ...payload }, ORIGIN);
    } catch {
      try {
        window.postMessage({ type, ...payload }, '*');
      } catch {}
    }
  }

  function processChatHistoryData(data) {
    if (!data || !data.status || !Array.isArray(data.response)) return;

    const activeKeys = ['spend_active_credits', 'spendActiveCredits', 'active_credits', 'activeCredits'];
    const allKeys = ['spend_all_credits', 'spendAllCredits', 'all_credits', 'allCredits'];

    const maleMessages = data.response.filter((msg) => msg.is_male === 1);
    const messagePrices = maleMessages.map((msg) => ({
      id: msg.id,
      price: msg.message_price ?? msg.messagePrice ?? '0.0000',
      spend_active_credits: getCredits(msg, activeKeys),
      spend_all_credits: getCredits(msg, allKeys)
    })).filter((msg) => msg.id != null);

    window.__pulseChatHistoryMessagePrices = messagePrices;
    if (messagePrices.length > 0) {
      safePost('CHAT_HISTORY_PRICE_DATA', { messagePrices });
    }

    const paidMediaMessages = data.response.filter(
      (msg) => msg.is_male === 0 && msg.payed === 1 && (msg.message_type === 'SENT_AUDIO' || msg.message_type === 'SENT_VIDEO')
    );
    const paidMessageIds = paidMediaMessages.map((msg) => msg.id).filter((id) => id != null);

    window.__pulseChatHistoryPaidMessageIds = paidMessageIds;
    if (paidMessageIds.length > 0) {
      safePost('CHAT_HISTORY_PAID_DATA', { paidMessageIds });
    }
  }

  function respondWithStoredData() {
    if (Array.isArray(window.__pulseChatHistoryMessagePrices) && window.__pulseChatHistoryMessagePrices.length > 0) {
      safePost('CHAT_HISTORY_PRICE_DATA', { messagePrices: window.__pulseChatHistoryMessagePrices });
    }
    if (Array.isArray(window.__pulseChatHistoryPaidMessageIds) && window.__pulseChatHistoryPaidMessageIds.length > 0) {
      safePost('CHAT_HISTORY_PAID_DATA', { paidMessageIds: window.__pulseChatHistoryPaidMessageIds });
    }
  }

  window.addEventListener('message', (event) => {
    try {
      if (event.source !== window) return;
      if (!event.data || event.data.type !== 'REQUEST_CHAT_HISTORY_BALANCE_DATA') return;
      respondWithStoredData();
    } catch {}
  });

  function normalizeUrl(input) {
    try {
      return new URL(typeof input === 'string' ? input : String((input && input.url) || ''), location.href);
    } catch {
      return null;
    }
  }

  function parseJsonFromResponse(value) {
    if (!value) return Promise.resolve(null);
    if (typeof value === 'string') {
      try {
        return Promise.resolve(JSON.parse(value));
      } catch {
        return Promise.resolve(null);
      }
    }
    if (value instanceof Response) {
      return value.clone().json().catch(() => null);
    }
    return Promise.resolve(null);
  }

  try {
    const nativeFetch = window.fetch;
    if (typeof nativeFetch === 'function') {
      window.fetch = async function (...args) {
        const res = await nativeFetch.apply(this, args);
        try {
          const url = normalizeUrl(args[0]);
          if (url && TARGET_RE.test(url.pathname)) {
            const data = await parseJsonFromResponse(res);
            processChatHistoryData(data);
          }
        } catch {}
        return res;
      };
    }
  } catch {}

  try {
    const XO = XMLHttpRequest.prototype.open;
    const XS = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function (method, url) {
      try {
        const parsed = normalizeUrl(url);
        this.__pulseChatHistoryUrl = parsed ? parsed.pathname : String(url || '');
      } catch {
        this.__pulseChatHistoryUrl = String(url || '');
      }
      return XO.apply(this, arguments);
    };

    XMLHttpRequest.prototype.send = function () {
      try {
        this.addEventListener('load', function () {
          try {
            if (!TARGET_RE.test(String(this.__pulseChatHistoryUrl || ''))) return;
            const data = JSON.parse(this.responseText || 'null');
            processChatHistoryData(data);
          } catch {}
        });
      } catch {}
      return XS.apply(this, arguments);
    };
  } catch {}
})();
