<script lang="ts">
	import { onMount } from 'svelte';
	import { availableLanguages, language, setLanguage } from '$lib/i18n';

	let isOpen = false;
	let rootElement: HTMLDivElement | undefined;

	const languageLabels: Record<string, string> = {
		en: 'English',
		fr: 'Francais'
	};

	const languageFlags: Record<string, string> = {
		en: 'GB',
		fr: 'FR'
	};

	function getLanguageLabel(lang: string): string {
		return languageLabels[lang] || lang.toUpperCase();
	}

	function getFlagCode(lang: string): string {
		return languageFlags[lang] || 'UN';
	}

	function toFlagEmoji(code: string): string {
		const normalized = code.toUpperCase();
		if (normalized.length !== 2) {
			return 'UN';
		}

		const first = normalized.codePointAt(0);
		const second = normalized.codePointAt(1);
		if (!first || !second) {
			return 'UN';
		}

		return String.fromCodePoint(127397 + first, 127397 + second);
	}

	function toggleMenu() {
		isOpen = !isOpen;
	}

	function selectLanguage(lang: string) {
		setLanguage(lang);
		isOpen = false;
	}

	onMount(() => {
		const onDocumentClick = (event: MouseEvent) => {
			if (!rootElement) {
				return;
			}

			if (!rootElement.contains(event.target as Node)) {
				isOpen = false;
			}
		};

		document.addEventListener('click', onDocumentClick);
		return () => document.removeEventListener('click', onDocumentClick);
	});
</script>

<div bind:this={rootElement} class="relative">
	<button
		type="button"
		onclick={toggleMenu}
		class="flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-2 text-sm font-semibold text-slate-100 transition hover:border-amber-300/50 hover:bg-white/10"
		aria-haspopup="true"
		aria-expanded={isOpen}
		aria-label="Change language"
	>
		<span class="text-base" aria-hidden="true">{toFlagEmoji(getFlagCode($language))}</span>
		<span class="uppercase text-xs tracking-wider">{$language}</span>
		<svg
			class="h-3.5 w-3.5 transition-transform {isOpen ? 'rotate-180' : ''}"
			fill="none"
			stroke="currentColor"
			viewBox="0 0 24 24"
		>
			<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
		</svg>
	</button>

	{#if isOpen}
		<div class="absolute right-0 top-full z-20 mt-2 w-44 rounded-xl border border-white/10 bg-slate-900/95 p-1 shadow-[0_24px_60px_rgba(0,0,0,0.45)] backdrop-blur">
			{#each availableLanguages as lang (lang)}
				<button
					type="button"
					onclick={() => selectLanguage(lang)}
					class="flex w-full items-center justify-between rounded-lg px-3 py-2 text-left text-sm transition {lang === $language ? 'bg-amber-300 text-slate-900' : 'text-slate-100 hover:bg-white/5'}"
				>
					<span class="flex items-center gap-2">
						<span class="text-base" aria-hidden="true">{toFlagEmoji(getFlagCode(lang))}</span>
						<span>{getLanguageLabel(lang)}</span>
					</span>
					<span class="text-xs uppercase tracking-wide opacity-70">{lang}</span>
				</button>
			{/each}
		</div>
	{/if}
</div>
