(function () {
  if (window.__jobCollectorBridgeInstalled) {
    return;
  }

  window.__jobCollectorBridgeInstalled = true;

  const MESSAGE_TYPE = {
    RAW_CAPTURE_OBSERVED: 'raw_capture_observed'
  };

  const BRIDGE_SOURCE = 'job-collector-bridge';

  function log(action, message, meta) {
    const prefix = `[job-collector][bridge][${action}]`;
    console.warn(prefix, message, meta || {});
  }

  function shouldCaptureUrl(url) {
    try {
      const parsedUrl = new URL(url, window.location.origin);
      const isSupportedRecruitmentHost =
        parsedUrl.hostname === 'fe-api.zhaopin.com' || parsedUrl.hostname.endsWith('.zhaopin.com');
      const isBossApiHost = parsedUrl.hostname === 'www.zhipin.com' || parsedUrl.hostname.endsWith('.zhipin.com');

      if (!isSupportedRecruitmentHost && !isBossApiHost) {
        return false;
      }

      return parsedUrl.pathname.startsWith('/c/i/') || parsedUrl.pathname.startsWith('/wapi/zpgeek/');
    } catch {
      return false;
    }
  }

  function emitObservedCapture(payload) {
    window.postMessage(
      {
        source: BRIDGE_SOURCE,
        type: MESSAGE_TYPE.RAW_CAPTURE_OBSERVED,
        payload: payload
      },
      window.location.origin
    );
  }

  async function safelyReadFetchBody(response) {
    const contentType = response.headers.get('content-type') || '';

    if (!contentType.includes('application/json')) {
      return null;
    }

    try {
      return await response.clone().text();
    } catch {
      return null;
    }
  }

  function installFetchInterceptor() {
    const originalFetch = window.fetch.bind(window);

    window.fetch = async function () {
      const response = await originalFetch.apply(window, arguments);

      try {
        const url = response.url || String(arguments[0]);

        if (!shouldCaptureUrl(url)) {
          return response;
        }

        const body = await safelyReadFetchBody(response);

        if (body !== null) {
          emitObservedCapture({
            url: url,
            method: (arguments[1] && arguments[1].method) || 'GET',
            responseType: 'json',
            responseBody: body,
            source: 'fetch'
          });
        }
      } catch (error) {
        log('fetch_capture_failed', 'Page bridge failed to read fetch response.', {
          error: error instanceof Error ? error.message : String(error)
        });
      }

      return response;
    };
  }

  function installXhrInterceptor() {
    const originalOpen = XMLHttpRequest.prototype.open;
    const originalSend = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function (method, url, async, username, password) {
      this.__jobCollectorMethod = method;
      this.__jobCollectorUrl = String(url);

      return originalOpen.call(
        this,
        method,
        url,
        async === undefined ? true : async,
        username === undefined ? null : username,
        password === undefined ? null : password
      );
    };

    XMLHttpRequest.prototype.send = function (body) {
      this.addEventListener(
        'loadend',
        function () {
          try {
            const responseUrl = this.responseURL || this.__jobCollectorUrl;

            if (!responseUrl || !shouldCaptureUrl(String(responseUrl))) {
              return;
            }

            let responseBody = null;

            if (this.responseType === '' || this.responseType === 'text') {
              responseBody = this.responseText;
            } else if (this.responseType === 'json') {
              responseBody = JSON.stringify(this.response);
            }

            if (!responseBody) {
              return;
            }

            emitObservedCapture({
              url: String(responseUrl),
              method: String(this.__jobCollectorMethod || 'GET'),
              responseType: this.responseType || 'text',
              responseBody: responseBody,
              source: 'xhr'
            });
          } catch (error) {
            log('xhr_capture_failed', 'Page bridge failed to read XHR response.', {
              error: error instanceof Error ? error.message : String(error)
            });
          }
        },
        { once: true }
      );

      return originalSend.call(this, body);
    };
  }

  installFetchInterceptor();
  installXhrInterceptor();
})();
