/* Langfuse Lens — Theme Toggle + Sidebar */
const STORAGE_KEY = 'lens_theme';

export function toggleTheme() {
  const current = document.documentElement.getAttribute('data-theme') || 'dark';
  const next = current === 'dark' ? 'light' : 'dark';
  document.documentElement.setAttribute('data-theme', next);
  localStorage.setItem(STORAGE_KEY, next);
}

function initSidebar() {
  const btn = document.getElementById('sidebar-toggle');
  const sidebar = document.getElementById('sidebar');
  const overlay = document.getElementById('sidebar-overlay');
  if (!btn || !sidebar) return;

  function isMobile() {
    return window.matchMedia('(max-width: 768px)').matches;
  }

  function closeMobileSidebar() {
    sidebar.classList.remove('open');
    overlay?.classList.remove('visible');
    document.body.classList.remove('sidebar-open');
  }

  btn.addEventListener('click', () => {
    if (isMobile()) {
      const isOpen = sidebar.classList.toggle('open');
      overlay?.classList.toggle('visible', isOpen);
      document.body.classList.toggle('sidebar-open', isOpen);
    } else {
      sidebar.classList.toggle('collapsed');
    }
  });

  // Close sidebar when clicking overlay
  overlay?.addEventListener('click', closeMobileSidebar);

  // Close sidebar when clicking a nav link (mobile)
  sidebar.querySelectorAll('.nav-item').forEach(link => {
    link.addEventListener('click', () => {
      if (isMobile()) closeMobileSidebar();
    });
  });

  // Close sidebar on resize to desktop
  window.addEventListener('resize', () => {
    if (!isMobile()) {
      sidebar.classList.remove('open');
      overlay?.classList.remove('visible');
      document.body.classList.remove('sidebar-open');
    }
  });
}

function init() {
  const btn = document.getElementById('theme-toggle');
  if (btn) btn.addEventListener('click', toggleTheme);
  initSidebar();
}

// ES modules are deferred; DOM may already be ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', init);
} else {
  init();
}
