<script setup>
import { ref } from "vue";
import { Splide, SplideSlide } from "@splidejs/vue-splide";
import "@splidejs/splide/dist/css/splide.min.css";

const props = defineProps({
  question: {
    type: Object,
    required: true,
  },
});
defineEmits(["answerSelected"]);

const slides = ref();
const answerWeight = ref(props.question.answers[0].weight);

function selectAnswer(answer) {
  const answerIndex = props.question.answers.findIndex(
    (a) => a.id === answer.id
  );
  slides.value.splide.go(answerIndex);
}
function slideMove(splide, newIndex) {
  answerWeight.value = props.question.answers[newIndex].weight;
}
</script>

<template>
  <div class="main">
    <div class="top">
      <legend>{{ question.title }}</legend>
      <template v-if="question.answers">
        <div class="choice" v-for="answer in question.answers" :key="answer.id">
          <label>
            <input
              type="radio"
              :data-answerId="answer.id"
              :name="`question_${question.id}`"
              :value="answer.weight"
              v-model="answerWeight"
              @click="selectAnswer(answer)"
            />
            {{ answer.title }}
          </label>
        </div>
      </template>
    </div>
    <div class="bottom">
      <template v-if="question.answers">
        <Splide
          @splide:move="slideMove"
          class="answers"
          :id="`question_${question.id}`"
          ref="slides"
        >
          <SplideSlide
            v-for="answer in question.answers"
            :key="answer.id"
            @click="$emit('answerSelected', question, answerWeight)"
          >
            <img
              height="200"
              :src="`/answers/${answer.image}.png`"
            />
          </SplideSlide>
        </Splide>
      </template>
    </div>
  </div>
</template>

<style lang="sass" scoped>
input[type=radio]
  margin-right: .5rem

.main
  height: 100%
  max-width: 100%
  display: flex
  flex-direction: column
  justify-content: space-around
  align-items: center

  .bottom
    width: 400px
    max-width: 100%
    min-width: 280px

.answers
  text-align: center

@media only screen and (orientation : landscape)
  .main
    flex-direction: row

    .bottom
      max-width: 50%
</style>
