<script lang="ts">
	import { resolve } from '$app/paths';
	import logo from '$lib/assets/logo_governo_PE.png';
	import type { Snippet } from 'svelte';
	import { onMount } from 'svelte';
	import { aplicarTemaDaisyUI } from '$lib/utils/temas';

	type HeaderProps = {
		left?: Snippet;
		right?: Snippet;
	};

	const { left, right }: HeaderProps = $props();

	let themeSelectEl: HTMLSelectElement | null = null;

	function safeGetThemeLS(): string | null {
		try {
			const t = localStorage.getItem('theme');
			return t && t.trim() ? t : null;
		} catch {
			return null;
		}
	}

	onMount(() => {
		const persisted = safeGetThemeLS();
		if (persisted) {
			// Sincroniza UI + HTML com o valor persistido (evita select ficar "aqua" indevido)
			if (themeSelectEl && themeSelectEl.value !== persisted) {
				themeSelectEl.value = persisted;
			}
			aplicarTemaDaisyUI(persisted);
		}
	});

	function onThemeChange(e: Event) {
		const nextValue = (e.currentTarget as HTMLSelectElement | null)?.value ?? null;

		// Se o theme-change não atualizar (caso comum após login/logout),
		// garantimos aqui a persistência + aplicação imediata.
		if (nextValue) {
			try {
				localStorage.setItem('theme', nextValue);
			} catch {
				// ignore
			}
			aplicarTemaDaisyUI(nextValue);
		}
	}
</script>

<header
	class="bg-base-200 border-base-100 sticky top-0 z-50 w-full border-b py-3 shadow-sm backdrop-blur-md transition-all duration-300"
>
	<div class=" flex h-16 w-full items-center justify-between px-4">
		<div class="flex items-center gap-3">
			{#if left}
				{@render left()}
			{/if}

			<a
				href={resolve('/')}
				class="group flex items-center gap-3 transition-transform hover:scale-[1.02]"
			>
				<img src={logo} alt="Logo Governo PE" class="h-10 w-auto object-contain drop-shadow-sm" />
				<div class="hidden flex-col sm:flex">
					<span class="text-primary text-2xl font-bold tracking-wider uppercase">SGSE</span>
					<span class="text-base-content -mt-1 text-lg leading-none font-extrabold tracking-tight"
						>Sistema de Gestão da Secretaria de Esportes</span
					>
				</div>
			</a>
		</div>

		<div class="flex items-center gap-2">
			<select
				bind:this={themeSelectEl}
				class="select select-sm bg-base-100 border-base-300 w-40"
				aria-label="Selecionar tema"
				data-choose-theme
				onchange={onThemeChange}
			>
				<option value="aqua">Aqua</option>
				<option value="sgse-blue">Azul</option>
				<option value="sgse-green">Verde</option>
				<option value="sgse-orange">Laranja</option>
				<option value="sgse-red">Vermelho</option>
				<option value="sgse-pink">Rosa</option>
				<option value="sgse-teal">Verde-água</option>
				<option value="sgse-corporate">Corporativo</option>
				<option value="light">Claro</option>
				<option value="dark">Escuro</option>
			</select>

			{#if right}
				{@render right()}
			{/if}
		</div>
	</div>
</header>
