<script setup>
import data from "@/data.json";

import { ref, computed } from "vue";

import { useStore } from "@/stores";

import { Splide, SplideSlide } from "@splidejs/vue-splide";
import Question from "./Question.vue";
import "@splidejs/splide/dist/css/splide.min.css";
import ScoreHeader from "./ScoreHeader.vue";
import html2canvas from "html2canvas";

const props = defineProps({
  id: {
    type: String,
    required: true,
  },
});

const score = data.find((score) => score.id == props.id);
const slides = ref();

const store = useStore();
const language = store.language;

function formatAnswers(answers) {
  return answers
    .map((answer) => answer.answers_id)
    .map((answer) => {
      const translation = answer.translations.filter(
        (item) => item.languages_code == language
      );
      return {
        id: answer.id,
        title: translation.length > 0 ? translation[0].title : answer.title,
        weight: answer.weight,
        image: answer.image,
      };
    });
}

function formatScore(score) {
  return score.questions
    .map((question) => question.questions_id)
    .map((question) => {
      const translation = question.translations.filter(
        (item) => item.languages_code == language
      );
      const answers = formatAnswers(question.answers);
      return {
        id: question.id,
        weight: answers[0].weight,
        title: translation.length > 0 ? translation[0].title : question.title,
        answers: answers,
        splide: ref(),
      };
    });
}

const title = score ? score.title : "";
const questions = ref(formatScore(score));

const scoreSum = computed(() => {
  return questions.value
    .map((question) => question.weight)
    .reduce((value, currentValue) => value + currentValue, 0);
});
const displayScoreResult = computed(
  () => !questions.value.filter((q) => q.weight == null).length
);
function getResultsFromScore(score) {
  return score.results
    .map((result) => result.results_id)
    .map((result) => {
      const translation = result.translations.filter(
        (item) => item.languages_code == language
      );
      return {
        id: result.id,
        max: result.max,
        min: result.min,
        pde_qtra: result.pde_qtra,
        effets: translation.length > 0 ? translation[0].effets : "",
        facteur: translation.length > 0 ? translation[0].facteur : "",
        pde: translation.length > 0 ? translation[0].pde : "",
      };
    });
}
const results = ref(getResultsFromScore(score));
const result = computed(() =>
  displayScoreResult.value
    ? results.value
        .filter((r) => !r.min || r.min <= scoreSum.value)
        .filter((r) => !r.max || r.max >= scoreSum.value)[0]
    : null
);
function goQuestionSlide(question) {
  console.log(slides.value);
  slides.value.go(
    questions.value.findIndex((element) => element.id === question.id)
  );
}
function answerSelected(question, answerWeight) {
  questions.value.find((q) => q.id === question.id).weight = answerWeight;
}

function nextQuestion() {
  setTimeout(() => {
    slides.value.go(">");
    console.log(slides);
  }, 100);
}

async function share() {
  console.log(document.querySelector(".latest"));
  const canvas = await html2canvas(document.querySelector("html"));
  let anchor = document.createElement("a");
  anchor.download = "download.png";
  anchor.href = canvas.toDataURL("image/png");
  anchor.click();
  anchor.remove();
}
</script>

<template>
  <ScoreHeader v-if="title" :title="title" />
  <Splide
    ref="slides"
    class="questions"
    v-if="questions"
    :options="{
      pagination: false,
      speed: 700,
      height: '100%',
      arrows: false,
      direction: 'ttb',
      wheel: true,
      releaseWheel: true,
    }"
  >
    <SplideSlide v-for="question in questions" :key="question.id">
      <Question
        :question="question"
        @answerSelected="answerSelected"
        @nextQuestion="nextQuestion"
      />
    </SplideSlide>
    <SplideSlide class="latest">
      <template v-if="displayScoreResult && result">
        <div>
          <h2 class="center">Probabilité d'échec</h2>
          <h2 class="center">{{ result.pde_qtra }}</h2>
          <div class="gradient">
            <div
              v-for="(item, index) in [...Array(7).keys()]"
              :class="{ active: result && result.pde_qtra === index + 1 }"
              :key="item"
            >
              {{ index + 1 }}
            </div>
          </div>
          <div class="details">
            <p>Rappel des paramètres choisis :</p>
            <ul>
              <li v-for="question in questions" :key="question.id">
                {{ question.title }} :
                {{
                  question.answers.find(
                    (answer) => answer.weight === question.weight
                  ).title
                }}
              </li>
            </ul>
          </div>
          <button @click="() => share()">Partager</button>
        </div>
      </template>
      <template v-else>
        <div class="noscore">
          <p>
            Aucun score ne peut vous être proposé, vous devez faire une
            sélection sur les paramètres suivants :
          </p>
          <ul>
            <li
              v-for="question in questions.filter((q) => q.weight == null)"
              :key="question.id"
            >
              <a
                @click="
                  (event) => {
                    goQuestionSlide(question);
                    return false;
                  }
                "
                href="javascript:;"
                >{{ question.title }}</a
              >
            </li>
          </ul>
        </div>
      </template>
    </SplideSlide>
  </Splide>
</template>

<style lang="sass" scoped>
.center
  text-align: center
.noscore
  display: flex
  justify-content: center
  align-items: center
  height: 100%
  color: var(--color-text)
  flex-direction: column

  p
    font-size: 1rem
    text-align: center
    margin-bottom: 1rem
  a
    color: var(--color-text)
.questions
  position: fixed
  top: var(--header-size)
  left: 0
  right: 0
  bottom: 0
  background: transparent


.splide__slide
  position: relative
  padding: 1rem

.splide__track
  overflow: visible!important

legend
  font-size: 1.1rem
  font-weight: bold

label
  display: inline-block
  width: 100%
  padding: .3rem

.latest
  background-color: var(--color-highlight-background)
  color: var(--color-highlight-text)
  text-align: center
  display: flex
  align-items: center
  justify-content: center

  h2
    font-size: 2rem
    font-weight: bold
    & + h2
      line-height: 2rem
      font-size: 2.6rem

    @media (max-height: 600px)
      font-size: 1.5rem
      & + h2
        font-size: 2rem

  ul
    text-align: left
    padding-left: 1.5rem
    list-style-type: disc

  .details
    text-align: left !important
    font-family: serif
    font-size: .9rem
    line-height: normal
    background: var(--color-highlight-background)
    border: 1px solid var(--color-highlight-text)
    padding: 1rem

.gradient
  padding: 0 1rem
  height: 3rem
  background-image: linear-gradient(to right, red, red, rgb(255, 255, 0), rgb(255, 255, 0), green, green)
  display: flex
  margin: 2.5rem auto
  align-items: center
  border-radius: 3px
  max-width: 30rem
  text-shadow: 1px 1px 4px var(--color-highlight-text-invert),-1px -1px 4px var(--color-highlight-text-invert), -1px 1px 4px var(--color-highlight-text-invert), 1px -1px 4px var(--color-highlight-text-invert)
  color: var(--color-highlight-text)

  div
    width: calc(100%/7)
    text-align: center
    align-self: center
    font-weight: bold

  .active
    position: relative

    &:before
      content: ""
      border: 1px solid var(--color-highlight-text)
      border-radius: 3px
      top: -2.8rem
      bottom: -1.5rem
      position: absolute
      width: 100%
      font-weight: bold
      display: flex
      align-items: center
      justify-content: center

    &::after
      content: "PdE"
      position: absolute
      font-size: 1rem
      top: -2rem
      bottom: -1.5rem
      left: 0
      right: 0
      line-height: .7rem
      text-shadow: none

.splide__arrows
  position: inherit
</style>
