{% raw %}/**
 * Theme toggle component for dark/light mode switching.
 *
 * Features:
 * - Toggles data-theme attribute on <html> element
 * - Persists preference to localStorage
 * - Respects prefers-color-scheme on initial load
 * - Uses Lucide sun/moon icons
 *
 * AUTO-GENERATED BY PRISM
 */

import { useEffect, useState, type ReactElement } from 'react';
import { Sun, Moon } from 'lucide-react';

type Theme = 'light' | 'dark' | 'system';

const STORAGE_KEY = 'prism-theme';

/**
 * Get the resolved theme based on system preference or explicit choice.
 */
function getResolvedTheme(theme: Theme): 'light' | 'dark' {
  if (theme === 'system') {
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
  }
  return theme;
}

/**
 * Apply theme to the document.
 */
function applyTheme(theme: 'light' | 'dark'): void {
  const root = document.documentElement;
  if (theme === 'dark') {
    root.setAttribute('data-theme', 'dark');
  } else {
    root.removeAttribute('data-theme');
  }
}

export interface ThemeToggleProps {
  /** Size of the toggle button */
  size?: 'sm' | 'md' | 'lg';
  /** Additional CSS classes */
  className?: string;
  /** Show label text */
  showLabel?: boolean;
}

/**
 * Theme toggle button component.
 *
 * @example
 * ```tsx
 * <ThemeToggle />
 * <ThemeToggle size="lg" showLabel />
 * ```
 */
export function ThemeToggle({
  size = 'md',
  className = '',
  showLabel = false,
}: ThemeToggleProps): ReactElement {
  const [theme, setTheme] = useState<Theme>('system');
  const [mounted, setMounted] = useState(false);

  // Get icon size based on button size
  const iconSize = {
    sm: 16,
    md: 20,
    lg: 24,
  }[size];

  // Initialize theme from localStorage or system preference
  useEffect(() => {
    setMounted(true);
    const stored = localStorage.getItem(STORAGE_KEY) as Theme | null;
    if (stored && ['light', 'dark', 'system'].includes(stored)) {
      setTheme(stored);
      applyTheme(getResolvedTheme(stored));
    } else {
      // Default to system preference
      applyTheme(getResolvedTheme('system'));
    }
  }, []);

  // Listen for system preference changes
  useEffect(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

    const handleChange = () => {
      if (theme === 'system') {
        applyTheme(getResolvedTheme('system'));
      }
    };

    mediaQuery.addEventListener('change', handleChange);
    return () => mediaQuery.removeEventListener('change', handleChange);
  }, [theme]);

  const toggleTheme = () => {
    const resolvedCurrent = getResolvedTheme(theme);
    const newTheme: Theme = resolvedCurrent === 'light' ? 'dark' : 'light';

    setTheme(newTheme);
    localStorage.setItem(STORAGE_KEY, newTheme);
    applyTheme(newTheme);
  };

  // Prevent hydration mismatch
  if (!mounted) {
    return (
      <button
        className={`btn-ghost btn-icon ${size === 'sm' ? 'btn-sm' : size === 'lg' ? 'btn-lg' : ''} ${className}`}
        aria-label="Toggle theme"
        disabled
      >
        <div style={{ width: iconSize, height: iconSize }} />
      </button>
    );
  }

  const resolvedTheme = getResolvedTheme(theme);
  const isDark = resolvedTheme === 'dark';

  return (
    <button
      onClick={toggleTheme}
      className={`btn-ghost ${showLabel ? '' : 'btn-icon'} ${size === 'sm' ? 'btn-sm' : size === 'lg' ? 'btn-lg' : ''} ${className}`}
      aria-label={isDark ? 'Switch to light mode' : 'Switch to dark mode'}
      title={isDark ? 'Switch to light mode' : 'Switch to dark mode'}
    >
      {isDark ? (
        <Sun size={iconSize} className="transition-transform duration-normal" />
      ) : (
        <Moon size={iconSize} className="transition-transform duration-normal" />
      )}
      {showLabel && (
        <span className="ml-2">{isDark ? 'Light' : 'Dark'}</span>
      )}
    </button>
  );
}

/**
 * Hook to access current theme state.
 *
 * @example
 * ```tsx
 * const { theme, setTheme, resolvedTheme } = useTheme();
 * ```
 */
export function useTheme() {
  const [theme, setThemeState] = useState<Theme>('system');
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    const stored = localStorage.getItem(STORAGE_KEY) as Theme | null;
    if (stored && ['light', 'dark', 'system'].includes(stored)) {
      setThemeState(stored);
    }
  }, []);

  const setTheme = (newTheme: Theme) => {
    setThemeState(newTheme);
    localStorage.setItem(STORAGE_KEY, newTheme);
    applyTheme(getResolvedTheme(newTheme));
  };

  return {
    theme,
    setTheme,
    resolvedTheme: mounted ? getResolvedTheme(theme) : 'light',
  };
}

export default ThemeToggle;
{% endraw %}
