<script setup lang="ts">
/**
 * Dashboard / Page d'accueil — Glibredecision.
 *
 * Accueil sobre et lisible : cartes d'entree, banniere connexion,
 * apercu boite a outils et activite recente.
 */
const documents = useDocumentsStore()
const decisions = useDecisionsStore()
const protocols = useProtocolsStore()
const auth = useAuthStore()

const loading = ref(true)
const formulaOpen = ref(false)

onMounted(async () => {
  try {
    await Promise.all([
      documents.fetchAll(),
      decisions.fetchAll(),
      protocols.fetchProtocols(),
    ])
  }
  finally {
    loading.value = false
  }
})

/** Entry cards — the 4 main doors. */
const entryCards = computed(() => [
  {
    key: 'documents',
    title: 'Documents',
    icon: 'i-lucide-book-open',
    to: '/documents',
    count: documents.activeDocuments.length,
    countLabel: `${documents.activeDocuments.length} actif${documents.activeDocuments.length > 1 ? 's' : ''}`,
    totalLabel: `${documents.list.length} au total`,
    description: 'Textes fondateurs sous vote permanent',
    color: 'var(--mood-accent)',
  },
  {
    key: 'decisions',
    title: 'Decisions',
    icon: 'i-lucide-scale',
    to: '/decisions',
    count: decisions.activeDecisions.length,
    countLabel: `${decisions.activeDecisions.length} en cours`,
    totalLabel: `${decisions.list.length} au total`,
    description: 'Processus de decision collectifs',
    color: 'var(--mood-secondary, var(--mood-accent))',
  },
  {
    key: 'protocoles',
    title: 'Protocoles',
    icon: 'i-lucide-settings',
    to: '/protocols',
    count: protocols.protocols.length,
    countLabel: `${protocols.protocols.length} modalite${protocols.protocols.length > 1 ? 's' : ''}`,
    totalLabel: 'Boite a outils de vote + workflows',
    description: 'Modalites de vote, formules, workflows n8n',
    color: 'var(--mood-tertiary, var(--mood-accent))',
  },
  {
    key: 'mandats',
    title: 'Mandats',
    icon: 'i-lucide-user-check',
    to: '/mandates',
    count: null,
    countLabel: null,
    totalLabel: null,
    description: 'Un contexte, un objectif, une duree, une ou plusieurs nominations ; par defaut : nomination d\'un binome.',
    color: 'var(--mood-success)',
  },
])

/** Last 5 decisions sorted by most recent. */
const recentDecisions = computed(() => {
  return [...decisions.list]
    .sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime())
    .slice(0, 5)
})

function formatDate(dateStr: string): string {
  const date = new Date(dateStr)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffHours = diffMs / (1000 * 60 * 60)

  if (diffHours < 1) {
    const diffMinutes = Math.floor(diffMs / (1000 * 60))
    return diffMinutes <= 1 ? 'A l\'instant' : `Il y a ${diffMinutes} min`
  }
  if (diffHours < 24) {
    return `Il y a ${Math.floor(diffHours)}h`
  }
  if (diffHours < 48) {
    return 'Hier'
  }
  return date.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' })
}
</script>

<template>
  <div class="dash">
    <!-- Welcome -->
    <div class="dash__welcome">
      <h1 class="dash__title"><span class="dash__title-g">ğ</span><span class="dash__title-paren">(</span>Decision<span class="dash__title-paren">)</span></h1>
      <p class="dash__subtitle">
        Decisions collectives pour la communaute Duniter / G1
      </p>
    </div>

    <!-- Entry cards -->
    <div class="dash__entries">
      <template v-if="loading">
        <LoadingSkeleton v-for="i in 4" :key="i" :lines="3" card />
      </template>
      <template v-else>
        <NuxtLink
          v-for="card in entryCards"
          :key="card.key"
          :to="card.to"
          class="entry-card"
          :style="{ '--card-color': card.color }"
        >
          <div class="entry-card__icon">
            <UIcon :name="card.icon" class="text-xl" />
          </div>
          <h2 class="entry-card__title">{{ card.title }}</h2>
          <template v-if="card.count !== null">
            <span class="entry-card__count">{{ card.countLabel }}</span>
            <span class="entry-card__total">{{ card.totalLabel }}</span>
          </template>
          <template v-else>
            <span class="entry-card__desc">{{ card.description }}</span>
          </template>
          <span class="entry-card__arrow">
            <UIcon name="i-lucide-arrow-right" class="text-sm" />
          </span>
        </NuxtLink>
      </template>
    </div>

    <!-- Connect banner -->
    <div v-if="!auth.isAuthenticated" class="dash__connect">
      <div class="dash__connect-left">
        <UIcon name="i-lucide-key-round" class="text-base" />
        <div>
          <p class="dash__connect-text">Connectez-vous avec votre identite Duniter pour participer.</p>
          <p class="dash__connect-hint">Signature Ed25519 · aucun mot de passe</p>
        </div>
      </div>
      <NuxtLink to="/login" class="dash__connect-btn">
        <UIcon name="i-lucide-log-in" class="text-sm" />
        <span>Connexion</span>
      </NuxtLink>
    </div>

    <!-- Boite a outils teaser -->
    <div class="dash__toolbox">
      <div class="dash__toolbox-head">
        <UIcon name="i-lucide-wrench" class="text-base" />
        <h3>Boite a outils</h3>
        <span class="dash__toolbox-count">{{ protocols.protocols.length }}</span>
      </div>
      <p class="dash__toolbox-desc">
        Protocoles de vote avec formule de seuil WoT adaptative.
      </p>
      <div class="dash__toolbox-tags">
        <template v-if="protocols.protocols.length > 0">
          <NuxtLink
            v-for="protocol in protocols.protocols"
            :key="protocol.id"
            :to="`/protocols/${protocol.id}`"
            class="dash__tag"
          >
            {{ protocol.name }}
          </NuxtLink>
        </template>
        <template v-else>
          <span class="dash__tag">Vote majoritaire</span>
          <span class="dash__tag">Vote nuance</span>
          <span class="dash__tag">Vote permanent</span>
        </template>
      </div>
      <NuxtLink to="/protocols" class="dash__toolbox-link">
        Voir la boite a outils
        <UIcon name="i-lucide-chevron-right" class="text-xs" />
      </NuxtLink>
    </div>

    <!-- Recent activity -->
    <div v-if="recentDecisions.length > 0" class="dash__activity">
      <div class="dash__activity-head">
        <UIcon name="i-lucide-activity" class="text-base" />
        <h3>Activite recente</h3>
      </div>
      <div class="dash__activity-list">
        <NuxtLink
          v-for="decision in recentDecisions"
          :key="decision.id"
          :to="`/decisions/${decision.id}`"
          class="dash__activity-item"
        >
          <div class="dash__activity-main">
            <span class="dash__activity-title">{{ decision.title }}</span>
            <span class="dash__activity-date">{{ formatDate(decision.updated_at) }}</span>
          </div>
          <StatusBadge :status="decision.status" type="decision" :clickable="false" />
        </NuxtLink>
      </div>
    </div>

    <!-- Formula explainer -->
    <UCollapsible v-model:open="formulaOpen">
      <button class="dash__formula-trigger" @click="formulaOpen = !formulaOpen">
        <div class="dash__formula-trigger-left">
          <UIcon name="i-lucide-calculator" class="text-sm" />
          <span>Formule de seuil WoT</span>
        </div>
        <UIcon
          :name="formulaOpen ? 'i-lucide-chevron-up' : 'i-lucide-chevron-down'"
          class="text-xs"
        />
      </button>
      <template #content>
        <div class="dash__formula-body">
          <p class="dash__formula-desc">
            Le seuil s'adapte a la participation : faible = quasi-unanimite ; forte = majorite simple.
          </p>
          <code class="dash__formula-code">
            Seuil = C + B^W + (M + (1-M) * (1 - (T/W)^G)) * max(0, T-C)
          </code>
          <div class="dash__formula-params">
            <span>C = constante</span>
            <span>B = base</span>
            <span>W = taille WoT</span>
            <span>T = votes</span>
            <span>M = majorite</span>
            <span>G = gradient</span>
          </div>
          <NuxtLink to="/protocols/formulas" class="dash__formula-link">
            Ouvrir le simulateur
            <UIcon name="i-lucide-chevron-right" class="text-xs" />
          </NuxtLink>
        </div>
      </template>
    </UCollapsible>
  </div>
</template>

<style scoped>
.dash {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  max-width: 52rem;
}

/* --- Welcome --- */
.dash__welcome {
  padding: 0.5rem 0;
}
.dash__title {
  font-size: 1.625rem;
  font-weight: 800;
  color: var(--mood-accent);
  letter-spacing: -0.02em;
}
.dash__title-g {
  font-style: italic;
}
.dash__title-paren {
  font-weight: 300;
  color: var(--mood-text-muted);
}
.dash__subtitle {
  margin-top: 0.25rem;
  font-size: 0.875rem;
  color: var(--mood-text-muted);
}

/* --- Entry cards --- */
.dash__entries {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr));
  gap: 0.75rem;
}

.entry-card {
  position: relative;
  display: flex;
  flex-direction: column;
  gap: 0.375rem;
  padding: 1.25rem 1rem;
  background: var(--mood-surface);
  border: 1px solid var(--mood-border);
  border-radius: 6px;
  text-decoration: none;
  cursor: pointer;
  transition: border-color 0.15s ease, box-shadow 0.15s ease;
}
.entry-card:hover {
  border-color: var(--card-color, var(--mood-accent));
  box-shadow: 0 2px 8px var(--mood-shadow);
}

.entry-card__icon {
  width: 2.25rem;
  height: 2.25rem;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  background: color-mix(in srgb, var(--card-color, var(--mood-accent)) 10%, transparent);
  color: var(--card-color, var(--mood-accent));
  margin-bottom: 0.25rem;
}

.entry-card__title {
  font-size: 1rem;
  font-weight: 700;
  color: var(--mood-text);
  margin: 0;
}

.entry-card__count {
  font-size: 1.25rem;
  font-weight: 800;
  color: var(--card-color, var(--mood-accent));
  line-height: 1;
}

.entry-card__total {
  font-size: 0.6875rem;
  color: var(--mood-text-muted);
}

.entry-card__desc {
  font-size: 0.75rem;
  color: var(--mood-text-muted);
  line-height: 1.4;
}

.entry-card__arrow {
  position: absolute;
  top: 1rem;
  right: 1rem;
  color: var(--mood-text-muted);
  opacity: 0.4;
  transition: opacity 0.15s;
}
.entry-card:hover .entry-card__arrow {
  opacity: 1;
  color: var(--card-color, var(--mood-accent));
}

/* --- Connect banner --- */
.dash__connect {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 0.75rem;
  padding: 0.875rem 1rem;
  background: var(--mood-accent-soft);
  border: 1px solid var(--mood-border);
  border-radius: 6px;
}

.dash__connect-left {
  display: flex;
  align-items: flex-start;
  gap: 0.625rem;
  color: var(--mood-accent);
}

.dash__connect-text {
  font-size: 0.8125rem;
  font-weight: 500;
  color: var(--mood-text);
}

.dash__connect-hint {
  font-size: 0.6875rem;
  color: var(--mood-text-muted);
}

.dash__connect-btn {
  display: inline-flex;
  align-items: center;
  gap: 0.375rem;
  padding: 0.375rem 0.875rem;
  font-size: 0.75rem;
  font-weight: 600;
  color: var(--mood-accent-text);
  background: var(--mood-accent);
  border-radius: 4px;
  text-decoration: none;
  transition: opacity 0.15s ease;
}
.dash__connect-btn:hover {
  opacity: 0.88;
}

/* --- Toolbox teaser --- */
.dash__toolbox {
  background: var(--mood-surface);
  border: 1px solid var(--mood-border);
  border-radius: 6px;
  padding: 1rem;
}

.dash__toolbox-head {
  display: flex;
  align-items: center;
  gap: 0.375rem;
  color: var(--mood-accent);
  font-weight: 700;
  font-size: 0.875rem;
}
.dash__toolbox-head h3 { margin: 0; }

.dash__toolbox-count {
  font-size: 0.625rem;
  font-weight: 700;
  background: var(--mood-accent-soft);
  color: var(--mood-accent);
  padding: 1px 5px;
  border-radius: 3px;
  margin-left: 0.25rem;
}

.dash__toolbox-desc {
  margin-top: 0.25rem;
  font-size: 0.75rem;
  color: var(--mood-text-muted);
}

.dash__toolbox-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.375rem;
  margin-top: 0.5rem;
}

.dash__tag {
  display: inline-flex;
  align-items: center;
  padding: 0.25rem 0.625rem;
  font-size: 0.6875rem;
  font-weight: 500;
  color: var(--mood-accent);
  background: var(--mood-accent-soft);
  border: 1px solid var(--mood-border);
  border-radius: 4px;
  text-decoration: none;
  transition: border-color 0.15s ease;
}
.dash__tag:hover {
  border-color: var(--mood-accent);
}

.dash__toolbox-link {
  display: inline-flex;
  align-items: center;
  gap: 0.25rem;
  margin-top: 0.5rem;
  font-size: 0.6875rem;
  font-weight: 600;
  color: var(--mood-accent);
  text-decoration: none;
}
.dash__toolbox-link:hover {
  text-decoration: underline;
}

/* --- Activity --- */
.dash__activity {
  background: var(--mood-surface);
  border: 1px solid var(--mood-border);
  border-radius: 6px;
  padding: 1rem;
}

.dash__activity-head {
  display: flex;
  align-items: center;
  gap: 0.375rem;
  color: var(--mood-text);
  font-weight: 700;
  font-size: 0.875rem;
  margin-bottom: 0.5rem;
}
.dash__activity-head h3 { margin: 0; }

.dash__activity-list {
  display: flex;
  flex-direction: column;
}

.dash__activity-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.5rem;
  padding: 0.5rem 0;
  border-bottom: 1px solid var(--mood-border);
  text-decoration: none;
  transition: background 0.1s;
}
.dash__activity-item:last-child { border-bottom: none; }
.dash__activity-item:hover {
  background: var(--mood-surface-hover);
  margin: 0 -0.5rem;
  padding-left: 0.5rem;
  padding-right: 0.5rem;
  border-radius: 4px;
}

.dash__activity-main {
  display: flex;
  flex-direction: column;
  min-width: 0;
  flex: 1;
}

.dash__activity-title {
  font-size: 0.8125rem;
  font-weight: 500;
  color: var(--mood-text);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.dash__activity-date {
  font-size: 0.625rem;
  color: var(--mood-text-muted);
}

/* --- Formula --- */
.dash__formula-trigger {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 0.75rem 1rem;
  background: var(--mood-surface);
  border: 1px solid var(--mood-border);
  border-radius: 6px;
  color: var(--mood-text-muted);
  font-size: 0.8125rem;
  font-weight: 500;
  cursor: pointer;
  transition: border-color 0.15s;
}
.dash__formula-trigger:hover {
  border-color: var(--mood-accent);
}

.dash__formula-trigger-left {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.dash__formula-body {
  padding: 0 1rem 1rem;
  background: var(--mood-surface);
  border: 1px solid var(--mood-border);
  border-top: none;
  border-radius: 0 0 6px 6px;
  display: flex;
  flex-direction: column;
  gap: 0.625rem;
}

.dash__formula-desc {
  font-size: 0.75rem;
  color: var(--mood-text-muted);
  line-height: 1.5;
}

.dash__formula-code {
  display: block;
  padding: 0.625rem;
  background: var(--mood-accent-soft);
  border-radius: 4px;
  font-size: 0.75rem;
  font-family: ui-monospace, SFMono-Regular, monospace;
  color: var(--mood-text);
  overflow-x: auto;
}

.dash__formula-params {
  display: flex;
  flex-wrap: wrap;
  gap: 0.625rem;
  font-size: 0.625rem;
  color: var(--mood-text-muted);
  font-family: ui-monospace, SFMono-Regular, monospace;
}

.dash__formula-link {
  display: inline-flex;
  align-items: center;
  gap: 0.25rem;
  font-size: 0.6875rem;
  font-weight: 600;
  color: var(--mood-accent);
  text-decoration: none;
}
.dash__formula-link:hover {
  text-decoration: underline;
}
</style>
