(function () {
  const api = typeof chrome !== 'undefined' ? chrome : (typeof browser !== 'undefined' ? browser : null);

  function openHome() {
    if (!api || !api.tabs || !api.runtime) return;
    const url = api.runtime.getURL('index.html');
    api.tabs.create({ url });
  }

  function openSidebar() {
    if (!api) return;

    // Edge / Chrome Manifest V3 side panel
    if (api.sidePanel && typeof api.sidePanel.open === 'function' && api.windows) {
      api.windows.getCurrent(function (win) {
        if (!win) return;
        api.sidePanel.open({ windowId: win.id });
      });
      return;
    }

    // Firefox sidebar
    if (api.sidebarAction && typeof api.sidebarAction.open === 'function') {
      api.sidebarAction.open();
      return;
    }

    alert('当前浏览器版本暂不支持通过扩展打开侧边栏。');
  }

  function toggleQr() {
    const panel = document.getElementById('qrPanel');
    if (!panel) return;
    const isShown = panel.style.display === 'flex';
    panel.style.display = isShown ? 'none' : 'flex';
  }

  function init() {
    const btnMini = document.getElementById('btnMiniProgram');
    const btnHome = document.getElementById('btnOpenHome');
    const btnSidebar = document.getElementById('btnOpenSidebar');

    if (btnMini) {
      btnMini.addEventListener('click', toggleQr);
    }
    if (btnHome) {
      btnHome.addEventListener('click', openHome);
    }
    if (btnSidebar) {
      btnSidebar.addEventListener('click', openSidebar);
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

