<script lang="ts">
	import '../app.css';
	import { page } from '$app/stores';
	import { onMount } from 'svelte';

	let { children } = $props();

	type ThemeOverride = 'dark' | 'light' | null;
	let override = $state<ThemeOverride>(null);
	let systemDark = $state(true);

	let isDark = $derived(override !== null ? override === 'dark' : systemDark);

	$effect(() => {
		document.documentElement.classList.toggle('dark', isDark);
	});

	function toggleTheme() {
		const next = !isDark;
		if (next === systemDark) {
			override = null;
			localStorage.removeItem('hold-slayer-theme');
		} else {
			override = next ? 'dark' : 'light';
			localStorage.setItem('hold-slayer-theme', override);
		}
	}

	onMount(() => {
		const mq = window.matchMedia('(prefers-color-scheme: dark)');
		systemDark = mq.matches;

		const stored = localStorage.getItem('hold-slayer-theme');
		if (stored === 'dark' || stored === 'light') {
			override = stored as ThemeOverride;
		}

		const onSystemChange = (e: MediaQueryListEvent) => {
			systemDark = e.matches;
		};
		mq.addEventListener('change', onSystemChange);
		return () => mq.removeEventListener('change', onSystemChange);
	});

	const nav = [{ href: '/', label: 'Dashboard' }];
</script>

<div class="min-h-screen bg-slate-50 dark:bg-gray-950 text-gray-900 dark:text-gray-100">
	<header
		class="border-b border-gray-200 dark:border-gray-800 bg-white/80 dark:bg-gray-900/80 backdrop-blur sticky top-0 z-10"
	>
		<div class="mx-auto max-w-7xl px-4 py-3 flex items-center gap-6">
			<div class="flex items-center gap-2">
				<span class="text-orange-500 text-lg leading-none">🔥</span>
				<span class="font-semibold text-gray-900 dark:text-white tracking-tight">Hold Slayer</span>
				<span class="text-gray-500 text-sm hidden sm:inline">Gateway</span>
			</div>
			<nav class="flex gap-1 ml-2">
				{#each nav as item}
					<a
						href={item.href}
						class="px-3 py-1.5 rounded text-sm font-medium transition-colors {$page.url.pathname ===
						item.href
							? 'bg-orange-600 text-white'
							: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-800'}"
					>
						{item.label}
					</a>
				{/each}
			</nav>
			<button
				onclick={toggleTheme}
				class="ml-auto text-xs px-2.5 py-1 rounded-full bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 border border-gray-200 dark:border-gray-700 hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
				title={isDark ? 'Switch to light mode' : 'Switch to dark mode'}
			>
				{isDark ? 'Light' : 'Dark'}
			</button>
		</div>
	</header>

	<main class="mx-auto max-w-7xl px-4 py-6">
		{@render children()}
	</main>
</div>
