(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 STORAGE_KEY = 'temuWebBridgeStorage';
  const pending = new Map();
  const nativeChrome = window.chrome;

  function dispatchStateChange() {
    window.dispatchEvent(new CustomEvent('temu-web-bridge-state-change'));
  }

  function setBridgeState(active, ready) {
    window.__TEMU_WEB_BRIDGE_ACTIVE__ = Boolean(active);
    window.__TEMU_WEB_BRIDGE_READY__ = Boolean(ready);
    document.documentElement.setAttribute('data-temu-web-bridge', '1');
    document.documentElement.setAttribute('data-temu-extension-installed', active ? '1' : '0');
    document.documentElement.setAttribute('data-temu-bridge-ready', ready ? '1' : '0');
    dispatchStateChange();
  }

  function loadStorage() {
    try {
      return JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}') || {};
    } catch {
      return {};
    }
  }

  function saveStorage(value) {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(value || {}));
  }

  function normalizeStorageKeys(keys, store) {
    if (keys === null || keys === undefined) return { ...store };
    if (typeof keys === 'string') return { [keys]: store[keys] };
    if (Array.isArray(keys)) {
      return keys.reduce((acc, key) => {
        acc[key] = store[key];
        return acc;
      }, {});
    }
    if (typeof keys === 'object') {
      return Object.keys(keys).reduce((acc, key) => {
        acc[key] = store[key] === undefined ? keys[key] : store[key];
        return acc;
      }, {});
    }
    return {};
  }

  function promisifyCallback(result, callback) {
    if (typeof callback === 'function') {
      queueMicrotask(() => callback(result));
    }
    return Promise.resolve(result);
  }

  function postRuntimeMessage(message, timeoutMs) {
    const id = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
    return new Promise((resolve, reject) => {
      const timer = window.setTimeout(() => {
        pending.delete(id);
        reject(new Error('Execution plugin is not connected'));
      }, timeoutMs || 30000);
      pending.set(id, { resolve, reject, timer });
      window.postMessage({ source: 'xiaoqingwa-web', type: BRIDGE_REQUEST, id, message }, window.location.origin);
    });
  }

  window.addEventListener('message', (event) => {
    if (event.source !== window || !event.data) return;
    if (event.data.type === BRIDGE_RESPONSE) {
      const item = pending.get(event.data.id);
      if (!item) return;
      pending.delete(event.data.id);
      window.clearTimeout(item.timer);
      if (event.data.error) {
        item.reject(new Error(event.data.error));
      } else {
        item.resolve(event.data.response);
      }
      return;
    }
    if (event.data.type === BRIDGE_PONG) {
      setBridgeState(true, true);
    }
  });

  const storageLocal = nativeChrome?.storage?.local || {
    get(keys, callback) {
      return promisifyCallback(normalizeStorageKeys(keys, loadStorage()), callback);
    },
    set(values, callback) {
      const store = loadStorage();
      Object.assign(store, values || {});
      saveStorage(store);
      return promisifyCallback(undefined, callback);
    },
    remove(keys, callback) {
      const store = loadStorage();
      const list = Array.isArray(keys) ? keys : [keys];
      list.filter(Boolean).forEach(key => delete store[key]);
      saveStorage(store);
      return promisifyCallback(undefined, callback);
    },
    clear(callback) {
      saveStorage({});
      return promisifyCallback(undefined, callback);
    }
  };

  const runtime = {
    ...(nativeChrome?.runtime || {}),
    getURL(path) {
      if (nativeChrome?.runtime?.getURL) return nativeChrome.runtime.getURL(path);
      return String(path || '').replace(/^\/+/, '');
    },
    sendMessage(message, callback) {
      const promise = nativeChrome?.runtime?.sendMessage
        ? Promise.resolve(nativeChrome.runtime.sendMessage(message))
        : postRuntimeMessage(message, message?.timeoutMs || 30000);
      if (typeof callback === 'function') {
        promise.then(result => callback(result)).catch(error => callback({ success: false, error: error.message }));
      }
      return promise;
    }
  };

  window.chrome = {
    ...(nativeChrome || {}),
    runtime,
    storage: {
      ...(nativeChrome?.storage || {}),
      local: storageLocal
    }
  };

  window.__TEMU_WEB_BRIDGE_POST_MESSAGE__ = postRuntimeMessage;
  setBridgeState(false, false);
  window.postMessage({ source: 'xiaoqingwa-web', type: BRIDGE_PING }, window.location.origin);
  window.setTimeout(() => {
    if (!window.__TEMU_WEB_BRIDGE_READY__) dispatchStateChange();
  }, 800);
})();
