<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { RouterLink } from 'vue-router'
import { api, ApiError } from '@/api/client'
import type { Category, Stats, Wrapped } from '@/types/api'
import LoadingState from '@/components/LoadingState.vue'
import ErrorState from '@/components/ErrorState.vue'

const categories = ref<Category[]>([])
const counts = ref<Record<string, number>>({})
const loading = ref(true)
const error = ref<string | null>(null)

async function load() {
  loading.value = true
  error.value = null
  try {
    // 2 appels en parallèle : la liste des catégories + stats pour les counts par slug.
    const [cats, stats] = await Promise.all([
      api.get<Wrapped<Category>>('/api/categories'),
      api.get<Stats>('/api/stats'),
    ])
    categories.value = cats.data
    counts.value = Object.fromEntries(stats.by_category.map(c => [c.slug, c.count]))
  } catch (e) {
    error.value = e instanceof ApiError ? (e.payload.message ?? e.code) : 'Erreur réseau'
  } finally {
    loading.value = false
  }
}
onMounted(load)

const DIMENSION_LABEL = {
  social: 'Plancher social',
  ecologique: 'Plafond écologique',
  transversal: 'Transversal',
} as const
</script>

<template>
  <section class="px-10 py-8 max-w-6xl">
    <header>
      <h1 class="text-3xl font-semibold text-donut-text">Catégories Thématiques</h1>
      <p class="text-donut-muted mt-1">Explorez les initiatives par domaine d'impact.</p>
    </header>

    <div class="mt-8">
      <LoadingState v-if="loading" />
      <ErrorState v-else-if="error" :message="error" :retry="load" />
      <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
        <RouterLink
          v-for="cat in categories"
          :key="cat.id"
          :to="{ name: 'projects', query: { category: cat.slug } }"
          class="group block rounded-xl border border-donut-border bg-donut-surface overflow-hidden hover:shadow-md transition-shadow"
          :style="{ borderTopWidth: '4px', borderTopStyle: 'solid', borderTopColor: cat.color_hex }"
        >
          <div class="p-6">
            <div
              class="w-11 h-11 rounded-lg flex items-center justify-center mb-4"
              :style="{ background: cat.color_hex + '1A', color: cat.color_hex }"
            >
              <svg viewBox="0 0 24 24" class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
              </svg>
            </div>
            <h3 class="text-lg font-semibold text-donut-text group-hover:text-black">{{ cat.name }}</h3>
            <p v-if="cat.description" class="text-sm text-donut-muted mt-2 leading-relaxed">
              {{ cat.description }}
            </p>
            <div class="mt-5 flex items-center justify-between gap-2">
              <span class="inline-flex items-center rounded-full bg-orange-50 text-status-active px-2.5 py-1 text-xs font-medium">
                {{ counts[cat.slug] ?? 0 }} projet{{ (counts[cat.slug] ?? 0) === 1 ? '' : 's' }}
              </span>
              <span class="text-[10px] text-donut-muted uppercase tracking-wider">
                {{ DIMENSION_LABEL[cat.dimension] }}
              </span>
            </div>
          </div>
        </RouterLink>
      </div>
    </div>
  </section>
</template>
