(() => {
  if (window.__MMW_ADMIN_PAGE_PROBE_BRIDGE__) return;
  window.__MMW_ADMIN_PAGE_PROBE_BRIDGE__ = true;
  if (isProbeBlockedHost(location.hostname)) return;

  const ACTION_LOG = "MMW_ADMIN_PAGE_PROBE_LOG";
  const ACTION_CONFIG = "MMW_ADMIN_PAGE_PROBE_CONFIG";
  const STORAGE_KEYS = [
    "adminDebugEnabled",
    "adminDebugPageProbeEnabled",
    "adminDebugReferenceCaptureEnabled",
    "adminDebugReferenceCaptureRules"
  ];
  const MIN_LOG_GAP_MS = 450;
  const MAX_LOGS_PER_MINUTE = 80;
  const MIN_REFERENCE_LOG_GAP_MS = 25;
  const MAX_REFERENCE_LOGS_PER_MINUTE = 1200;
  const MAX_STRING = 1200;
  const MAX_ARRAY = 12;
  const MAX_KEYS = 28;
  const REFERENCE_COMPACT_PROFILE = {
    maxString: 4800,
    maxArray: 48,
    maxKeys: 96,
    maxDepth: 14
  };
  const SENSITIVE_KEY_RE = /token|authorization|cookie|password|passwd|secret|session|csrf|credential|access[_-]?key|refresh[_-]?key/i;

  let lastLogAt = 0;
  let lastReferenceLogAt = 0;
  let lastConfigEnabled = false;
  const minuteWindow = [];
  const referenceMinuteWindow = [];

  window.addEventListener("message", (event) => {
    if (event.source !== window) return;
    const data = event.data;
    if (!data || data.action !== ACTION_LOG || !data.data) return;
    const eventName = data.data.event || "page-event";
    if (shouldThrottleLog(eventName)) return;
    chrome.runtime.sendMessage({
      type: "ADMIN_DEBUG_LOG",
      entry: {
        source: "page-probe",
        event: eventName,
        level: data.data.level || "info",
        pageUrl: data.data.href || location.href,
        payload: {
          seq: data.data.seq,
          href: data.data.href || location.href,
          frameUrl: location.href,
          payload: compactLogPayload(eventName, data.data.payload)
        }
      }
    }).catch(() => {});
  });

  chrome.storage.onChanged.addListener((changes, areaName) => {
    if (areaName !== "local") return;
    if (STORAGE_KEYS.some((key) => Object.prototype.hasOwnProperty.call(changes, key))) {
      syncConfig();
    }
  });

  syncConfig();

  async function syncConfig() {
    const values = await chrome.storage.local.get(STORAGE_KEYS).catch(() => ({}));
    const referenceCaptureEnabled = values.adminDebugReferenceCaptureEnabled === true;
    const configEnabled = values.adminDebugEnabled === true && (values.adminDebugPageProbeEnabled === true || referenceCaptureEnabled);
    if (!configEnabled && !lastConfigEnabled) return;
    lastConfigEnabled = configEnabled;
    window.postMessage({
      action: ACTION_CONFIG,
      enabled: configEnabled,
      referenceCapture: {
        enabled: referenceCaptureEnabled,
        rules: values.adminDebugReferenceCaptureRules && typeof values.adminDebugReferenceCaptureRules === "object"
          ? values.adminDebugReferenceCaptureRules
          : {}
      }
    }, "*");
  }

  function shouldThrottleLog(eventName) {
    const isReference = String(eventName || "").startsWith("reference-");
    const minGap = isReference ? MIN_REFERENCE_LOG_GAP_MS : MIN_LOG_GAP_MS;
    const maxPerMinute = isReference ? MAX_REFERENCE_LOGS_PER_MINUTE : MAX_LOGS_PER_MINUTE;
    const windowRef = isReference ? referenceMinuteWindow : minuteWindow;
    const now = Date.now();
    const lastAt = isReference ? lastReferenceLogAt : lastLogAt;
    if (now - lastAt < minGap) return true;
    if (isReference) lastReferenceLogAt = now;
    else lastLogAt = now;
    while (windowRef.length && now - windowRef[0] > 60000) windowRef.shift();
    if (windowRef.length >= maxPerMinute) return true;
    windowRef.push(now);
    return false;
  }

  function compactLogPayload(eventName, payload) {
    return compactValue(
      payload,
      0,
      "",
      String(eventName || "").startsWith("reference-") ? REFERENCE_COMPACT_PROFILE : null
    );
  }

  function compactValue(value, depth = 0, key = "", profile = null) {
    const maxString = profile?.maxString || MAX_STRING;
    const maxArray = profile?.maxArray || MAX_ARRAY;
    const maxKeys = profile?.maxKeys || MAX_KEYS;
    const maxDepth = profile?.maxDepth || 3;
    if (SENSITIVE_KEY_RE.test(key)) return "[redacted]";
    if (value === null || value === undefined) return value;
    if (typeof value === "string") return truncate(value, maxString);
    if (typeof value === "number" || typeof value === "boolean") return value;
    if (typeof value === "bigint") return String(value);
    if (typeof value === "function") return "[function]";
    if (depth >= maxDepth) return "[depth-limit]";
    if (Array.isArray(value)) {
      const items = value.slice(0, maxArray).map((item) => compactValue(item, depth + 1, key, profile));
      if (value.length > maxArray) items.push(`[${value.length - maxArray} more]`);
      return items;
    }
    if (typeof value === "object") {
      const result = {};
      for (const [itemKey, itemValue] of Object.entries(value).slice(0, maxKeys)) {
        result[itemKey] = compactValue(itemValue, depth + 1, itemKey, profile);
      }
      return result;
    }
    return String(value);
  }

  function truncate(value, max) {
    const text = String(value || "");
    return text.length > max ? `${text.slice(0, max)}...[truncated ${text.length - max}]` : text;
  }

  function isProbeBlockedHost(hostname) {
    const host = String(hostname || "").toLowerCase();
    return /(^|\.)pay\.weixin\.qq\.com$/.test(host)
      || /(^|\.)wxpay\.qq\.com$/.test(host)
      || /(^|\.)alipay\.com$/.test(host)
      || /(^|\.)alipayobjects\.com$/.test(host)
      || /(^|\.)paypal\.com$/.test(host);
  }
})();
