// theme-toggle.js
(function() {
  const STORAGE_KEY = 'danix-theme';
  const DARK_CLASS = 'theme-dark';
  const LIGHT_CLASS = 'theme-light';

  // Initialize theme on page load
  function init() {
    const saved = localStorage.getItem(STORAGE_KEY);
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    const isDark = saved === null ? prefersDark : saved === 'dark';

    applyTheme(isDark ? 'dark' : 'light');
  }

  // Apply theme to document
  function applyTheme(theme) {
    const html = document.documentElement;

    html.classList.remove(DARK_CLASS, LIGHT_CLASS);

    if (theme === 'dark') {
      html.classList.remove(LIGHT_CLASS);
      localStorage.setItem(STORAGE_KEY, 'dark');
    } else {
      html.classList.add(LIGHT_CLASS);
      localStorage.setItem(STORAGE_KEY, 'light');
    }
  }

  // Get current theme
  function getCurrentTheme() {
    return document.documentElement.classList.contains(LIGHT_CLASS) ? 'light' : 'dark';
  }

  // Toggle theme
  function toggleTheme() {
    const current = getCurrentTheme();
    const next = current === 'dark' ? 'light' : 'dark';
    applyTheme(next);

    // Dispatch custom event for other scripts to listen
    window.dispatchEvent(new CustomEvent('theme-changed', { detail: { theme: next } }));
  }

  // Setup toggle button
  function setupToggleButton() {
    const btn = document.getElementById('theme-switch');
    if (btn) {
      btn.addEventListener('click', toggleTheme);
      updateToggleButtonUI();

      // Listen for theme changes to update button UI
      window.addEventListener('theme-changed', updateToggleButtonUI);
    }
  }

  function updateToggleButtonUI() {
    const btn = document.getElementById('theme-switch');
    if (btn) {
      const current = getCurrentTheme();
      if (current === 'light') {
        btn.classList.add('light');
      } else {
        btn.classList.remove('light');
      }
    }
  }

  // Initialize on DOMContentLoaded
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
      init();
      setupToggleButton();
    });
  } else {
    init();
    setupToggleButton();
  }

  // Expose to global scope for testing
  window.ThemeToggle = {
    toggle: toggleTheme,
    set: applyTheme,
    get: getCurrentTheme,
  };
})();
