<script lang="ts" setup>
import { computed, watch } from "vue";
import localeStore from "../store/localeStore.ts";
import { useI18n } from "vue-i18n";
import { DropdownChangeEvent } from "primevue/dropdown";
import { usePrimeVue } from "primevue/config";
import primeVue_de from "@/i18n/translations/primevue/prime_vue_local_de.json";
import primeVue_en from "@/i18n/translations/primevue/prime_vue_local_en.json";
const { t } = useI18n({ useScope: "global" });

const countries = computed(() => [
  { name: t("english"), code: "en", icon: "🇬🇧" },
  { name: t("german"), code: "de", icon: "🇩🇪" },
]);

function displayIcon(code: string) {
  return countries.value.find((country) => country.code === code)?.icon;
}

function displayCountry(code: string) {
  return countries.value.find((country) => country.code === code)?.name;
}

const primeVueConfig = usePrimeVue();

function updateLocale(locale: string) {
  localeStore().setLocale(locale);

  if (locale === "de") {
    primeVueConfig.config.locale = primeVue_de;
  } else {
    primeVueConfig.config.locale = primeVue_en;
  }
}

updateLocale(localeStore().locale);
</script>
<template>
  <Dropdown
    v-model="$i18n.locale"
    :options="$i18n.availableLocales"
    option-label="name"
    placeholder="Select a Language"
    class="w-full md:w-14rem"
    @change="updateLocale($event.value)"
  >
    <template #value="slotProps">
      <div v-if="slotProps.value" class="flex align-items-center">
        <div class="mr-2 flag">{{ displayIcon(slotProps.value) }}</div>
        <div>{{ displayCountry(slotProps.value) }}</div>
      </div>
      <span v-else>
        {{ slotProps.placeholder }}
      </span>
    </template>
    <template #option="slotProps">
      <div class="flex align-items-center">
        <div class="mr-2 flag">{{ displayIcon(slotProps.option) }}</div>
        <div>{{ displayCountry(slotProps.option) }}</div>
      </div>
    </template>
  </Dropdown>
</template>
