<script lang="ts">
    import { getLocale, locales, localizeHref } from '$lib/paraglide/runtime'
    import { type Locale } from '$lib/paraglide/runtime';
    import { page } from '$app/state'
    import logo from '$lib/assets/logo.svg'

    let { showLogo = true } = $props()

    const localeNames: Record<string, string> = {
        en: 'English',
        de: 'Deutsch',
        hu: 'Magyar',
    }

    let open = $state(false)

    function getHref(locale: Locale): string {
        return page.data.translationSlug
            ? localizeHref(`/blog/${page.data.translationSlug}`, { locale })
            : page.data.metadata
                ? localizeHref('/blog', { locale })
                : localizeHref(page.url.pathname, { locale })
    }
</script>

<div class="relative">
    <button
            onclick={() => open = !open}
            class="flex items-center gap-1 px-3 py-1.5 hover:bg-white/10 transition cursor-pointer select-none"
    >
        {#if showLogo}
            <img src={logo} alt="Logo" class="h-5 w-5" />
        {/if}
        {localeNames[getLocale()] ?? getLocale()}
        <span class="text-xs opacity-60 transition-transform duration-150" class:rotate-180={open}>▾</span>
    </button>

    {#if open}
        <button
                class="fixed inset-0 z-10 cursor-default"
                style="background: transparent; border: none;"
                onclick={() => open = false}
                aria-label="Close language switcher"
        ></button>

        <ul
                class="absolute right-0 mt-1 z-20 rounded shadow-lg overflow-hidden min-w-28 text-sm"
                style="background-color: #0a3d57;"
                role="menu"
        >
            {#each [...locales].filter(l => l !== getLocale()).sort() as locale}
                <li role="none">
                    <a
                    href={getHref(locale)}
                    data-sveltekit-reload
                    onclick={() => open = false}
                    role="menuitem"
                    class="block px-4 py-2 transition hover:bg-white/10 cursor-pointer"
                    >
                    {localeNames[locale] ?? locale}
                    </a>
                </li>
            {/each}
        </ul>
    {/if}
</div>