<script setup lang="ts">
/**
 * /decisions — le registre v2. Pills d'état cliquables (mapping unique),
 * pills courtes de route, filtres (cercle/tag/me concerne/poids/gravées/
 * consignées), recherche locale. Zéro bouton de création : on crée par la
 * capture — l'état vide le rappelle.
 */
import type { Decision, DecisionRoute, Weight } from '~/types/domain'
import { ROUTE_SHORT, STATUS_LABELS, FROZEN_LABEL, CAPTURE_PLACEHOLDER } from '~/lexicon'
import { useCollectiveStore } from '~/stores/collective'
import { displayStatus, fold, type DisplayStatus } from '~/components/decisions/decisionUi'

const col = useCollectiveStore()

// ── Filtres ──
const query = ref('')
const statusFilter = ref<DisplayStatus | null>(null)
const routeFilter = ref<DecisionRoute | null>(null)
const filterCircle = ref<string | null>(null)
const filterTag = ref<string | null>(null)
const filterMine = ref(false)
const filterWeight = ref<Weight | null>(null)
const filterEngraved = ref(false)
const filterRecorded = ref(false)

const latestSession = (decisionId: string) =>
  col.sessions
    .filter(s => s.decisionId === decisionId)
    .sort((a, b) => (a.opensAt < b.opensAt ? 1 : -1))[0]

const shownStatus = (d: Decision): DisplayStatus => displayStatus(d, latestSession(d.id))

// ── Pills d'état — l'ordre du cycle, comptées, masquées à zéro ──
const STATUS_ORDER: DisplayStatus[] = [
  'draft', 'advice', 'objection', 'framing', 'voting', 'frozen',
  'adopted', 'closed', 'rejected', 'revoked', 'transmitted',
]
const statusPills = computed(() =>
  STATUS_ORDER
    .map(status => ({
      status,
      label: status === 'frozen' ? FROZEN_LABEL : STATUS_LABELS[status],
      count: col.decisions.filter(d => shownStatus(d) === status).length,
    }))
    .filter(pill => pill.count > 0),
)

const ROUTES: DecisionRoute[] = ['solo', 'mandate', 'transmit', 'advice', 'collective', 'record']
const routePills = computed(() =>
  ROUTES
    .map(route => ({ route, count: col.decisions.filter(d => d.route === route).length }))
    .filter(pill => pill.count > 0),
)

// ── Liste filtrée puis triée : en cours par échéance, terminées ensuite ──
const meId = computed(() => col.me?.id ?? null)
const ACTIVE: DisplayStatus[] = ['draft', 'advice', 'objection', 'framing', 'voting', 'frozen']

function concernsMe(d: Decision): boolean {
  if (!meId.value) return false
  if (d.authorId === meId.value) return true
  return col.concerns.some(c => c.decisionId === d.id && c.personId === meId.value)
}

function deadlineOf(d: Decision): string {
  return d.windowEndsAt ?? latestSession(d.id)?.closesAt ?? d.createdAt
}

const filtered = computed(() => {
  const needle = fold(query.value.trim())
  return col.decisions.filter((d) => {
    if (statusFilter.value && shownStatus(d) !== statusFilter.value) return false
    if (routeFilter.value && d.route !== routeFilter.value) return false
    if (filterCircle.value && !d.scope.circleIds.includes(filterCircle.value)) return false
    if (filterTag.value && !d.tags.includes(filterTag.value)) return false
    if (filterMine.value && !concernsMe(d)) return false
    if (filterWeight.value && d.weight !== filterWeight.value) return false
    if (filterEngraved.value && !d.engraving) return false
    if (filterRecorded.value && d.route !== 'record') return false
    if (needle.length > 0 && !fold(d.title).includes(needle)
      && !d.tags.some(t => fold(t).includes(needle))) return false
    return true
  })
})

const sorted = computed(() => {
  const active = filtered.value
    .filter(d => ACTIVE.includes(shownStatus(d)))
    .sort((a, b) => deadlineOf(a).localeCompare(deadlineOf(b)))
  const settled = filtered.value
    .filter(d => !ACTIVE.includes(shownStatus(d)))
    .sort((a, b) => (b.decidedAt ?? b.updatedAt).localeCompare(a.decidedAt ?? a.updatedAt))
  return [...active, ...settled]
})

const hasAny = computed(() => col.decisions.length > 0)

function toggleStatus(status: DisplayStatus) {
  statusFilter.value = statusFilter.value === status ? null : status
}
function toggleRoute(route: DecisionRoute) {
  routeFilter.value = routeFilter.value === route ? null : route
}
</script>

<template>
  <!-- ld-v2 -->
  <div class="reg">
    <header class="reg__header">
      <div>
        <h1 class="reg__title">Décisions</h1>
        <p class="reg__subtitle">le registre — chaque décision a son URL, pour toujours</p>
      </div>
      <NuxtLink to="/decisions/observatoire" class="reg__observatory">
        <UIcon name="i-lucide-telescope" />
        <span>L'Observatoire</span>
      </NuxtLink>
    </header>

    <div v-if="hasAny" class="reg__pills" role="group" aria-label="Filtrer par état">
      <button
        v-for="pill in statusPills"
        :key="pill.status"
        type="button"
        class="status-pill is-clickable"
        :class="[`status-${pill.status}`, { active: statusFilter === pill.status }]"
        @click="toggleStatus(pill.status)"
      >
        <span>{{ pill.label }}</span>
        <span class="reg__count">{{ pill.count }}</span>
      </button>
    </div>

    <div v-if="hasAny" class="reg__pills" role="group" aria-label="Filtrer par chemin">
      <button
        v-for="pill in routePills"
        :key="pill.route"
        type="button"
        class="reg__route-pill"
        :class="{ 'reg__route-pill--on': routeFilter === pill.route }"
        @click="toggleRoute(pill.route)"
      >
        {{ ROUTE_SHORT[pill.route] }}
      </button>
    </div>

    <div v-if="hasAny" class="reg__tools">
      <div class="reg__search">
        <UIcon name="i-lucide-search" class="reg__search-icon" />
        <input
          v-model="query"
          type="search"
          placeholder="Chercher une décision…"
          aria-label="Chercher une décision"
        >
      </div>
      <DecisionRegistryFilters
        v-model:circle-id="filterCircle"
        v-model:tag="filterTag"
        v-model:mine="filterMine"
        v-model:weight="filterWeight"
        v-model:engraved="filterEngraved"
        v-model:recorded="filterRecorded"
      />
    </div>

    <div v-if="sorted.length > 0" class="reg__list">
      <DecisionRegistryCard v-for="d in sorted" :key="d.id" :decision="d" />
    </div>

    <div v-else class="ld-card reg__empty">
      <template v-if="!hasAny">
        <span class="reg__empty-well">井</span>
        <p class="reg__empty-title">Aucune décision pour l'instant.</p>
        <p class="reg__empty-line">
          Rien ne se crée ici : tout part de la capture —
          « {{ CAPTURE_PLACEHOLDER }} » sur Aujourd'hui.
        </p>
        <NuxtLink to="/" class="ld-btn ld-btn--ghost">
          <UIcon name="i-lucide-sun-medium" />
          <span>Aller à Aujourd'hui</span>
        </NuxtLink>
      </template>
      <template v-else>
        <p class="reg__empty-title">Rien ne correspond à ces filtres.</p>
        <p class="reg__empty-line">Élargis la recherche — ou décide par la capture, sur Aujourd'hui.</p>
      </template>
    </div>
  </div>
</template>

<style scoped>
.reg {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  max-width: 52rem;
  width: 100%;
  margin: 0 auto;
}
.reg__header {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 0.75rem;
  flex-wrap: wrap;
}
.reg__title {
  margin: 0;
  font-size: clamp(1.5rem, 4vw, 2rem);
  font-weight: 800;
  letter-spacing: -0.02em;
}
.reg__subtitle {
  margin: 0.25rem 0 0;
  font-size: 0.9375rem;
  color: var(--mood-text-muted);
}
.reg__observatory {
  display: inline-flex;
  align-items: center;
  gap: 0.4rem;
  min-height: 2.25rem;
  padding: 0.375rem 1rem;
  border-radius: var(--r-pill);
  background: var(--mood-accent-soft);
  color: var(--mood-accent);
  font-size: 0.875rem;
  font-weight: 700;
  text-decoration: none;
  transition: transform 0.1s ease;
}
.reg__observatory:hover { transform: translateY(-1px); }

.reg__pills {
  display: flex;
  flex-wrap: wrap;
  gap: 0.4rem;
}
.reg__count {
  font-size: 0.75rem;
  opacity: 0.75;
}
.reg__route-pill {
  min-height: 2.25rem;
  padding: 0.25rem 0.875rem;
  border-radius: var(--r-pill);
  background: var(--mood-accent-soft);
  color: var(--mood-text-muted);
  font-size: 0.8125rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.12s ease;
}
.reg__route-pill:hover { transform: translateY(-1px); color: var(--mood-text); }
.reg__route-pill--on {
  background: var(--mood-accent);
  color: var(--mood-accent-text);
}

.reg__tools {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  gap: 0.75rem;
}
.reg__search {
  position: relative;
  flex: 1;
  min-width: 14rem;
}
.reg__search input {
  width: 100%;
  min-height: 2.75rem;
  padding: 0.5rem 1rem 0.5rem 2.5rem;
  font-size: 0.9375rem;
  box-shadow: var(--shadow-card);
}
.reg__search-icon {
  position: absolute;
  left: 0.875rem;
  top: 50%;
  transform: translateY(-50%);
  color: var(--mood-text-muted);
  pointer-events: none;
}

.reg__list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.reg__empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.75rem;
  padding: 2.5rem 1.5rem;
  text-align: center;
}
.reg__empty-well {
  font-size: 2rem;
  font-weight: 800;
  color: var(--mood-accent);
  opacity: 0.5;
  transform: rotate(-10deg);
}
.reg__empty-title {
  margin: 0;
  font-size: 1.0625rem;
  font-weight: 700;
}
.reg__empty-line {
  margin: 0;
  font-size: 0.9375rem;
  color: var(--mood-text-muted);
  max-width: 28rem;
}
</style>
