/**
 * STONK KOC - Collector Hook (MAIN world)
 * Intercepts TikTok API responses stealthily
 * Runs in MAIN world to access window.fetch directly
 */
(function () {
  const HOOK_ID = "stonk-koc-hook-v0.1";
  if (window[HOOK_ID]) return;
  window[HOOK_ID] = true;

  // APIs cần capture cho KOC data
  const TARGET_APIS = [
    "/api/v1/oec/affiliate/cmp/creator/rank/list/get",
    "/api/v1/oec/affiliate/creator/marketplace/find",
    "/api/v1/affiliate/expert/list",
    "/api/v1/affiliate/expert/detail",
    "/api/v1/oec/affiliate/seller/invitation_group/invitation/limit",
    "/api/v1/oec/affiliate/crm/creator/upper_limit/get",
    "/api/v1/oec/affiliate/cmp/filter",
    "/api/v1/insights/affiliate/creator/search/suggestions",
    "/api/v1/affiliate/has_agent",
  ];

  function shouldCapture(url) {
    if (!url) return false;
    return TARGET_APIS.some(api => url.includes(api));
  }

  function upload(url, body) {
    window.postMessage({ source: "stonk-koc-hook", type: "upload", url, body }, window.location.origin);
  }

  // Stealth: mask as native
  function makeNative(fn, originalFn) {
    const originalStr = originalFn ? originalFn.toString() : "function () { [native code] }";
    Object.defineProperty(fn, "toString", {
      value: () => originalStr,
      configurable: true, writable: true,
    });
    return fn;
  }

  // ── Stealth Fetch Intercept ────────────────────────────────
  const originalFetch = window.fetch;
  window.fetch = makeNative(function (...args) {
    const promise = originalFetch(...args);
    promise.then(response => {
      try {
        const url = args[0] instanceof Request ? args[0].url : String(args[0]);
        if (shouldCapture(url)) {
          response.clone().json().then(data => {
            upload(url, data);
          }).catch(() => {});
        }
      } catch (_) {}
    }).catch(() => {});
    return promise;
  }, originalFetch);

  // ── Stealth XHR Intercept ──────────────────────────────────
  const origOpen = XMLHttpRequest.prototype.open;
  const origSend = XMLHttpRequest.prototype.send;

  XMLHttpRequest.prototype.open = makeNative(function (method, url) {
    this._stonk_url = url;
    return origOpen.apply(this, arguments);
  }, origOpen);

  XMLHttpRequest.prototype.send = makeNative(function () {
    this.addEventListener("load", function () {
      try {
        if (shouldCapture(this._stonk_url)) {
          const data = JSON.parse(this.responseText);
          upload(this._stonk_url, data);
        }
      } catch (_) {}
    });
    return origSend.apply(this, arguments);
  }, origSend);

  console.log("[STONK KOC] Hook Active v0.1 — Capturing TikTok KOC APIs");
})();
