---
// ThemeToggle Component
// Features: Sun/moon icons, smooth transitions, localStorage persistence,
//           system preference detection (prefers-color-scheme), ARIA accessible
---

<!-- Unique ID via data attribute; JS uses querySelectorAll to support multiple instances -->
<button
  data-theme-toggle
  type="button"
  role="switch"
  aria-checked="false"
  aria-label="Switch to dark mode"
  title="Toggle dark/light mode"
  class="theme-toggle relative w-10 h-10 flex items-center justify-center rounded-lg text-secondary-600 hover:text-primary hover:bg-secondary-50 dark:text-secondary-400 dark:hover:text-primary-400 dark:hover:bg-secondary-800 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-primary-400 focus:ring-offset-2 dark:focus:ring-offset-secondary-900"
>
  <!-- Sun icon (shown in dark mode to switch to light) -->
  <svg
    class="sun-icon w-5 h-5 absolute transition-all duration-300"
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
  >
    <circle cx="12" cy="12" r="4" />
    <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41" />
  </svg>

  <!-- Moon icon (shown in light mode to switch to dark) -->
  <svg
    class="moon-icon w-5 h-5 absolute transition-all duration-300"
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
  >
    <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
  </svg>
</button>

<!-- Live region: announces theme changes to screen readers without disrupting reading flow -->
<span
  data-theme-live
  role="status"
  aria-live="polite"
  aria-atomic="true"
  class="sr-only"
></span>

<style>
  /* Initial icon states - controlled by JS after load */
  .theme-toggle .sun-icon {
    opacity: 0;
    transform: scale(0.5) rotate(-90deg);
  }

  .theme-toggle .moon-icon {
    opacity: 1;
    transform: scale(1) rotate(0deg);
  }

  /* Dark mode: show sun, hide moon */
  :global(html.dark) .theme-toggle .sun-icon {
    opacity: 1;
    transform: scale(1) rotate(0deg);
  }

  :global(html.dark) .theme-toggle .moon-icon {
    opacity: 0;
    transform: scale(0.5) rotate(90deg);
  }

  /* Respect reduced motion */
  @media (prefers-reduced-motion: reduce) {
    .theme-toggle .sun-icon,
    .theme-toggle .moon-icon {
      transition: none !important;
    }
  }
</style>

<script>
  function initThemeToggles() {
    // Use data attribute selector to support multiple instances (desktop + mobile)
    const btns = document.querySelectorAll<HTMLButtonElement>('[data-theme-toggle]');
    if (!btns.length) return;

    function syncAllButtons(isDark: boolean) {
      const label = isDark ? 'Switch to light mode' : 'Switch to dark mode';
      btns.forEach((btn) => {
        btn.setAttribute('aria-label', label);
        btn.setAttribute('title', label);
        btn.setAttribute('aria-checked', isDark ? 'true' : 'false');
      });
    }

    function announceThemeChange(isDark: boolean) {
      // Announce to screen readers via live region (polite = does not interrupt)
      document.querySelectorAll('[data-theme-live]').forEach((el) => {
        el.textContent = isDark ? 'Dark mode enabled' : 'Light mode enabled';
      });
    }

    function applyTheme(isDark: boolean, announce = false) {
      document.documentElement.classList.toggle('dark', isDark);
      syncAllButtons(isDark);
      if (announce) announceThemeChange(isDark);

      // Update all theme-color meta tags for browser chrome
      const color = isDark ? '#0f172a' : '#0891b2';
      document.querySelectorAll('meta[name="theme-color"]').forEach((m) => {
        m.setAttribute('content', color);
      });
    }

    btns.forEach((btn) => {
      btn.addEventListener('click', () => {
        const newIsDark = !document.documentElement.classList.contains('dark');
        applyTheme(newIsDark, true);
        try {
          localStorage.setItem('theme', newIsDark ? 'dark' : 'light');
        } catch {
          // localStorage not available (e.g. private browsing)
        }
      });
    });

    // Sync ARIA state on init
    const isDark = document.documentElement.classList.contains('dark');
    syncAllButtons(isDark);
  }

  // Run immediately if DOM is ready, otherwise wait
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initThemeToggles);
  } else {
    initThemeToggles();
  }

  // Listen for system preference changes (when no explicit user choice)
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
    const stored = localStorage.getItem('theme');
    if (!stored) {
      const isDark = e.matches;
      document.documentElement.classList.toggle('dark', isDark);
      const color = isDark ? '#0f172a' : '#0891b2';
      document.querySelectorAll('meta[name="theme-color"]').forEach((m) => {
        m.setAttribute('content', color);
      });
      const label = isDark ? 'Switch to light mode' : 'Switch to dark mode';
      document.querySelectorAll('[data-theme-toggle]').forEach((btn) => {
        btn.setAttribute('aria-label', label);
        btn.setAttribute('aria-checked', isDark ? 'true' : 'false');
      });
    }
  });
</script>
