<template>
    <div class="relative">
        <button
            type="button"
            class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-semibold text-slate-600 hover:border-slate-300"
            @click="open = !open"
        >
            {{ activeLanguage.shortLabel.toUpperCase() }}
        </button>
        <div
            v-if="open"
            class="absolute right-0 mt-2 w-56 rounded-xl border border-slate-200 bg-white p-3 shadow-lg"
        >
            <div class="text-xs font-semibold text-slate-500">Language</div>
            <div class="mt-2 space-y-1">
                <button
                    v-for="lang in languages"
                    :key="lang.locale"
                    type="button"
                    class="flex w-full items-center justify-between rounded-lg px-3 py-2 text-left text-xs hover:bg-slate-50"
                    @click="selectLanguage(lang)"
                >
                    <span class="font-semibold text-slate-700">
                        {{ lang.label }}
                    </span>
                    <span class="text-[11px] text-slate-400">
                        {{ lang.currencySymbol }} {{ lang.currency }}
                    </span>
                </button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { computed, ref } from 'vue';

const props = defineProps({
    languages: {
        type: Array,
        default: () => [],
    },
});

const open = ref(false);
const selectedLocale = ref(props.languages[0]?.locale ?? 'en-US');

const activeLanguage = computed(() => {
    return (
        props.languages.find((lang) => lang.locale === selectedLocale.value) ?? {
            shortLabel: 'en',
            label: 'English',
            currency: 'USD',
            currencySymbol: '$',
        }
    );
});

const selectLanguage = (lang) => {
    selectedLocale.value = lang.locale;
    open.value = false;
};
</script>
