<script lang="ts">
	import { Moon, Sun, Monitor } from 'lucide-svelte';
	import { preferences } from '$lib/stores';
	import { browser } from '$app/environment';
	import { onMount } from 'svelte';

	const themes = [
		{ value: 'cs2light', label: 'Light', icon: Sun },
		{ value: 'cs2dark', label: 'Dark', icon: Moon },
		{ value: 'auto', label: 'Auto', icon: Monitor }
	] as const;

	// Get current theme data
	const currentTheme = $derived(themes.find((t) => t.value === $preferences.theme) || themes[2]);

	const applyTheme = (theme: 'cs2light' | 'cs2dark' | 'auto') => {
		if (!browser) return;

		let actualTheme = theme;

		if (theme === 'auto') {
			const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
			actualTheme = isDark ? 'cs2dark' : 'cs2light';
		}

		document.documentElement.setAttribute('data-theme', actualTheme);
	};

	const handleThemeChange = (theme: 'cs2light' | 'cs2dark' | 'auto') => {
		preferences.setTheme(theme);
		applyTheme(theme);
	};

	// Apply theme on mount and when system preference changes
	onMount(() => {
		applyTheme($preferences.theme);

		const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
		const handler = () => {
			if ($preferences.theme === 'auto') {
				applyTheme('auto');
			}
		};

		mediaQuery.addEventListener('change', handler);
		return () => mediaQuery.removeEventListener('change', handler);
	});
</script>

<!-- Theme Toggle Dropdown -->
<div class="dropdown dropdown-end">
	<button tabindex="0" class="btn btn-circle btn-ghost" aria-label="Theme">
		<currentTheme.icon class="h-5 w-5" />
	</button>
	<ul class="menu dropdown-content z-[1] mt-3 w-52 rounded-box bg-base-100 p-2 shadow-lg">
		{#each themes as theme}
			<li>
				<button
					class:active={$preferences.theme === theme.value}
					onclick={() => handleThemeChange(theme.value)}
				>
					<theme.icon class="h-4 w-4" />
					{theme.label}
					{#if theme.value === 'auto'}
						<span class="text-xs text-base-content/60">(System)</span>
					{/if}
				</button>
			</li>
		{/each}
	</ul>
</div>
