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

const stats = ref<Stats | null>(null)
const activity = ref<ActivityEvent[]>([])
const loading = ref(true)
const error = ref<string | null>(null)

async function load() {
  loading.value = true
  error.value = null
  try {
    const [s, a] = await Promise.all([
      api.get<Stats>('/api/stats'),
      api.get<Wrapped<ActivityEvent>>('/api/activity', { query: { limit: 12 } }),
    ])
    stats.value = s
    activity.value = a.data
  } catch (e) {
    error.value = e instanceof ApiError ? (e.payload.message ?? e.code) : 'Erreur réseau'
  } finally {
    loading.value = false
  }
}
onMounted(load)

// Verbes -> formulation lisible avec actor_label avant.
const VERB_LABEL: Record<string, string> = {
  joined:             'a rejoint',
  left:               'a quitté',
  created_project:    'a créé',
  updated_project:    'a mis à jour',
  completed_project:  'a terminé',
  added_step:         'a ajouté une étape à',
  completed_step:     'a terminé une étape de',
  posted_discussion:  'a publié dans',
  added_resource:     'a ajouté une ressource à',
}

const kpiBlocks = computed(() => {
  if (!stats.value) return []
  const total = stats.value.projects_total
  return [
    {
      label: 'Projets Actifs',
      value: stats.value.projects_active,
      sub: `Sur ${total} projet${total > 1 ? 's' : ''} au total`,
      iconPath: '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',
      iconColor: '#F97316',
    },
    {
      label: 'Participants',
      value: stats.value.participants_total,
      sub: 'Citoyens engagés',
      iconPath: 'M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2 M9 7a4 4 0 1 0 0 8 4 4 0 0 0 0-8 M23 21v-2a4 4 0 0 0-3-3.87 M16 3.13a4 4 0 0 1 0 7.75',
      iconColor: '#EF4444',
    },
    {
      label: 'Projets Réalisés',
      value: stats.value.projects_completed,
      sub: 'Impacts concrets',
      iconPath: 'M9 11l3 3L22 4 M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11',
      iconColor: '#22C55E',
    },
    {
      label: 'Projets Historiques',
      value: stats.value.projects_archived,
      sub: 'Mémoire du Donut',
      iconPath: 'M12 8v4l3 3 M21 12a9 9 0 1 1-9-9',
      iconColor: '#6B7280',
    },
  ]
})
</script>

<template>
  <section class="px-10 py-8 max-w-7xl">
    <header>
      <h1 class="text-3xl font-semibold text-donut-text">Tableau de bord</h1>
      <p class="text-donut-muted mt-1">Vue d'ensemble de l'activité citoyenne et de l'intelligence collective.</p>
    </header>

    <LoadingState v-if="loading" class="mt-8" />
    <ErrorState v-else-if="error" :message="error" :retry="load" class="mt-8" />

    <div v-else class="mt-8 space-y-6">
      <!-- KPI -->
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <div
          v-for="k in kpiBlocks"
          :key="k.label"
          class="rounded-xl border border-donut-border bg-donut-surface p-5"
        >
          <div class="flex items-start justify-between">
            <div class="text-sm text-donut-muted">{{ k.label }}</div>
            <div
              class="w-8 h-8 rounded-md flex items-center justify-center"
              :style="{ background: k.iconColor + '1A', color: k.iconColor }"
            >
              <svg viewBox="0 0 24 24" class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path :d="k.iconPath"/>
              </svg>
            </div>
          </div>
          <div class="mt-2 text-3xl font-semibold text-donut-text">{{ k.value }}</div>
          <div class="text-xs text-donut-muted mt-1">{{ k.sub }}</div>
        </div>
      </div>

      <!-- 2 colonnes : Vision Donut (résumé) + Activité Récente -->
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <!-- Vision Donut résumé -->
        <div class="lg:col-span-2 rounded-xl border border-donut-border bg-donut-surface p-6">
          <div class="flex items-start justify-between gap-4">
            <div>
              <h2 class="text-lg font-semibold text-donut-text">Vision Donut</h2>
              <p class="text-sm text-donut-muted">Plancher social et plafond écologique : nos projets dans l'espace sûr.</p>
            </div>
          </div>

          <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6 items-center">
            <!-- mini donut -->
            <div class="flex items-center justify-center">
              <svg viewBox="-100 -100 200 200" class="w-44 h-44">
                <circle r="80" fill="#22C55E1A" stroke="#22C55E" stroke-width="0.5" />
                <circle r="55" fill="#FAFAF6" />
                <circle r="40" fill="#F9731622" stroke="#F97316" stroke-width="0.5" />
                <circle r="20" fill="#FAFAF6" />
                <text text-anchor="middle" font-size="9" fill="#111827" font-weight="600">LE DONUT</text>
                <text y="11" text-anchor="middle" font-size="6" fill="#6B7280">
                  {{ stats?.projects_total ?? 0 }} projets
                </text>
              </svg>
            </div>
            <!-- légende dimensions -->
            <div class="space-y-3">
              <div>
                <div class="text-xs uppercase tracking-wider text-status-active font-semibold">Plancher social</div>
                <div class="text-sm text-donut-text mt-1">
                  {{ stats?.by_dimension.social ?? 0 }} projets sociaux
                </div>
              </div>
              <div>
                <div class="text-xs uppercase tracking-wider text-status-completed font-semibold" style="color:#22C55E">Plafond écologique</div>
                <div class="text-sm text-donut-text mt-1">
                  {{ stats?.by_dimension.ecologique ?? 0 }} projets environnementaux
                </div>
              </div>
              <div>
                <div class="text-xs uppercase tracking-wider text-donut-muted font-semibold">Transversal</div>
                <div class="text-sm text-donut-text mt-1">
                  {{ stats?.by_dimension.transversal ?? 0 }} projets
                </div>
              </div>
            </div>
          </div>

          <div class="mt-6 text-right">
            <RouterLink
              :to="{ name: 'donut' }"
              class="text-sm text-status-active font-medium hover:underline inline-flex items-center gap-1"
            >
              Voir la vision Donut complète
              <span aria-hidden="true">→</span>
            </RouterLink>
          </div>
        </div>

        <!-- Activité Récente -->
        <div class="rounded-xl border border-donut-border bg-donut-surface p-6">
          <h2 class="text-lg font-semibold text-donut-text">Activité Récente</h2>
          <p class="text-sm text-donut-muted">Les dernières dynamiques de la communauté.</p>

          <ul v-if="activity.length" class="mt-4 space-y-3">
            <li v-for="a in activity" :key="a.id" class="flex items-start gap-3">
              <span class="mt-1.5 w-2 h-2 rounded-full bg-status-active shrink-0" aria-hidden="true" />
              <div class="flex-1 min-w-0 text-sm">
                <div class="text-donut-text">
                  <span class="font-medium">{{ a.actor_label }}</span>
                  {{ ' ' }}
                  <span class="text-donut-muted">{{ VERB_LABEL[a.verb] ?? a.verb }}</span>
                </div>
                <div class="text-donut-muted text-xs mt-0.5 truncate">{{ a.summary }}</div>
                <div class="text-donut-muted text-xs mt-0.5">{{ formatRelative(a.occurred_at) }}</div>
              </div>
            </li>
          </ul>
          <p v-else class="text-sm text-donut-muted mt-4">Aucune activité récente.</p>
        </div>
      </div>
    </div>
  </section>
</template>
