<script lang="ts">
	import { browser } from '$app/environment';
	import { onMount } from 'svelte';

	let isDarkMode = $state(false);

	onMount(() => {
		const stored = localStorage.getItem('bibdle-theme');
		if (stored === 'dark') {
			isDarkMode = true;
		} else if (stored === 'light') {
			isDarkMode = false;
		} else {
			isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
		}
	});

	$effect(() => {
		if (isDarkMode) {
			document.documentElement.classList.add('dark');
			document.documentElement.classList.remove('light');
			localStorage.setItem('bibdle-theme', 'dark');
		} else {
			document.documentElement.classList.remove('dark');
			document.documentElement.classList.add('light');
			localStorage.setItem('bibdle-theme', 'light');
		}
	});

	function toggleTheme() {
		isDarkMode = !isDarkMode;
	}
</script>

{#if browser}
	<button
		onclick={toggleTheme}
		aria-label={isDarkMode ? 'Switch to light mode' : 'Switch to dark mode'}
		class="flex items-center gap-2 p-1 text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-100 transition-colors duration-200 cursor-pointer"
	>
		{#if isDarkMode}
			<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" 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 2v2"/>
				<path d="M12 20v2"/>
				<path d="m4.93 4.93 1.41 1.41"/>
				<path d="m17.66 17.66 1.41 1.41"/>
				<path d="M2 12h2"/>
				<path d="M20 12h2"/>
				<path d="m6.34 17.66-1.41 1.41"/>
				<path d="m19.07 4.93-1.41 1.41"/>
			</svg>
		{:else}
			<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
				<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>
			</svg>
		{/if}
		<span class="text-xs uppercase tracking-widest">
			{isDarkMode ? 'Light mode' : 'Dark mode'}
		</span>
	</button>
{/if}
