<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { api, type CollectionSummary } from '@/api/client'
import { useAuthStore } from '@/stores/auth'
import AdminPanel from '@/components/AdminPanel.vue'

const router = useRouter()
const auth = useAuthStore()

const collections = ref<CollectionSummary[]>([])
const loading = ref(true)
const error = ref<string | null>(null)

async function load() {
  loading.value = true
  error.value = null
  try {
    collections.value = await api.listCollections()
  } catch (e) {
    error.value = (e as Error).message
  } finally {
    loading.value = false
  }
}

function play(id: number) {
  router.push({ name: 'game', params: { id } })
}

onMounted(load)
</script>

<template>
  <main class="mx-auto max-w-5xl px-6 py-12">
    <header class="mb-12 text-center">
      <h1 class="display text-6xl text-[var(--color-text)] md:text-8xl">
        <span class="text-[var(--color-primary)]">Smash</span> or
        <span class="text-[var(--color-red-500)]">Pass</span> ?
      </h1>
      <p class="mt-3 text-[var(--color-text-muted)]">
        Choisissez une collection et lancez la partie.
      </p>
    </header>

    <p v-if="error" class="mb-4 text-center text-[var(--color-red-500)]">{{ error }}</p>

    <section v-if="loading" class="text-center text-[var(--color-text-muted)]">Chargement…</section>

    <section v-else>
      <div v-if="collections.length === 0" class="text-center text-[var(--color-text-muted)]">
        Aucune collection disponible pour le moment.
      </div>

      <ul v-else class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <li
          v-for="c in collections"
          :key="c.id"
          class="group cursor-pointer rounded-[var(--radius-card)] border border-[var(--color-border)] bg-[var(--color-surface)] p-6 transition hover:border-[var(--color-primary)] hover:bg-[var(--color-surface-2)]"
          @click="play(c.id)"
        >
          <h2 class="mb-2 text-2xl text-[var(--color-text)]">{{ c.name }}</h2>
          <p class="text-sm text-[var(--color-text-muted)]">
            {{ c.character_count }} personnage{{ c.character_count > 1 ? 's' : '' }}
          </p>
          <p
            class="mt-4 inline-block rounded-md bg-[var(--color-primary)] px-3 py-1 text-sm font-semibold text-white opacity-0 transition group-hover:opacity-100"
          >
            Jouer →
          </p>
        </li>
      </ul>
    </section>

    <div v-if="auth.isAuthenticated" class="mt-16">
      <AdminPanel :collections="collections" @refresh="load" />
    </div>
  </main>
</template>
