<script setup>
import { ref, computed, onMounted } from 'vue'
import { useQuizStore } from '@/stores/quizStore'

const quizStore = useQuizStore()

const showModal = ref(false)
const currentQuestionIndex = ref(0)
const selectedOption = ref(null)
const showResult = ref(false)
const isCorrect = ref(false)
const resultExplanation = ref('')
const isLoading = ref(false)

const currentQuestion = computed(() => quizStore.questions[currentQuestionIndex.value])
const totalQuestions = computed(() => quizStore.totalQuestions)
const progress = computed(() => ((currentQuestionIndex.value + 1) / totalQuestions.value) * 100)

// Auto-show modal after 3-5 seconds if canPlayToday
onMounted(() => {
  if (quizStore.canPlayToday) {
    setTimeout(() => {
      openModal()
    }, 3500) // 3.5 seconds
  }
})

async function openModal() {
  if (!quizStore.canPlayToday) {
    alert('Már játszottál ma! Holnap próbáld újra.')
    return
  }
  
  isLoading.value = true
  try {
    // Fetch daily quiz questions from API
    await quizStore.fetchDailyQuiz()
    resetQuiz()
    showModal.value = true
  } catch (error) {
    console.error('Failed to load daily quiz:', error)
    alert('Hiba történt a kvíz betöltése közben. Próbáld újra később.')
  } finally {
    isLoading.value = false
  }
}

function closeModal() {
  showModal.value = false
}

function resetQuiz() {
  currentQuestionIndex.value = 0
  selectedOption.value = null
  showResult.value = false
  isCorrect.value = false
  resultExplanation.value = ''
}

async function selectOption(optionIndex) {
  if (showResult.value) return
  selectedOption.value = optionIndex
  
  try {
    const result = await quizStore.answerQuestion(currentQuestion.value.id, optionIndex)
    isCorrect.value = result.is_correct
    resultExplanation.value = result.explanation
    showResult.value = true
  } catch (error) {
    console.error('Failed to submit answer:', error)
    alert('Hiba történt a válasz beküldése közben.')
  }
}

function nextQuestion() {
  if (currentQuestionIndex.value < totalQuestions.value - 1) {
    currentQuestionIndex.value++
    selectedOption.value = null
    showResult.value = false
  } else {
    finishQuiz()
  }
}

async function finishQuiz() {
  try {
    await quizStore.completeDailyQuiz()
    showModal.value = false
    alert(`Kvíz befejezve! Szerezttél ${quizStore.userPoints} pontot. Streak: ${quizStore.currentStreak}`)
  } catch (error) {
    console.error('Failed to complete quiz:', error)
    alert('Hiba történt a kvíz befejezése közben.')
  }
}

function skipToday() {
  quizStore.completeDailyQuiz() // mark as played today
  closeModal()
}
</script>

<template>
  <div v-if="showModal" class="fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 p-4">
    <div class="relative w-full max-w-2xl rounded-2xl bg-gradient-to-br from-blue-50 to-white shadow-2xl p-6 md:p-8 border border-blue-200">
      <!-- Close button -->
      <button @click="closeModal" class="absolute top-4 right-4 text-gray-500 hover:text-gray-800 text-2xl">
        &times;
      </button>

      <!-- Header -->
      <div class="text-center mb-6">
        <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gradient-to-r from-blue-500 to-purple-500 mb-4">
          <span class="text-3xl">🧠</span>
        </div>
        <h2 class="text-3xl font-bold text-gray-900">Napi Kvíz</h2>
        <p class="text-gray-600 mt-2">Teszteld tudásod és szerezz pontokat!</p>
        <div class="mt-4 flex items-center justify-between text-sm text-gray-700">
          <div class="flex items-center gap-2">
            <span class="font-bold">Pontok:</span>
            <span class="bg-blue-100 text-blue-800 px-3 py-1 rounded-full">{{ quizStore.userPoints }}</span>
          </div>
          <div class="flex items-center gap-2">
            <span class="font-bold">Streak:</span>
            <span class="bg-amber-100 text-amber-800 px-3 py-1 rounded-full">{{ quizStore.currentStreak }} nap</span>
          </div>
        </div>
      </div>

      <!-- Progress bar -->
      <div class="mb-8">
        <div class="flex justify-between text-sm text-gray-700 mb-2">
          <span>Kérdés {{ currentQuestionIndex + 1 }} / {{ totalQuestions }}</span>
          <span>{{ Math.round(progress) }}%</span>
        </div>
        <div class="h-3 bg-gray-200 rounded-full overflow-hidden">
          <div class="h-full bg-gradient-to-r from-blue-500 to-purple-500 transition-all duration-500" :style="{ width: `${progress}%` }"></div>
        </div>
      </div>

      <!-- Question -->
      <div class="mb-8">
        <h3 class="text-xl font-semibold text-gray-900 mb-6">{{ currentQuestion.question }}</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <button
            v-for="(option, idx) in currentQuestion.options"
            :key="idx"
            @click="selectOption(idx)"
            class="p-4 text-left rounded-xl border-2 transition-all duration-300"
            :class="{
              'border-blue-500 bg-blue-50': selectedOption === idx,
              'border-gray-300 hover:border-blue-400 hover:bg-blue-50': selectedOption === null && !showResult,
              'border-green-500 bg-green-50': showResult && idx === currentQuestion.correctAnswer,
              'border-red-300 bg-red-50': showResult && selectedOption === idx && !isCorrect,
            }"
            :disabled="showResult"
          >
            <div class="flex items-center">
              <div class="flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center mr-3"
                :class="{
                  'bg-blue-100 text-blue-800': selectedOption === idx && !showResult,
                  'bg-green-100 text-green-800': showResult && idx === currentQuestion.correctAnswer,
                  'bg-red-100 text-red-800': showResult && selectedOption === idx && !isCorrect,
                  'bg-gray-100 text-gray-800': selectedOption !== idx && !showResult,
                }">
                {{ String.fromCharCode(65 + idx) }}
              </div>
              <span class="font-medium">{{ option }}</span>
            </div>
          </button>
        </div>
      </div>

      <!-- Result & Explanation -->
      <div v-if="showResult" class="mb-8 p-5 rounded-xl" :class="isCorrect ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'">
        <div class="flex items-center gap-3 mb-3">
          <div class="w-10 h-10 rounded-full flex items-center justify-center" :class="isCorrect ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'">
            {{ isCorrect ? '✅' : '❌' }}
          </div>
          <h4 class="text-xl font-bold" :class="isCorrect ? 'text-green-800' : 'text-red-800'">
            {{ isCorrect ? 'Helyes válasz!' : 'Sajnos nem talált!' }}
          </h4>
        </div>
        <p class="text-gray-800">{{ resultExplanation }}</p>
        <div class="mt-4 text-sm text-gray-700">
          <span class="font-bold">Pontok:</span> {{ isCorrect ? '+10' : '0' }} |
          <span class="font-bold">Streak:</span> {{ isCorrect ? 'növelve' : 'nullázva' }}
        </div>
      </div>

      <!-- Actions -->
      <div class="flex flex-col sm:flex-row gap-4">
        <button
          v-if="!showResult"
          @click="skipToday"
          class="flex-1 py-3 px-6 rounded-xl border-2 border-gray-300 text-gray-700 font-semibold hover:bg-gray-100 transition"
        >
          Emlékeztess később
        </button>
        <button
          v-if="showResult && currentQuestionIndex < totalQuestions - 1"
          @click="nextQuestion"
          class="flex-1 py-3 px-6 rounded-xl bg-gradient-to-r from-blue-500 to-purple-500 text-white font-bold hover:opacity-90 transition"
        >
          Következő kérdés
        </button>
        <button
          v-if="showResult && currentQuestionIndex === totalQuestions - 1"
          @click="finishQuiz"
          class="flex-1 py-3 px-6 rounded-xl bg-gradient-to-r from-green-500 to-emerald-600 text-white font-bold hover:opacity-90 transition"
        >
          Kvíz befejezése
        </button>
        <button
          @click="closeModal"
          class="flex-1 py-3 px-6 rounded-xl bg-gray-200 text-gray-800 font-semibold hover:bg-gray-300 transition"
        >
          Bezárás
        </button>
      </div>

      <!-- Footer note -->
      <div class="mt-8 text-center text-sm text-gray-500">
        A napi kvíz csak egyszer játszható 24 óránként. Streaked növeléséhez válaszolj helyesen minden nap!
      </div>
    </div>
  </div>
</template>

<style scoped>
/* Additional custom styles if needed */
</style>