<script lang="ts">
	import { languageStore } from '$lib/stores/language.svelte';
	import { languages } from '$lib/i18n/translations';
	import { Button } from '$lib/components/ui/button';
	import { Languages } from 'lucide-svelte';

	let showMenu = $state(false);

	function toggleMenu() {
		showMenu = !showMenu;
	}

	function setLanguage(code: 'en' | 'da') {
		languageStore.setLanguage(code);
		showMenu = false;
	}

	function handleClickOutside(event: MouseEvent) {
		const target = event.target as HTMLElement;
		if (!target.closest('.language-toggle-menu')) {
			showMenu = false;
		}
	}

	$effect(() => {
		if (showMenu) {
			document.addEventListener('click', handleClickOutside);
			return () => document.removeEventListener('click', handleClickOutside);
		}
	});
</script>

<div class="relative language-toggle-menu">
	<Button variant="outline" size="icon" onclick={toggleMenu} aria-label="Toggle language">
		<Languages class="h-[1.2rem] w-[1.2rem]" />
	</Button>

	{#if showMenu}
		<div
			class="absolute left-0 sm:right-0 sm:left-auto mt-2 w-40 rounded-md border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950 shadow-lg z-50"
		>
			<div class="py-1">
				{#each languages as lang}
					<button
						type="button"
						class="w-full text-left px-4 py-2 text-sm hover:bg-slate-100 dark:hover:bg-slate-900 transition-colors"
						class:font-bold={languageStore.current === lang.code}
						class:bg-slate-100={languageStore.current === lang.code}
						class:dark:bg-slate-900={languageStore.current === lang.code}
						onclick={() => setLanguage(lang.code)}
					>
						{lang.name}
					</button>
				{/each}
			</div>
		</div>
	{/if}
</div>
