<script lang="ts">
    import { browser } from "$app/environment";
    import { page } from "$app/stores";
    import { setLocale, locale } from "$lib/i18n/i18n-svelte";
    import type { Locales } from "$lib/i18n/i18n-types";
    import { locales } from "$lib/i18n/i18n-util";
    import { loadLocaleAsync } from "$lib/i18n/i18n-util.async";

    const switchLocale = async (newLocale: Locales) => {
        if (!newLocale || $locale === newLocale) return;
        await loadLocaleAsync(newLocale);
        setLocale(newLocale);
        document.querySelector("html")?.setAttribute("lang", newLocale);
    };

    $: if (browser) {
        switchLocale($page.params.lang as Locales);
    }
</script>

<ul>
    {#each locales as aLocale}
        <li>
            <button
                type="button"
                class:active={aLocale === $locale}
                on:click={() => switchLocale(aLocale)}
            >
                {aLocale}
            </button>
        </li>
    {/each}
</ul>
