(() => {
  const TARGET_PATH = "/api/chatList/chatListByUserID";

  function normalizePath(urlLike) {
    try {
      const u = new URL(urlLike, window.location.href);
      return u.pathname || "";
    } catch (e) {
      return String(urlLike || "");
    }
  }

  function isTarget(urlLike) {
    const p = normalizePath(urlLike);
    return p === TARGET_PATH || p.endsWith(TARGET_PATH);
  }

  function postLimits(respJson) {
    try {
      if (!respJson || respJson.status !== true || !Array.isArray(respJson.response)) return;

      const arr = respJson.response
        .map((x) => ({
          chat_uid: x && x.chat_uid,
          message_limit: x && x.message_limit,
          letter_limit: x && x.letter_limit,
          total_limit: x && x.total_limit,
        }))
        .filter((x) => x && x.chat_uid);

      if (arr.length > 0) {
        window.postMessage({ type: "CHAT_LIMITS_DATA", chatLimits: arr }, "*");
      }
    } catch (e) {
      // swallow
    }
  }

  // --- fetch hook (read-only via clone()) ---
  try {
    const origFetch = window.fetch;
    if (typeof origFetch === "function") {
      window.fetch = function (...args) {
        const p = origFetch.apply(this, args);
        try {
          const req = args[0];
          const urlLike = typeof req === "string" ? req : (req && req.url) || "";
          if (isTarget(urlLike)) {
            p.then((res) => {
              try {
                res.clone().json().then(postLimits).catch(() => {});
              } catch (e) {}
            }).catch(() => {});
          }
        } catch (e) {}
        return p;
      };
    }
  } catch (e) {}

  // --- XHR hook (read-only via responseText) ---
  try {
    const origOpen = XMLHttpRequest.prototype.open;
    const origSend = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function (method, url, ...rest) {
      try {
        this.__pulse_url__ = url;
      } catch (e) {}
      return origOpen.call(this, method, url, ...rest);
    };

    XMLHttpRequest.prototype.send = function (...args) {
      try {
        const urlLike = this.__pulse_url__ || "";
        if (isTarget(urlLike)) {
          this.addEventListener("load", function () {
            try {
              const txt = this.responseText;
              if (!txt || typeof txt !== "string") return;
              let j = null;
              try {
                j = JSON.parse(txt);
              } catch (e) {
                return;
              }
              postLimits(j);
            } catch (e) {}
          });
        }
      } catch (e) {}
      return origSend.apply(this, args);
    };
  } catch (e) {}
})();
