<script setup lang="ts">
/**
 * /decisions/[id] — la fiche décision, URL permanente de l'objet pivot.
 * Progressive disclosure par état : timeline + périmètre toujours ;
 * s'instruire (formulation/vote), fenêtre, formulation, éléments de dossier,
 * session, vigueur, chaînage. Imprimable en PV A4 ; gravure locale.
 */
import {
  ADOPTED_STAMP, BASELINE_ARROW, ENGAGES_LABEL, INERTIA_LABELS,
  REOPEN_HANDLE, ROUTE_ICONS, ROUTE_LABELS, URGENT_BADGE, WEIGHT_LABELS,
} from '~/lexicon'
import { useCollectiveStore } from '~/stores/collective'
import { displayStatus, displayStatusLabel, dateFr } from '~/components/decisions/decisionUi'

const route = useRoute()
const col = useCollectiveStore()

const decisionId = computed(() => route.params.id as string)
const decision = computed(() => col.decisions.find(d => d.id === decisionId.value))

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

const shown = computed(() =>
  decision.value ? displayStatus(decision.value, session.value) : 'draft')

// ── Origine : protocole et inertie (poignée « Remettre en question ») ──
const originProtocol = computed(() =>
  decision.value?.protocolId
    ? col.protocols.find(p => p.id === decision.value!.protocolId)?.name
    : undefined)
const originInertia = computed(() => {
  const clauseId = decision.value?.amendsClauseId
  if (!clauseId) return undefined
  const clause = col.clauses.find(c => c.id === clauseId)
  return clause ? INERTIA_LABELS[clause.inertia] : undefined
})
const originLine = computed(() => {
  const parts: string[] = []
  if (originProtocol.value) parts.push(originProtocol.value)
  if (originInertia.value) parts.push(originInertia.value)
  return parts.length > 0
    ? `Le protocole et l'inertie d'origine s'appliquent : ${parts.join(' — ')}.`
    : 'Le protocole et l\'inertie d\'origine s\'appliquent.'
})

// ── Blocs selon l'état ──
const showInstruct = computed(() =>
  decision.value?.status === 'framing' || decision.value?.status === 'voting')
const showWindow = computed(() =>
  decision.value?.status === 'objection' || decision.value?.status === 'advice')
const hasElements = computed(() =>
  col.decisions.some(d =>
    d.parentDecisionId === decisionId.value && d.chainKind === 'element'))

const framingDays = computed(() => col.settings?.triage.framingDays ?? 14)

// ── Gestes ──
async function splitDossier() {
  await navigateTo(`/decider?parent=${decisionId.value}&chain=element`)
}
async function reopen() {
  await navigateTo(`/decider?parent=${decisionId.value}&chain=revision`)
}
</script>

<template>
  <!-- ld-v2 -->
  <article v-if="decision" class="fiche">
    <!-- ── En-tête ── -->
    <header class="fiche__head">
      <div class="fiche__status-row">
        <span class="status-pill" :class="`status-${shown}`">
          {{ displayStatusLabel(shown) }}
        </span>
        <span v-if="decision.status === 'adopted'" class="ld-stamp">
          井 {{ ADOPTED_STAMP }}
        </span>
        <span v-if="decision.engraving" class="fiche__well" title="gravée">井</span>
      </div>

      <h1 class="fiche__title">{{ decision.title }}</h1>

      <p v-if="decision.baselineNote" class="fiche__baseline">
        <span class="fiche__baseline-arrow">{{ BASELINE_ARROW }}</span>
        <span>{{ decision.baselineNote }}</span>
      </p>

      <div class="fiche__meta">
        <span class="fiche__route" :style="{ color: `var(--route-${decision.route})` }">
          <UIcon :name="ROUTE_ICONS[decision.route]" />
          <span>{{ ROUTE_LABELS[decision.route] }}</span>
        </span>
        <span class="fiche__chip">{{ WEIGHT_LABELS[decision.weight] }}</span>
        <span v-if="decision.urgent" class="fiche__urgent">
          <UIcon name="i-lucide-siren" />
          <span>{{ URGENT_BADGE }}</span>
        </span>
      </div>

      <p v-if="decision.decidedHow" class="fiche__how">
        Comment ça s'est décidé : « {{ decision.decidedHow }} »
      </p>

      <div v-if="decision.routeOverridden && decision.overrideNote" class="fiche__banner">
        <UIcon name="i-lucide-feather" />
        <span><strong>Chemin allégé</strong> — « {{ decision.overrideNote }} »</span>
      </div>
      <div v-if="decision.scopeKeptNote" class="fiche__banner">
        <UIcon name="i-lucide-circle-dot" />
        <span><strong>Périmètre maintenu</strong> — « {{ decision.scopeKeptNote }} »</span>
      </div>
    </header>

    <!-- ── Actions + fiche de preuve ── -->
    <DecisionProof :decision="decision" />

    <!-- ── Cycle de vie + périmètre ── -->
    <div class="fiche__grid">
      <div class="ld-card fiche__card">
        <h2 class="fiche__card-title">Cycle de vie</h2>
        <DecisionTimeline :decision="decision" :session="session" />
      </div>
      <div class="ld-card fiche__card">
        <DecisionPerimeter :decision="decision" />
      </div>
    </div>

    <!-- ── S'instruire ── -->
    <div v-if="showInstruct" class="ld-card fiche__card">
      <DecisionInstruct :decision="decision" />
    </div>

    <!-- ── Fenêtre ── -->
    <div v-if="showWindow" class="ld-card fiche__card">
      <DecisionWindow :decision="decision" />
    </div>

    <!-- ── Formulation ── -->
    <div v-if="decision.status === 'framing'" class="ld-card fiche__card">
      <h2 class="fiche__card-title">Formulation</h2>
      <p class="fiche__framing-phrase">
        {{ framingDays }} jours pour s'instruire et formuler des contre-propositions.
      </p>
      <LdCountdown v-if="decision.windowEndsAt" :ends-at="decision.windowEndsAt" />
      <div v-if="decision.weight === 'structural'" class="no-print">
        <button type="button" class="ld-btn ld-btn--ghost" @click="splitDossier()">
          <UIcon name="i-lucide-scissors" />
          <span>Découper en micro-décisions</span>
        </button>
      </div>
    </div>

    <!-- ── Éléments du dossier ── -->
    <div v-if="hasElements" class="ld-card fiche__card">
      <DecisionElements :decision="decision" />
    </div>

    <!-- ── Session ── -->
    <div v-if="session" class="ld-card fiche__card">
      <DecisionSession :decision="decision" />
    </div>

    <!-- ── Vigueur ── -->
    <div v-if="decision.status === 'adopted'" class="ld-card fiche__card">
      <DecisionVigor :decision="decision" />
    </div>

    <!-- ── Remettre en question ── -->
    <div v-if="decision.status === 'adopted'" class="ld-card fiche__card fiche__reopen no-print">
      <div>
        <p class="fiche__reopen-title">{{ REOPEN_HANDLE }}</p>
        <p class="fiche__reopen-line">{{ originLine }}</p>
      </div>
      <button type="button" class="ld-btn ld-btn--ghost" @click="reopen()">
        <UIcon name="i-lucide-rotate-ccw" />
        <span>{{ REOPEN_HANDLE }}</span>
      </button>
    </div>

    <!-- ── Chaînage ── -->
    <div class="fiche__chain-wrap">
      <DecisionChain :decision="decision" />
    </div>

    <!-- ── Pied de PV (impression) ── -->
    <p class="print-only fiche__pv-foot">
      {{ ENGAGES_LABEL }} : {{ decision.resources?.note ?? '—' }}
      — fiche imprimée le {{ dateFr(new Date().toISOString()) }} · libreDecision
    </p>
  </article>

  <div v-else class="ld-card fiche__missing">
    <p>Cette décision est introuvable dans ce collectif.</p>
    <NuxtLink to="/decisions" class="ld-btn ld-btn--ghost">Retour au registre</NuxtLink>
  </div>
</template>

<style scoped>
.fiche {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  max-width: 52rem;
  width: 100%;
  margin: 0 auto;
}
.fiche__head { display: flex; flex-direction: column; gap: 0.625rem; }
.fiche__status-row {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex-wrap: wrap;
}
.fiche__well {
  font-size: 1.25rem;
  font-weight: 800;
  color: var(--mood-status-vigueur);
  transform: rotate(-10deg);
}
.fiche__title {
  margin: 0;
  font-size: clamp(1.375rem, 4vw, 1.875rem);
  font-weight: 800;
  line-height: 1.25;
  letter-spacing: -0.02em;
  overflow-wrap: anywhere;
}
.fiche__baseline {
  margin: 0;
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  align-items: baseline;
  font-size: 0.9375rem;
}
.fiche__baseline-arrow {
  font-weight: 800;
  font-size: 0.8125rem;
  color: var(--mood-accent);
  background: var(--mood-accent-soft);
  padding: 2px 10px;
  border-radius: var(--r-pill);
  white-space: nowrap;
}
.fiche__meta {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.5rem;
}
.fiche__route {
  display: inline-flex;
  align-items: center;
  gap: 0.4rem;
  font-weight: 800;
  font-size: 0.9375rem;
}
.fiche__chip {
  font-size: 0.8125rem;
  font-weight: 600;
  color: var(--mood-text-muted);
  background: var(--mood-accent-soft);
  padding: 3px 10px;
  border-radius: var(--r-pill);
}
.fiche__urgent {
  display: inline-flex;
  align-items: center;
  gap: 0.3rem;
  font-size: 0.8125rem;
  font-weight: 700;
  color: var(--route-urgent);
  background: color-mix(in srgb, var(--route-urgent) 11%, transparent);
  padding: 3px 10px;
  border-radius: var(--r-pill);
}
.fiche__how {
  margin: 0;
  font-size: 0.9375rem;
  font-style: italic;
  color: var(--mood-text-muted);
}
.fiche__banner {
  display: flex;
  align-items: flex-start;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  border-radius: var(--r-input);
  font-size: 0.9375rem;
  color: var(--mood-status-fenetre);
  background: var(--mood-status-fenetre-bg);
  box-shadow: inset 0 0 0 1.5px var(--mood-status-fenetre);
}
.fiche__grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
}
@media (min-width: 768px) {
  .fiche__grid { grid-template-columns: 1fr 1fr; }
}
.fiche__card {
  padding: 1.25rem 1.375rem;
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}
.fiche__card-title {
  margin: 0;
  font-size: 1.0625rem;
  font-weight: 800;
  letter-spacing: -0.01em;
}
.fiche__framing-phrase { margin: 0; font-size: 0.9375rem; font-weight: 600; }
.fiche__reopen {
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 0.75rem;
}
.fiche__reopen-title { margin: 0; font-weight: 800; font-size: 0.9375rem; }
.fiche__reopen-line {
  margin: 0.125rem 0 0;
  font-size: 0.8125rem;
  color: var(--mood-text-muted);
}
.fiche__pv-foot { font-size: 0.75rem; color: #333333; }
.fiche__missing {
  max-width: 52rem;
  margin: 0 auto;
  padding: 2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
  text-align: center;
}
@media print {
  .fiche__grid { grid-template-columns: 1fr 1fr; }
  .fiche__card { padding: 0.5rem 0; }
}
</style>
