<script setup lang="ts">
/**
 * Starter deck selection page.
 *
 * New users must select a starter deck before accessing the main app.
 * Displays 5 themed starter deck options (grass, fire, water, psychic, lightning)
 * with visual previews and descriptions.
 *
 * Selection triggers an API call to assign the deck, with a mock fallback
 * in development mode if the backend isn't ready.
 */
import { ref } from 'vue'

import { useStarter, type StarterType, type StarterDeck } from '@/composables/useStarter'

const { isLoading, error, selectedType, starterDecks, selectStarter, clearError } = useStarter()

// Confirmation state
const pendingSelection = ref<StarterType | null>(null)
const showConfirmation = ref(false)

/**
 * Type-specific colors for card borders and accents.
 */
const typeColors: Record<StarterType, { border: string; bg: string; text: string }> = {
  grass: {
    border: 'border-green-500',
    bg: 'bg-green-500',
    text: 'text-green-500',
  },
  fire: {
    border: 'border-orange-500',
    bg: 'bg-orange-500',
    text: 'text-orange-500',
  },
  water: {
    border: 'border-blue-500',
    bg: 'bg-blue-500',
    text: 'text-blue-500',
  },
  psychic: {
    border: 'border-pink-500',
    bg: 'bg-pink-500',
    text: 'text-pink-500',
  },
  lightning: {
    border: 'border-yellow-500',
    bg: 'bg-yellow-500',
    text: 'text-yellow-500',
  },
}

/**
 * Type-specific icons (using emoji for now, can replace with custom icons).
 */
const typeIcons: Record<StarterType, string> = {
  grass: '\u{1F33F}', // Herb
  fire: '\u{1F525}',  // Fire
  water: '\u{1F4A7}', // Droplet
  psychic: '\u{1F52E}', // Crystal ball
  lightning: '\u{26A1}', // Lightning
}

/**
 * Handle deck card click - show confirmation dialog.
 */
function handleDeckClick(deck: StarterDeck): void {
  if (isLoading.value) return
  pendingSelection.value = deck.type
  showConfirmation.value = true
  clearError()
}

/**
 * Confirm selection and call API.
 */
async function confirmSelection(): Promise<void> {
  if (!pendingSelection.value) return
  showConfirmation.value = false
  await selectStarter(pendingSelection.value)
}

/**
 * Cancel selection confirmation.
 */
function cancelSelection(): void {
  showConfirmation.value = false
  pendingSelection.value = null
}

/**
 * Get the pending deck for confirmation display.
 */
function getPendingDeck(): StarterDeck | undefined {
  return starterDecks.find(d => d.type === pendingSelection.value)
}
</script>

<template>
  <div class="flex min-h-screen items-center justify-center bg-gray-900 p-4">
    <div class="w-full max-w-4xl">
      <!-- Header -->
      <div class="mb-8 text-center">
        <h1 class="mb-2 text-3xl font-bold text-white">
          Choose Your Starter Deck
        </h1>
        <p class="text-gray-400">
          Select a starter deck to begin your journey. You'll earn more cards
          and build custom decks as you progress.
        </p>
      </div>

      <!-- Error message -->
      <div
        v-if="error"
        class="mb-6 rounded-lg bg-red-900/50 p-4 text-center text-red-200"
        role="alert"
      >
        <p>{{ error }}</p>
        <button
          class="mt-2 text-sm text-red-300 underline hover:text-red-100"
          @click="clearError"
        >
          Dismiss
        </button>
      </div>

      <!-- Deck grid -->
      <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-5">
        <button
          v-for="deck in starterDecks"
          :key="deck.type"
          class="group relative flex flex-col items-center rounded-xl border-2 bg-gray-800 p-6 transition-all duration-200 hover:scale-105 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-900 disabled:cursor-not-allowed disabled:opacity-50"
          :class="[
            typeColors[deck.type].border,
            isLoading && selectedType === deck.type
              ? 'ring-2 ring-white'
              : 'hover:shadow-lg hover:shadow-current/20',
          ]"
          :disabled="isLoading"
          @click="handleDeckClick(deck)"
        >
          <!-- Loading spinner overlay -->
          <div
            v-if="isLoading && selectedType === deck.type"
            class="absolute inset-0 flex items-center justify-center rounded-xl bg-gray-900/70"
          >
            <div class="h-8 w-8 animate-spin rounded-full border-4 border-white border-t-transparent" />
          </div>

          <!-- Type icon -->
          <div
            class="mb-3 flex h-16 w-16 items-center justify-center rounded-full text-4xl"
            :class="typeColors[deck.type].bg"
          >
            {{ typeIcons[deck.type] }}
          </div>

          <!-- Deck name -->
          <h2 class="mb-1 text-lg font-semibold text-white">
            {{ deck.name }}
          </h2>

          <!-- Type badge -->
          <span
            class="mb-2 rounded-full px-2 py-0.5 text-xs font-medium capitalize"
            :class="[typeColors[deck.type].bg, 'text-white']"
          >
            {{ deck.type }}
          </span>

          <!-- Description -->
          <p class="text-center text-sm text-gray-400">
            {{ deck.description }}
          </p>

          <!-- Card count -->
          <p class="mt-2 text-xs text-gray-500">
            {{ deck.cardCount }} cards
          </p>
        </button>
      </div>

      <!-- Help text -->
      <p class="mt-8 text-center text-sm text-gray-500">
        This choice is permanent for your account, but you'll be able to build
        many more decks with cards you earn!
      </p>
    </div>

    <!-- Confirmation Modal -->
    <Teleport to="body">
      <div
        v-if="showConfirmation"
        class="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
        @click.self="cancelSelection"
      >
        <div
          class="w-full max-w-md rounded-xl border-2 bg-gray-800 p-6 shadow-2xl"
          :class="pendingSelection ? typeColors[pendingSelection].border : ''"
          role="dialog"
          aria-modal="true"
          aria-labelledby="confirm-title"
        >
          <h2
            id="confirm-title"
            class="mb-4 text-xl font-bold text-white"
          >
            Confirm Selection
          </h2>

          <div
            v-if="getPendingDeck()"
            class="mb-6"
          >
            <div class="flex items-center gap-4">
              <div
                class="flex h-12 w-12 items-center justify-center rounded-full text-2xl"
                :class="pendingSelection ? typeColors[pendingSelection].bg : ''"
              >
                {{ pendingSelection ? typeIcons[pendingSelection] : '' }}
              </div>
              <div>
                <p class="font-semibold text-white">
                  {{ getPendingDeck()?.name }}
                </p>
                <p class="text-sm text-gray-400">
                  {{ getPendingDeck()?.description }}
                </p>
              </div>
            </div>
          </div>

          <p class="mb-6 text-gray-300">
            Are you sure you want to choose the
            <strong
              class="capitalize"
              :class="pendingSelection ? typeColors[pendingSelection].text : ''"
            >{{ pendingSelection }}</strong>
            starter deck? This choice cannot be changed.
          </p>

          <div class="flex gap-3">
            <button
              class="flex-1 rounded-lg bg-gray-700 px-4 py-2 font-medium text-white transition hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-500"
              @click="cancelSelection"
            >
              Cancel
            </button>
            <button
              class="flex-1 rounded-lg px-4 py-2 font-medium text-white transition focus:outline-none focus:ring-2"
              :class="[
                pendingSelection ? typeColors[pendingSelection].bg : 'bg-blue-500',
                'hover:opacity-90',
              ]"
              @click="confirmSelection"
            >
              Confirm
            </button>
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>
