
  (() => {
    const topbar = document.querySelector('.mobile-topbar');
    const settingsToggle = document.getElementById('mobile-tools-settings-toggle');
    const settingsMenu = document.getElementById('mobile-tools-settings-menu');
    const themeToggle = document.getElementById('mobile-tools-theme-toggle');
    const themeLabel = themeToggle?.querySelector('.mobile-settings-icon');
    const localeSelect = document.getElementById('mobile-tools-locale-select');

    const updateTopbarHeight = () => {
      if (!topbar) return;
      document.documentElement.style.setProperty('--mobile-topbar-height', `${topbar.getBoundingClientRect().height}px`);
    };
    updateTopbarHeight();
    if (topbar && 'ResizeObserver' in window) new ResizeObserver(updateTopbarHeight).observe(topbar);
    window.addEventListener('orientationchange', () => window.setTimeout(updateTopbarHeight, 120));

    const setSettingsOpen = (open) => {
      if (!settingsMenu || !settingsToggle) return;
      settingsMenu.hidden = !open;
      settingsToggle.setAttribute('aria-expanded', String(open));
    };
    settingsToggle?.addEventListener('click', (event) => {
      event.stopPropagation();
      setSettingsOpen(settingsMenu?.hidden ?? true);
    });
    settingsMenu?.addEventListener('click', (event) => event.stopPropagation());
    document.addEventListener('click', () => setSettingsOpen(false));
    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape') setSettingsOpen(false);
    });

    const applyTheme = (theme) => {
      document.documentElement.dataset.theme = theme;
      if (themeLabel) themeLabel.textContent = theme === 'dark' ? 'Dark' : 'Light';
    };
    applyTheme(document.documentElement.dataset.theme === 'light' ? 'light' : 'dark');
    themeToggle?.addEventListener('click', () => {
      const next = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
      applyTheme(next);
      try { localStorage.setItem('lvonce-theme', next); } catch {}
    });
    window.addEventListener('storage', (event) => {
      if (event.key === 'lvonce-theme' && (event.newValue === 'dark' || event.newValue === 'light')) applyTheme(event.newValue);
    });

    const syncLocale = () => {
      if (!(localeSelect instanceof HTMLSelectElement)) return;
      const locale = window.__taitanI18n?.locale || document.documentElement.lang || 'zh-CN';
      localeSelect.value = locale;
    };
    syncLocale();
    window.addEventListener('taitan:locale-change', syncLocale);
    localeSelect?.addEventListener('change', (event) => {
      const value = event.currentTarget.value;
      if (window.__taitanI18n?.setLocale) window.__taitanI18n.setLocale(value);
      else {
        try { localStorage.setItem('taitan-tools:locale', value); } catch {}
        location.reload();
      }
    });
  })();

