// /assets/js/darkmode.js
(() => {
  const body = document.body;
  const toggle = document.getElementById('themeToggle');
  const icon = document.getElementById('themeIcon');

  // helper to set theme
  function setTheme(mode) {
    if (mode === 'dark') {
      body.classList.add('dark-mode');
      body.classList.remove('light-mode');
      icon.className = 'bi bi-sun-fill';
    } else {
      body.classList.remove('dark-mode');
      body.classList.add('light-mode');
      icon.className = 'bi bi-moon-fill';
    }
    localStorage.setItem('bmellon-theme', mode);
  }

  // initialize from localStorage or prefers-color-scheme
  const saved = localStorage.getItem('bmellon-theme');
  if (saved === 'dark' || (!saved && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
    setTheme('dark');
  } else {
    setTheme('light');
  }

  // click handler
  toggle.addEventListener('click', () => {
    const isDark = body.classList.contains('dark-mode');
    setTheme(isDark ? 'light' : 'dark');
  });
})();
