<template>
  <div class="min-h-screen bg-gray-50 p-4 md:p-8">
    <div class="max-w-4xl mx-auto">
      
      <!-- Header / Title -->
      <div class="mb-6 flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-800">Quiz Runner</h1>
          <p class="text-gray-500">Subject: General Knowledge</p>
        </div>
        <div class="text-right hidden md:block">
          <div class="text-sm text-gray-400">Time Elapsed</div>
          <div class="font-mono text-xl">10:05</div>
        </div>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
        
        <!-- Sidebar: Question Navigator -->
        <div class="lg:col-span-3 order-2 lg:order-1">
          <QCard class="bg-white shadow-sm sticky top-4">
            <QCardSection>
              <div class="text-subtitle1 font-bold mb-3">Questions</div>
              <div class="grid grid-cols-5 gap-2">
                <button
                  v-for="(q, index) in store.questions"
                  :key="q.id"
                  @click="store.goToQuestion(index)"
                  class="w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold transition-all border-2"
                  :class="getIndicatorClass(index, q.id)"
                >
                  {{ index + 1 }}
                </button>
              </div>
              
              <!-- Legend -->
              <div class="mt-6 space-y-2 text-xs text-gray-600">
                <div class="flex items-center gap-2"><div class="w-3 h-3 rounded-full bg-blue-500"></div> Current</div>
                <div class="flex items-center gap-2"><div class="w-3 h-3 rounded-full bg-green-500"></div> Completed</div>
                <div class="flex items-center gap-2"><div class="w-3 h-3 rounded-full bg-orange-500"></div> Skipped</div>
                <div class="flex items-center gap-2"><div class="w-3 h-3 rounded-full bg-gray-300"></div> Not Started</div>
              </div>
            </QCardSection>
          </QCard>
        </div>

        <!-- Main Content: Question -->
        <div class="lg:col-span-9 order-1 lg:order-2">
          <QCard v-if="store.currentQuestion" class="bg-white shadow-md min-h-[400px] flex flex-col">
            
            <!-- Question Header -->
            <QCardSection class="bg-gray-50 border-b border-gray-100 py-4">
              <div class="flex justify-between items-start">
                <div>
                  <QBadge :color="store.currentQuestion.is_skippable ? 'orange' : 'red'" class="mb-2">
                    {{ store.currentQuestion.is_skippable ? 'Optional' : 'Required' }}
                  </QBadge>
                  <h2 class="text-xl font-medium text-gray-800">
                    <span class="text-gray-400 mr-2">{{ store.currentQuestionIndex + 1 }}.</span>
                    {{ store.currentQuestion.title }}
                  </h2>
                </div>
              </div>
            </QCardSection>

            <!-- Question Body -->
            <QCardSection class="flex-grow py-8 px-6">
              
              <!-- Single Choice -->
              <div v-if="store.currentQuestion.type === 'single'">
                <div v-for="opt in store.currentQuestion.options" :key="opt.id" 
                     class="mb-3 p-3 border rounded-lg hover:bg-blue-50 cursor-pointer transition-colors"
                     :class="{ 'border-blue-500 bg-blue-50': currentVal === opt.id, 'border-gray-200': currentVal !== opt.id }"
                     @click="handleInput(opt.id)">
                  <div class="flex items-center">
                    <div class="w-5 h-5 rounded-full border flex items-center justify-center mr-3"
                         :class="{ 'border-blue-500': currentVal === opt.id, 'border-gray-300': currentVal !== opt.id }">
                      <div v-if="currentVal === opt.id" class="w-2.5 h-2.5 rounded-full bg-blue-500"></div>
                    </div>
                    <span class="text-gray-700">{{ opt.label }}</span>
                  </div>
                </div>
              </div>

              <!-- Multiple Choice -->
              <div v-else-if="store.currentQuestion.type === 'multiple'">
                <div v-for="opt in store.currentQuestion.options" :key="opt.id" 
                     class="mb-3 p-3 border rounded-lg hover:bg-blue-50 cursor-pointer transition-colors"
                     :class="{ 'border-blue-500 bg-blue-50': isSelected(opt.id), 'border-gray-200': !isSelected(opt.id) }"
                     @click="toggleSelection(opt.id)">
                  <div class="flex items-center">
                    <div class="w-5 h-5 rounded border flex items-center justify-center mr-3"
                         :class="{ 'border-blue-500 bg-blue-500': isSelected(opt.id), 'border-gray-300': !isSelected(opt.id) }">
                      <QIcon v-if="isSelected(opt.id)" name="check" class="text-white text-xs" />
                    </div>
                    <span class="text-gray-700">{{ opt.label }}</span>
                  </div>
                </div>
              </div>

              <!-- Text Input -->
              <div v-else-if="store.currentQuestion.type === 'text'">
                <QInput
                  v-model="textModel"
                  type="textarea"
                  outlined
                  rows="6"
                  placeholder="Type your answer here..."
                  class="w-full text-lg"
                  @update:model-value="handleTextInput"
                />
              </div>

            </QCardSection>

            <!-- Error Banner -->
            <QBanner v-if="store.lastError" class="bg-red-50 text-red-600 px-6 py-2 border-t border-red-100">
              <template v-slot:avatar>
                <QIcon name="warning" color="red" />
              </template>
              {{ store.lastError }}
            </QBanner>

            <!-- Actions Footer -->
            <QCardSection class="border-t border-gray-100 bg-gray-50 p-4 flex flex-wrap gap-4 items-center justify-between">
              
              <QBtn
                flat
                color="grey-7"
                label="Previous"
                icon="arrow_back"
                :disable="store.isFirstQuestion"
                @click="store.prevQuestion()"
                no-caps
              />

              <div class="flex gap-3">
                <QBtn
                  v-if="store.currentQuestion.is_skippable && store.answers[store.currentQuestion.id]?.status !== 'completed'"
                  flat
                  color="orange-8"
                  label="Skip for now"
                  @click="store.skipQuestion()"
                  no-caps
                />

                <QBtn
                  unelevated
                  :loading="store.loading"
                  :color="isSaved ? 'green' : 'primary'"
                  :label="isSaved ? 'Saved' : 'Save Answer'"
                  :icon="isSaved ? 'check' : 'save'"
                  class="px-6"
                  @click="store.saveCurrentAnswer()"
                  no-caps
                />

                <QBtn
                  unelevated
                  color="grey-9"
                  label="Next"
                  icon-right="arrow_forward"
                  :disable="store.isLastQuestion"
                  @click="store.nextQuestion()"
                  no-caps
                />
              </div>

            </QCardSection>
          </QCard>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, watch, reactive } from 'vue';
import { useRoute } from 'vue-router';
// Composable is auto-imported in Nuxt
// import { useQuizRunner } from '@/composables/useQuizRunner'; 

const route = useRoute();
// Wrap in reactive to unwrap refs, mimicking Pinia store behavior for template
const store = reactive(useQuizRunner());

onMounted(() => {
  const quizId = route.params.id as string;
  store.initQuiz(quizId);
});

// -- Helpers for Input Handling --

const currentVal = computed(() => {
  return store.currentAnswer?.value;
});

const isSaved = computed(() => {
  return store.currentAnswer?.is_saved;
});

// Single Choice
function handleInput(val: string) {
  store.updateAnswer(val);
}

// Text Choice
const textModel = ref('');
// Watch for question changes to reset text model
watch(
  () => store.currentQuestionIndex,
  () => {
    if (store.currentQuestion?.type === 'text') {
       textModel.value = (store.currentAnswer?.value as string) || '';
    }
    // Clear error when changing question
    store.lastError = null;
    // Scroll to top
    if (typeof window !== 'undefined') {
       window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  }, 
  { immediate: true }
);

// Watch for error to scroll to error/field
watch(
  () => store.lastError,
  (newVal) => {
    if (newVal) {
      if (typeof document !== 'undefined') {
        setTimeout(() => {
          const errorEl = document.querySelector('.q-banner');
          if (errorEl) {
            errorEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
          }
        }, 100);
      }
    }
  }
)

function handleTextInput(val: string | number | null) {
  store.updateAnswer(val as string);
}

// Multiple Choice
function isSelected(id: string) {
  const val = store.currentAnswer?.value;
  if (Array.isArray(val)) {
    return val.includes(id);
  }
  return false;
}

function toggleSelection(id: string) {
  const val = store.currentAnswer?.value;
  let currentArr: string[] = [];
  if (Array.isArray(val)) {
    currentArr = [...val];
  }
  
  const idx = currentArr.indexOf(id);
  if (idx >= 0) {
    currentArr.splice(idx, 1);
  } else {
    currentArr.push(id);
  }
  store.updateAnswer(currentArr);
}

// -- Helpers for Styling --

function getIndicatorClass(index: number, qId: number) {
  // 1. Current = Blue
  if (index === store.currentQuestionIndex) {
    return 'bg-blue-500 text-white border-blue-600';
  }

  const status = store.answers[qId]?.status || 'not_started';

  switch (status) {
    case 'completed':
      return 'bg-green-500 text-white border-green-600';
    case 'skipped':
      return 'bg-orange-500 text-white border-orange-600';
    case 'in_progress':
      // If it's in_progress but NOT current (should be rare/impossible with strict logic, but handled)
      return 'bg-blue-200 text-blue-800 border-blue-300'; 
    case 'not_started':
    default:
      return 'bg-gray-200 text-gray-400 border-gray-300 hover:bg-gray-300';
  }
}

</script>

<style scoped>
/* Optional: Transitions */
</style>
