// Theme toggle: dark/light with localStorage persistence and prefers-color-scheme default
(function () {
  const STORAGE_KEY = 'watchflows-theme'; // shared with the marketing site

  function getPreferred() {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored === 'dark' || stored === 'light') return stored;
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
  }

  function apply(theme) {
    document.documentElement.classList.toggle('dark', theme === 'dark');
    localStorage.setItem(STORAGE_KEY, theme);
    // Update toggle button icon
    const btn = document.getElementById('theme-toggle');
    if (btn) {
      btn.textContent = theme === 'dark' ? '\u2600\uFE0F' : '\uD83C\uDF19';
      btn.setAttribute('aria-label', theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode');
    }
  }

  // Apply dark class immediately to prevent flash (button doesn't exist yet)
  document.documentElement.classList.toggle('dark', getPreferred() === 'dark');

  // Set button icon once DOM is ready
  document.addEventListener('DOMContentLoaded', function () {
    apply(getPreferred());
  });

  // Expose toggle for button click
  window.toggleTheme = function () {
    var next = getPreferred() === 'dark' ? 'light' : 'dark';
    localStorage.setItem(STORAGE_KEY, next);
    apply(next);
  };

  // Listen for system preference changes
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function (e) {
    if (!localStorage.getItem(STORAGE_KEY)) {
      apply(e.matches ? 'dark' : 'light');
    }
  });
})();
