/**
 * JTZL_WebIRC_Chat - Theme Toggle Component
 *
 * @package   JTZL_WebIRC_Chat
 * @copyright Copyright (c) 2025, JT. G.
 * @license   GPL-3.0+
 * @since     3.0.0
 */

import { Moon, Sun } from 'lucide-react';
import { Button } from './button';
import { useTheme } from '../providers/ThemeProvider';
import { THEMES } from '../../lib/theme-constants';

interface ThemeToggleProps {
	className?: string;
}

export function ThemeToggle({ className }: ThemeToggleProps) {
	const { theme, setTheme, actualTheme } = useTheme();

	// Cycle through all three theme options: light -> dark -> system -> light
	const toggleTheme = () => {
		if (theme === THEMES.LIGHT) {
			setTheme(THEMES.DARK);
		} else if (theme === THEMES.DARK) {
			setTheme(THEMES.SYSTEM);
		} else {
			setTheme(THEMES.LIGHT);
		}
	};

	// Get the next theme in the cycle for better UX messaging
	const getNextTheme = () => {
		if (theme === THEMES.LIGHT) return 'dark';
		if (theme === THEMES.DARK) return 'system';
		return 'light';
	};

	const nextTheme = getNextTheme();
	const currentThemeLabel =
		theme === THEMES.SYSTEM ? `system (${actualTheme})` : theme;

	return (
		<Button
			variant="ghost"
			size="sm"
			onClick={toggleTheme}
			className={`theme-toggle ${className || ''}`}
			aria-label={`Switch from ${currentThemeLabel} to ${nextTheme} theme`}
			title={`Current theme: ${currentThemeLabel}. Click to switch to ${nextTheme} theme.`}
		>
			<span className="sr-only">
				{`Current theme: ${currentThemeLabel}. Click to switch to ${nextTheme} theme.`}
			</span>
			<div className="relative">
				{actualTheme === THEMES.LIGHT ? (
					<Sun
						className="h-4 w-4 transition-all duration-300 ease-in-out"
						aria-hidden="true"
					/>
				) : (
					<Moon
						className="h-4 w-4 transition-all duration-300 ease-in-out"
						aria-hidden="true"
					/>
				)}
				{/* Visual indicator for system theme */}
				{theme === THEMES.SYSTEM && (
					<span
						className="system-indicator absolute -top-1 -right-1 h-2 w-2 rounded-full bg-blue-500 shadow-sm"
						aria-hidden="true"
					/>
				)}
			</div>
		</Button>
	);
}
