(function () {
  'use strict';

  const BRIDGE_REQUEST = 'TEMU_WEB_BRIDGE_REQUEST';
  const BRIDGE_RESPONSE = 'TEMU_WEB_BRIDGE_RESPONSE';
  const BRIDGE_PING = 'TEMU_WEB_BRIDGE_PING';
  const BRIDGE_PONG = 'TEMU_WEB_BRIDGE_PONG';
  const WEB_APP_SOURCE = 'temu-web-app';
  const EXTENSION_BRIDGE_SOURCE = 'temu-extension-bridge';

  function announceReady() {
    document.documentElement.setAttribute('data-temu-extension-installed', '1');
    document.documentElement.setAttribute('data-temu-bridge-ready', '1');
    window.postMessage({ source: 'xiaoqingwa-extension', type: BRIDGE_PONG }, window.location.origin);
  }

  async function handleRuntimeMessage(message) {
    return await chrome.runtime.sendMessage(message || {});
  }

  const allowedStorageKeys = new Set([
    'temuServerToken',
    'temuServerUser',
    'temuServerAuthAt',
    'temuApiBase',
    'temuAutoBoundShops',
    'temuAuth',
    'temuLocalMallId',
  ]);

  function getBridgePlatform() {
    const path = String(window.location.pathname || '').toLowerCase();
    if (/^\/ozon(?:\/|$)/.test(path)) return 'ozon';
    if (/^\/temu(?:\/|$)/.test(path)) return 'temu';
    return 'temu';
  }

  function isAllowedStorageKey(key) {
    const value = String(key || '');
    if (value === 'temuTemplates') return getBridgePlatform() === 'ozon';
    return allowedStorageKeys.has(value) ||
      /^temuSalesDataCache(_|$)/.test(value) ||
      /^temuSalesCache(_|$)/.test(value) ||
      /^temuCustomizedProductCache(_|$)/.test(value) ||
      /^temuCustomizedTemplates(_|$)/.test(value) ||
      /^temuTemplates_/.test(value);
  }

  function filterStorageKeys(keys) {
    if (keys === null || keys === undefined) return null;
    if (typeof keys === 'string') return isAllowedStorageKey(keys) ? keys : [];
    if (Array.isArray(keys)) return keys.filter(isAllowedStorageKey);
    if (keys && typeof keys === 'object') {
      return Object.fromEntries(Object.entries(keys).filter(([key]) => isAllowedStorageKey(key)));
    }
    return [];
  }

  async function handleStoragePayload(payload = {}) {
    const area = chrome.storage?.local;
    if (!area) throw new Error('Storage API is not available');
    if (payload.type === 'temu-bridge-storage-get') {
      return await area.get(filterStorageKeys(payload.keys));
    }
    if (payload.type === 'temu-bridge-storage-set') {
      const values = Object.fromEntries(
        Object.entries(payload.values || {}).filter(([key]) => isAllowedStorageKey(key))
      );
      if (Object.keys(values).length) await area.set(values);
      return {};
    }
    if (payload.type === 'temu-bridge-storage-remove') {
      const keys = filterStorageKeys(payload.keys || []);
      if (Array.isArray(keys) && keys.length) await area.remove(keys);
      else if (typeof keys === 'string' && keys) await area.remove(keys);
      return {};
    }
    throw new Error(`Unsupported bridge payload: ${payload.type || 'unknown'}`);
  }

  async function handleModernBridgePayload(payload = {}) {
    if (payload.type === 'temu-bridge-ping') {
      return { pong: true };
    }
    if (payload.type === 'temu-bridge-runtime-sendMessage') {
      return { response: await handleRuntimeMessage(payload.message || {}) };
    }
    return { result: await handleStoragePayload(payload) };
  }

  window.addEventListener('message', (event) => {
    if (event.source !== window || !event.data) return;
    if (event.data.type === BRIDGE_PING) {
      announceReady();
      return;
    }

    if (event.data.source === WEB_APP_SOURCE && event.data.requestId) {
      const { requestId, payload } = event.data;
      handleModernBridgePayload(payload)
        .then(result => {
          window.postMessage({
            source: EXTENSION_BRIDGE_SOURCE,
            requestId,
            result: { ok: true, ...result }
          }, window.location.origin);
        })
        .catch(error => {
          window.postMessage({
            source: EXTENSION_BRIDGE_SOURCE,
            requestId,
            result: {
              ok: false,
              error: error?.message || String(error || 'Bridge request failed')
            }
          }, window.location.origin);
        });
      return;
    }

    if (event.data.type !== BRIDGE_REQUEST) return;

    const { id, message } = event.data;
    handleRuntimeMessage(message)
      .then(response => {
        window.postMessage({ source: 'xiaoqingwa-extension', type: BRIDGE_RESPONSE, id, response }, window.location.origin);
      })
      .catch(error => {
        window.postMessage({
          source: 'xiaoqingwa-extension',
          type: BRIDGE_RESPONSE,
          id,
          error: error?.message || String(error || 'Bridge request failed')
        }, window.location.origin);
      });
  });

  announceReady();
})();
