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

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

  const safePost = (lastMessages) => {
    try {
      if (Array.isArray(lastMessages) && lastMessages.length) {
        window.postMessage({ type: 'LAST_MESSAGE_DATA', lastMessages }, ORIGIN);
        window.postMessage({
          source: 'alpha-finder-chat-limits',
          type: 'LAST_MESSAGES',
          payload: lastMessages
        }, ORIGIN);
      }
    } catch {}
  };

  const parseJson = async (value) => {
    try {
      if (!value) return null;
      if (typeof value === 'string') return JSON.parse(value);
      if (value instanceof Response) return await value.clone().json();
      return null;
    } catch {
      return null;
    }
  };

  const extractArray = (data) => {
    if (!data) return null;
    if (Array.isArray(data)) return data;
    if (Array.isArray(data.response)) return data.response;
    if (Array.isArray(data.result)) return data.result;
    return null;
  };

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

  const hookFetch = () => {
    const nativeFetch = window.fetch;
    if (typeof nativeFetch !== 'function') return;
    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 parseJson(res);
          const arr = extractArray(data);
          if (arr) safePost(arr);
        }
      } catch {}
      return res;
    };
  };

  const hookXhr = () => {
    const XO = XMLHttpRequest.prototype.open;
    const XS = XMLHttpRequest.prototype.send;
    XMLHttpRequest.prototype.open = function(method, url) {
      try {
        const parsed = normalizeUrl(url);
        this.__pulseLastMessageUrl = parsed ? parsed.pathname : String(url || '');
      } catch {
        this.__pulseLastMessageUrl = String(url || '');
      }
      return XO.apply(this, arguments);
    };
    XMLHttpRequest.prototype.send = function() {
      try {
        this.addEventListener('load', function() {
          try {
            if (!TARGET_RE.test(String(this.__pulseLastMessageUrl || ''))) return;
            const data = JSON.parse(this.responseText || 'null');
            const arr = extractArray(data);
            if (arr) safePost(arr);
          } catch {}
        });
      } catch {}
      return XS.apply(this, arguments);
    };
  };

  hookFetch();
  hookXhr();
})();
