<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { api, ApiError } from '@/api/client'
import type { Paginated, ProjectListRow } from '@/types/api'
import ProjectCard from '@/components/ProjectCard.vue'
import LoadingState from '@/components/LoadingState.vue'
import ErrorState from '@/components/ErrorState.vue'

const projects = ref<ProjectListRow[]>([])
const total = ref(0)
const loading = ref(true)
const error = ref<string | null>(null)

async function load() {
  loading.value = true
  error.value = null
  try {
    const r = await api.get<Paginated<ProjectListRow>>('/api/projects', {
      query: { status: 'archived', per_page: 50 },
    })
    projects.value = r.data
    total.value = r.meta.total
  } catch (e) {
    error.value = e instanceof ApiError ? (e.payload.message ?? e.code) : 'Erreur réseau'
  } finally {
    loading.value = false
  }
}
onMounted(load)
</script>

<template>
  <section class="px-10 py-8 max-w-7xl">
    <header>
      <h1 class="text-3xl font-semibold text-donut-text">Archives</h1>
      <p class="text-donut-muted mt-1">Les projets archivés de la communauté — mémoire du Donut.</p>
    </header>

    <div class="mt-8">
      <LoadingState v-if="loading" />
      <ErrorState v-else-if="error" :message="error" :retry="load" />
      <div v-else-if="projects.length === 0" class="text-donut-muted text-center py-16">
        Aucun projet archivé pour le moment.
      </div>
      <div v-else>
        <div class="text-xs text-donut-muted mb-4">
          {{ total }} projet{{ total > 1 ? 's' : '' }} archivé{{ total > 1 ? 's' : '' }}
        </div>
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
          <ProjectCard v-for="p in projects" :key="p.id" :project="p" />
        </div>
      </div>
    </div>
  </section>
</template>
