(() => {
  const root = document.documentElement;
  const themeButtons = document.querySelectorAll('.theme-button');
  const STORAGE_KEY = 'signal-admin-theme';

  function setTheme(theme) {
    root.setAttribute('data-theme', theme);
    themeButtons.forEach((button) => {
      const active = button.dataset.theme === theme;
      button.dataset.active = active ? 'true' : 'false';
      button.setAttribute('aria-checked', active ? 'true' : 'false');
    });
    try {
      localStorage.setItem(STORAGE_KEY, theme);
    } catch {
      // ignore
    }
  }

  function initTheme() {
    let theme = 'light';
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored === 'light' || stored === 'dark') {
        theme = stored;
      } else if (window.matchMedia &&
                 window.matchMedia('(prefers-color-scheme: dark)').matches) {
        theme = 'dark';
      }
    } catch {
      // keep default
    }
    setTheme(theme);
  }

  themeButtons.forEach((button) => {
    button.addEventListener('click', () => {
      const nextTheme = button.dataset.theme || 'light';
      setTheme(nextTheme);
    });
  });

  // Simple detail binding: in a real app you’d map row cells to detail fields
  const rows = document.querySelectorAll('#user-table tbody tr');
  const detailEmpty = document.querySelector('.detail-empty');
  const detailBody = document.querySelector('.detail-body');

  rows.forEach((row) => {
    row.addEventListener('click', () => {
      detailEmpty.style.display = 'none';
      detailBody.style.display = 'block';
      // You can read row.cells here and update #detail-* elements.
    });
  });

  initTheme();
})();