<script>
	import {base_domain, CookieNames} from "$shared/lib/configuration";
	import {get_cookie, set_cookie} from "$shared/lib/helpers";
	import {createEventDispatcher, onMount} from "svelte";

	const dispatch = createEventDispatcher();

	export let glow = false;
	export let show = false;
	export let selection = "preffered";
	export let size;

	function change(to) {
		selection = to;
		set_cookie(CookieNames.locale, selection, base_domain());
		dispatch("change", selection);
	}

	onMount(() => {
		selection = get_cookie(CookieNames.locale);
		document.addEventListener("keydown", (e) => {
			if (e.code === "Esc") {
				show = false;
			}
		});
		document.addEventListener("click", (e) => {
			if (e.target.closest("[data-locale-switcher-element]") === null) {
				show = false;
			}
		});
	});
</script>

<div class="bg-light padding-x-xs padding-bottom-xs padding-top-xxxs radius-md {glow ? 'inner-glow shadow-xs':''}"
     data-locale-switcher-element
     class:is-hidden={!show}
     role="listbox">
    <div class="flex flex-wrap flex-column"
         role="group">
        <div class="margin-bottom-xs flex-grow">
            <span class="text-xs color-contrast-medium">Language</span>
        </div>
        <div class="flex gap-xs flex-row">
            <div class="ld-switch-popover__option"
                 aria-selected="{selection === 'en' ? 'true' : 'false'}"
                 on:click={() => change("en")}
                 role="option">
                <div class="text-xs margin-top-xxxs padding-x-xxxxs">English</div>
            </div>
            <div class="ld-switch-popover__option"
                 aria-selected="{selection === 'nb' ? 'true' : 'false'}"
                 on:click={() => change("nb")}
                 role="option">
                <div class="text-xs margin-top-xxxs padding-x-xxxxs">Norsk</div>
            </div>
            <div class="ld-switch-popover__option"
                 aria-selected="{selection === 'preffered' ? 'true' : 'false'}"
                 on:click={() => change("preffered")}
                 role="option">
                <div class="text-xs margin-top-xxxs padding-x-xxxxs">Default</div>
            </div>
        </div>
    </div>
</div>
