
<script lang="ts" setup>

const currentAxe = ref<Axe>();
const currentAxeIdentifier = ref(1);
const questions = computed(() => useQuizStore().questions);
const axes = computed(() => useQuizStore().axes);
const loading = ref(true);
const saving = ref(false);
const isFullRated = ref(false);

import {type Axe, useQuizStore} from "~/store/quiz";

const store = useQuizStore();

onMounted(() => {
  loading.value = true;
  store.initialize().finally(()=> {
    initializeState();
    store.resetResponses();
    loading.value = false;
  });
});

function showPrevious() {
  if (currentAxeIdentifier.value > 1) {
    currentAxeIdentifier.value--;
    initializeState();
  }
}

function showNext() {
  if (currentAxeIdentifier.value < axes.value.length) {
    currentAxeIdentifier.value++;
    initializeState();

    setTimeout(() => {
      scrollTop();
    }, 50)
  }
}

function initializeState() {
  currentAxe.value = axes.value.find(value => value.identifier === currentAxeIdentifier.value);
  const questions = store.questionsRatedPerAxe.get(currentAxeIdentifier.value);
  const unratedQuestions = questions ? questions.filter(value => !value.rated) : [];
  isFullRated.value = unratedQuestions.length === 0;
}

function scrollTop() {
  window.scrollTo({
    top: 60,
    behavior: "smooth",
  });
}

function saveResult() {
  store.save().then((response) => {
    navigateTo({path: "result", query: {quiz: response.id + ""}});
  });
}

function onRate(event: { isFullRated: boolean }) {
  isFullRated.value = event.isFullRated;
}
</script>

<template>
    <div v-if="!loading">
      <quiz-part
        :key="currentAxe.identifier" :axe-number="currentAxe.identifier" :total-axes="axes.length"
        :title="currentAxe.title"
        :description="currentAxe.description"
        :color="currentAxe.color"
        :icon="'balise_' + currentAxe.identifier + '.svg'"
        :questions="questions.get(currentAxe.identifier)"
        @rate="onRate"
      />

      <div class="button-container">
        <nuxt-link
          v-if="currentAxeIdentifier <= 1"
          class="button gray button-back"
          to="/dashboard" aria-label="Précédent">❮
        </nuxt-link>
        <button v-if="currentAxeIdentifier > 1" class="button gray" @click="showPrevious">❮</button>
        <button
          v-if="currentAxeIdentifier < axes.length" class="button blue" :disabled="!isFullRated"
          @click="showNext"
        >Suivant ❯
        </button>
        <button
          v-if="currentAxeIdentifier >= axes.length" class="button orange"
          :disabled="!isFullRated || saving" @click="saveResult()"
        >Valider ❯
        </button>
      </div>
    </div>
    <div v-else class="center">
      <loader/>
    </div>
</template>
