<template>
  <div class="space-y-8">
    <div v-if="loading" class="flex justify-center py-16">
      <span class="loading loading-spinner loading-lg text-primary"></span>
    </div>

    <div v-else-if="error" class="text-center py-10 text-error">{{ error }}</div>

    <template v-else-if="stats">
      <!-- Resumen -->
      <section>
        <h3 class="text-xs font-bold text-tertiary uppercase tracking-wide flex items-center gap-2 mb-3">
          <span class="inline-block w-1 h-3.5 bg-colorSecondary"></span>Resumen
        </h3>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
          <div class="stat bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box p-4">
            <div class="stat-title text-tertiary/70 text-xs font-medium">Total voluntarios</div>
            <div class="stat-value text-tertiary font-primary">{{ fmt(stats.total) }}</div>
          </div>
          <div class="stat bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box p-4">
            <div class="stat-title text-tertiary/70 text-xs font-medium">Edad promedio</div>
            <div class="stat-value text-tertiary font-primary">{{ stats.edad.promedio ?? "—" }} años</div>
          </div>
          <div class="stat bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box p-4">
            <div class="stat-title text-tertiary/70 text-xs font-medium">Femenino</div>
            <div class="stat-value text-tertiary font-primary">{{ fmt(sexo.f) }}</div>
            <div class="stat-desc text-tertiary/60">{{ pct(sexo.f, sexo.total) }}% del total</div>
          </div>
          <div class="stat bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box p-4">
            <div class="stat-title text-tertiary/70 text-xs font-medium">Masculino</div>
            <div class="stat-value text-tertiary font-primary">{{ fmt(sexo.m) }}</div>
            <div class="stat-desc text-tertiary/60">{{ pct(sexo.m, sexo.total) }}% del total</div>
          </div>
        </div>
      </section>

      <!-- Idiomas -->
      <section>
        <h3 class="text-xs font-bold text-tertiary uppercase tracking-wide flex items-center gap-2 mb-3">
          <span class="inline-block w-1 h-3.5 bg-colorSecondary"></span>Idiomas
        </h3>
        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
          <div
            v-for="lang in stats.idiomas"
            :key="lang.value"
            class="stat bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box p-4"
          >
            <div class="stat-title text-tertiary/70 text-xs font-medium">{{ lang.label }}</div>
            <div class="stat-value text-tertiary font-primary text-2xl">{{ fmt(lang.count) }}</div>
            <div class="stat-desc text-tertiary/60">{{ pct(lang.count, stats.total) }}% del total</div>
          </div>
        </div>
      </section>

      <!-- Distribuciones -->
      <section>
        <h3 class="text-xs font-bold text-tertiary uppercase tracking-wide flex items-center gap-2 mb-3">
          <span class="inline-block w-1 h-3.5 bg-colorSecondary"></span>Distribuciones
        </h3>
        <div class="grid md:grid-cols-2 gap-4">
          <div class="card bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box">
            <div class="card-body p-4 sm:p-5">
              <h4 class="card-title text-tertiary text-sm font-bold">Áreas de colaboración</h4>
              <div class="space-y-2">
                <div v-for="item in topAreas" :key="item.value" class="flex items-center gap-3">
                  <span class="w-32 sm:w-44 shrink-0 text-sm text-tertiary truncate" :title="item.label">{{ item.label }}</span>
                  <progress class="progress progress-secondary flex-1" :value="item.count" :max="areasMax"></progress>
                  <span class="w-12 shrink-0 text-right text-sm font-semibold text-tertiary">{{ fmt(item.count) }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="card bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box">
            <div class="card-body p-4 sm:p-5">
              <h4 class="card-title text-tertiary text-sm font-bold">Días disponibles</h4>
              <div class="space-y-2">
                <div v-for="item in stats.dias" :key="item.value" class="flex items-center gap-3">
                  <span class="w-32 sm:w-44 shrink-0 text-sm text-tertiary truncate" :title="item.label">{{ item.label }}</span>
                  <progress class="progress progress-secondary flex-1" :value="item.count" :max="diasMax"></progress>
                  <span class="w-12 shrink-0 text-right text-sm font-semibold text-tertiary">{{ fmt(item.count) }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="card bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box">
            <div class="card-body p-4 sm:p-5">
              <h4 class="card-title text-tertiary text-sm font-bold">Horario preferido</h4>
              <div class="space-y-2">
                <div v-for="item in stats.horarios" :key="item.value" class="flex items-center gap-3">
                  <span class="w-32 sm:w-44 shrink-0 text-sm text-tertiary truncate" :title="item.label">{{ item.label }}</span>
                  <progress class="progress progress-secondary flex-1" :value="item.count" :max="horariosMax"></progress>
                  <span class="w-12 shrink-0 text-right text-sm font-semibold text-tertiary">{{ fmt(item.count) }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="card bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box">
            <div class="card-body p-4 sm:p-5">
              <h4 class="card-title text-tertiary text-sm font-bold">Países</h4>
              <div class="space-y-2">
                <div v-for="item in stats.paises" :key="item.value" class="flex items-center gap-3">
                  <span class="w-32 sm:w-44 shrink-0 text-sm text-tertiary truncate" :title="item.value">{{ item.value }}</span>
                  <progress class="progress progress-secondary flex-1" :value="item.count" :max="paisesMax"></progress>
                  <span class="w-12 shrink-0 text-right text-sm font-semibold text-tertiary">{{ fmt(item.count) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- Disponibilidad y salud -->
      <section>
        <h3 class="text-xs font-bold text-tertiary uppercase tracking-wide flex items-center gap-2 mb-3">
          <span class="inline-block w-1 h-3.5 bg-colorSecondary"></span>Disponibilidad y salud
        </h3>
        <div class="card bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box">
          <div class="card-body p-4 sm:p-6 grid md:grid-cols-2 gap-x-8 gap-y-5">
            <div v-for="m in condMetrics" :key="m.title" class="space-y-1.5">
              <div class="flex justify-between text-sm text-tertiary">
                <span class="font-medium">{{ m.title }}</span>
                <span>Sí {{ m.pct }}% · No {{ 100 - m.pct }}%</span>
              </div>
              <progress class="progress progress-secondary w-full" :value="m.si" :max="m.total"></progress>
              <p class="text-xs text-tertiary/60">
                Sí: {{ fmt(m.si) }} · No: {{ fmt(m.no) }}
              </p>
            </div>

            <div class="space-y-1.5">
              <div class="flex justify-between text-sm text-tertiary">
                <span class="font-medium">Sexo</span>
                <span>F {{ pct(sexo.f, sexo.total) }}% · M {{ pct(sexo.m, sexo.total) }}%</span>
              </div>
              <div class="flex w-full h-3 rounded-none overflow-hidden bg-tertiary/15">
                <div class="bg-tertiary h-full" :style="{ width: pct(sexo.f, sexo.total) + '%' }"></div>
                <div class="bg-colorSecondary h-full" :style="{ width: pct(sexo.m, sexo.total) + '%' }"></div>
              </div>
              <p class="text-xs text-tertiary/60">
                F: {{ fmt(sexo.f) }} · M: {{ fmt(sexo.m) }}
              </p>
            </div>
          </div>
        </div>
      </section>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { cachedFetch } from "../../lib/adminCache";

const loading = ref(false);
const error = ref("");
const stats = ref(null);

const fmt = (n) => Number(n || 0).toLocaleString("es");
const pct = (n, total) => (total ? Math.round(((n || 0) / total) * 100) : 0);

const sexo = computed(() => {
  const s = stats.value?.sexo || [];
  const f = s.find((x) => x.value === "F")?.count || 0;
  const m = s.find((x) => x.value === "M")?.count || 0;
  return { f, m, total: f + m };
});

const topAreas = computed(() => (stats.value?.areas || []).slice(0, 8));
const areasMax = computed(() => topAreas.value[0]?.count || 1);
const diasMax = computed(() => stats.value?.dias[0]?.count || 1);
const horariosMax = computed(() => stats.value?.horarios[0]?.count || 1);
const paisesMax = computed(() => stats.value?.paises[0]?.count || 1);

const condMetrics = computed(() => {
  const c = stats.value?.condiciones;
  if (!c) return [];
  const mk = (title, key) => {
    const si = c[key].si || 0;
    const no = c[key].no || 0;
    const total = si + no;
    return { title, si, no, total, pct: total ? Math.round((si / total) * 100) : 0 };
  };
  return [
    mk("Disponible fuera de ciudad", "fuera_ciudad"),
    mk("Misiones internacionales", "misiones_internacionales"),
    mk("Condición médica", "condicion_medica"),
    mk("Voluntariado anterior", "voluntariado_anterior"),
  ];
});

async function fetchStats() {
  loading.value = true;
  error.value = "";
  try {
    const res = await cachedFetch("/api/admin/voluntarios/stats", { ttl: 60 });
    const json = await res.json();
    if (!json.success) throw new Error(json.message || "Error al cargar estadísticas");
    stats.value = json;
  } catch (e) {
    error.value = e.message;
  } finally {
    loading.value = false;
  }
}

onMounted(fetchStats);
</script>
