<script setup lang="ts">
import { buildPronoun } from '#shared/buildPronoun.ts';
import type { Pronoun } from '#shared/classes.ts';
import { buildFlags } from '#shared/flags.ts';
import type { Flag } from '#shared/flags.ts';
import { loadPronouns } from '~/src/data.ts';

const props = defineProps<{
    mainPronoun?: Pronoun | null;
}>();

const modelValue = defineModel<string[]>({ required: true });

const config = useConfig();
const { $translator: translator, $translateForPronoun: translateForPronoun } = useNuxtApp();

const pronouns = await loadPronouns(config);

const pronoun = computed(() => {
    if (props.mainPronoun) {
        return props.mainPronoun;
    }
    if (config.profile.editorEnabled && config.profile.flags?.defaultPronoun) {
        return buildPronoun(pronouns, config.profile.flags?.defaultPronoun, config, translator);
    }
    return null;
});

const allFlags = computed((): Record<string, Flag> => {
    return buildFlags(config.locale);
});

const allFlagsOptions = computed((): Record<string, string> => {
    const entries = Object.entries(allFlags.value).map(([flagName, flag]) => {
        return [flagName, `${translateForPronoun(flag.display, pronoun.value)}|${flag.display}`];
    });
    entries.sort((a, b) => a[1].localeCompare(b[1]));
    return Object.fromEntries(entries);
});
</script>

<template>
    <ButtonList v-slot="s" v-model="modelValue" :options="allFlagsOptions">
        <Flag
            :name="s.desc.split('|')[0]"
            :alt="s.desc.split('|')[1]"
            :img="`/flags/${s.v}.png`"
            :asterisk="allFlags[s.v].asterisk"
        />
    </ButtonList>
</template>
