<template>
  <div class="p-6 md:p-10 max-w-4xl mx-auto flex flex-col min-h-screen text-base-content">
    <!-- Header -->
    <div class="flex items-center gap-4 mb-8 shrink-0">
      <button @click="router.back()" class="btn btn-ghost btn-circle shrink-0">
        <ArrowLeftIcon :size="24" />
      </button>
      <div>
        <h1 class="text-2xl md:text-3xl font-black tracking-tight flex items-center gap-2">
          책갈피
        </h1>
        <p class="text-xs sm:text-sm opacity-50 font-medium">담아놓은 문제를 모아 풀 수 있습니다.</p>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="flex-1 flex flex-col items-center justify-center py-20 gap-4">
      <span class="loading loading-spinner loading-lg text-primary"></span>
      <p class="text-slate-400 text-sm">로딩 중...</p>
    </div>

    <!-- Empty State -->
    <div v-else-if="categories.length === 0" class="flex-1 flex flex-col items-center justify-center py-20">
      <div class="card bg-base-200 border border-base-300 shadow-xl max-w-md w-full p-8 text-center items-center gap-4">
        <div class="bg-base-300 p-4 rounded-full text-slate-500">
          <BookmarkXIcon :size="48" />
        </div>
        <h2 class="text-xl font-bold">책갈피한 문제가 없습니다</h2>
        <p class="text-xs sm:text-sm text-slate-400">퀴즈를 풀면서 책갈피 단추를 누르면 이곳에 모여 보여집니다.</p>
        <button @click="router.push('/categories')" class="btn btn-primary btn-sm sm:btn-md mt-2 gap-2">
          <BookOpenIcon :size="18" />
          문제 풀러 가기
        </button>
      </div>
    </div>

    <div v-else class="grid grid-cols-1 md:grid-cols-2 gap-8 items-start">
      <!-- Step 1: Select Category -->
      <div class="card bg-base-200 border border-base-300 shadow-xl overflow-hidden">
        <div class="card-body p-6">
          <h2 class="card-title text-lg font-black flex items-center gap-2 text-primary mb-4">
            <span class="badge badge-primary badge-sm">1</span>
            카테고리 선택
          </h2>
          <div class="space-y-3">
            <button
              v-for="cat in categories"
              :key="cat.name"
              @click="selectCategory(cat.name)"
              class="w-full btn btn-outline justify-between text-left h-auto py-2.5 sm:py-3 rounded-xl border-base-content/10 hover:border-primary transition-all duration-200 text-xs sm:text-sm"
              :class="selectedCategory === cat.name ? 'border-primary bg-primary/10 text-primary font-bold shadow-md' : 'text-base-content font-medium'"
            >
              <span class="truncate pr-2">{{ cat.name }}</span>
              <span class="badge badge-xs sm:badge-sm" :class="selectedCategory === cat.name ? 'badge-primary' : 'badge-ghost opacity-60'">
                {{ cat.count }}개
              </span>
            </button>
          </div>
        </div>
      </div>

      <!-- Step 2: Select Difficulty / Target -->
      <div class="card bg-base-200 border border-base-300 shadow-xl overflow-hidden transition-all duration-300">
        <div class="card-body p-6">
          <h2 class="card-title text-lg font-black flex items-center gap-2 text-primary mb-4">
            <span class="badge badge-primary badge-sm">2</span>
            난이도 선택
          </h2>

          <div v-if="!selectedCategory" class="flex flex-col items-center justify-center py-12 text-slate-500">
            <HelpCircleIcon :size="36" class="opacity-40 mb-2" />
            <p class="text-xs sm:text-sm font-medium">카테고리를 먼저 선택해 주세요.</p>
          </div>

          <div v-else-if="targetsLoading" class="flex flex-col items-center justify-center py-12 gap-3">
            <span class="loading loading-dots loading-md text-primary"></span>
          </div>

          <div v-else-if="targets.length === 0" class="flex flex-col items-center justify-center py-12 text-slate-500">
            <BookmarkXIcon :size="36" class="opacity-40 mb-2" />
            <p class="text-xs sm:text-sm font-medium">선택된 카테고리에 난이도가 존재하지 않습니다.</p>
          </div>

          <div v-else class="space-y-3">
            <button
              v-for="t in targets"
              :key="t.name"
              @click="selectTarget(t.name)"
              class="w-full btn btn-outline justify-between text-left h-auto py-2.5 sm:py-3 rounded-xl border-base-content/10 hover:border-primary transition-all duration-200 text-xs sm:text-sm"
              :class="selectedTarget === t.name ? 'border-primary bg-primary/10 text-primary font-bold shadow-md' : 'text-base-content font-medium'"
            >
              <span>{{ t.name }}</span>
              <span class="badge badge-xs sm:badge-sm" :class="selectedTarget === t.name ? 'badge-primary' : 'badge-ghost opacity-60'">
                {{ t.count }}개
              </span>
            </button>

            <!-- Start Button -->
            <button
              v-if="selectedTarget"
              @click="startBookmarkedQuiz"
              class="w-full btn btn-primary mt-6 py-4 h-auto rounded-xl gap-2 font-bold shadow-lg shadow-primary/20 hover:scale-[1.02] active:scale-[0.98] transition-all"
            >
              <PlayIcon :size="20" />
              즐겨찾기 퀴즈 풀기 시작
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowLeftIcon, BookmarkIcon, BookOpenIcon, HelpCircleIcon, PlayIcon } from 'lucide-vue-next'
// Custom Bookmark icons because lucide-vue-next might have variations
import { BookmarkXIcon } from 'lucide-vue-next'
import { QuizService, CategoryInfo, TargetInfo } from '../../bindings/changeme'

const router = useRouter()

const loading = ref(true)
const targetsLoading = ref(false)
const categories = ref<CategoryInfo[]>([])
const targets = ref<TargetInfo[]>([])

const selectedCategory = ref('')
const selectedTarget = ref('')

onMounted(async () => {
  try {
    const fetched = await QuizService.GetBookmarkedCategories()
    categories.value = fetched || []
  } catch (e) {
    console.error("Failed to load bookmarked categories:", e)
  } finally {
    loading.value = false
  }
})

async function selectCategory(catName: string) {
  selectedCategory.value = catName
  selectedTarget.value = ''
  targets.value = []
  targetsLoading.value = true
  try {
    const fetched = await QuizService.GetBookmarkedTargets(catName)
    targets.value = fetched || []
  } catch (e) {
    console.error("Failed to load bookmarked targets:", e)
  } finally {
    targetsLoading.value = false
  }
}

function selectTarget(targetName: string) {
  selectedTarget.value = targetName
}

function startBookmarkedQuiz() {
  if (!selectedCategory.value || !selectedTarget.value) return
  // Move to bookmarked quiz path
  router.push(`/bookmarks/quiz/${encodeURIComponent(selectedCategory.value)}/${encodeURIComponent(selectedTarget.value)}`)
}
</script>

<style scoped>
.btn {
  text-transform: none;
}
</style>
