<script setup lang="ts">
import CountryFlag from 'vue-country-flag-next';
import categories from '~/categories';

onMounted(() => {
  useHead({
    title: $t('mainTitle'),
  });
});

const { setLocale } = useI18n();

const loading = ref(false);

const examStore = useExamStore();
await callOnce(() => examStore.resetExam(), { mode: 'navigation' });

function setAndGo(category: string) {
  loading.value = true;
  examStore.setCategory(category);
  while (true) {
    if (examStore.category === category) {
      return navigateTo('/exam');
    }
  }
}

const langSelect = ref(examStore.lang);

function changeLanguage() {
  examStore.setLang(langSelect.value);
  setLocale(langSelect.value as 'pl' | 'en' | 'de' | 'ua');
}
</script>

<template>
  <div>
    <div v-if="!loading" class="text-3xl m-2 flex flex-col gap-2">
      <span>{{ $t('mainTitle') }}</span>
      <div class="flex gap-2">
        <CountryFlag
          class="block border border-1 border-black"
          :country="langSelect != 'en' ? langSelect : 'gb'"
          size="big"
        />
        <select v-model="langSelect" class="select" @change="changeLanguage">
          <option value="pl">Polish (Polski)</option>
          <option value="en">English</option>
          <option value="de">German (Deutsch)</option>
          <option value="ua">Ukrainian (Українська)</option>
        </select>
      </div>
      <div
        class="flex flex-col flex-wrap gap-2 items-start p-4 bg-slate-100 border-1 border-slate-500 rounded-xl w-fit"
      >
        <div
          v-for="category in categories"
          :key="`btn-${category}`"
          class="flex flex-row gap-3 items-center"
        >
          <button class="btn btn-xl btn-secondary" @click="setAndGo(category)">
            {{ category }}
          </button>
          <div class="flex flex-col text-sm">
            <div>{{ $t(`category.description.${category}`) }}</div>
            <div>{{ $t(`category.age.${category}`) }}</div>
          </div>
        </div>
      </div>
    </div>
    <LoadingScreen v-else />
  </div>
</template>
