<script setup lang="ts">
// <!-- ld-v2 --> La salle de vote — le geste démocratique central : instruit,
// puis prononcé. Cinq modalités, un seul lieu ; la clôture due est constatée
// au chargement, l'adoption s'applique d'elle-même et se fête sobrement.
import { wotThreshold } from '~/engine'
import { useCollectiveStore } from '~/stores/collective'
import { useDecisionsStore } from '~/stores/decisions'
import {
  ADOPTED_STAMP, ADOPTED_TOAST, ELECTION_RULE, SECRET_DISPLAY, STATUS_LABELS,
  VOTE_PRIVACY, WHO_VOTES, WORKSHOP_MODE,
} from '~/lexicon'
import type { Id, VoteSession } from '~/types/domain'

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

const decisionId = computed(() => String(route.params.id))
const decision = computed(() => col.decisions.find(d => d.id === decisionId.value))
const session = computed<VoteSession | undefined>(() =>
  col.sessions
    .filter(s => s.decisionId === decisionId.value)
    .sort((a, b) => (a.opensAt < b.opensAt ? 1 : -1))[0])
const protocol = computed(() => col.protocols.find(p => p.id === session.value?.protocolId))
const method = computed(() => protocol.value?.method)
const secret = computed(() => protocol.value?.ballot === 'secret')

// ── Qui vote — la liste arrêtée ──
const eligibleIds = computed<Id[]>(() => session.value?.corpusPersonIds ?? [])
const voterEntries = computed(() =>
  col.people.filter(p => eligibleIds.value.includes(p.id)).map(person => ({ person })))
const arrestedDate = computed(() => session.value
  ? new Date(session.value.opensAt).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit' })
  : '')

// ── Mode atelier — saisir pour quelqu'un, en présence ──
const workshop = ref(false)
const asId = ref<Id | ''>('')
onMounted(() => { workshop.value = !!localStorage.getItem('ld2-workshop') })
const votingAs = computed<Id | undefined>(() =>
  workshop.value && asId.value && asId.value !== col.me?.id ? asId.value : undefined)
const voterId = computed(() => votingAs.value ?? col.me?.id)
const inList = computed(() => voterId.value !== undefined && eligibleIds.value.includes(voterId.value))
const canAct = computed(() => session.value?.status === 'open' && inList.value)

const isSteward = computed(() => {
  const d = decision.value
  const me = col.me
  if (!d || !me) return false
  return d.stewardIds.length > 0 ? d.stewardIds.includes(me.id) : d.authorId === me.id
})

// ── Clôture due, constatée au chargement ──
const toast = ref('')
function celebrate() {
  toast.value = ADOPTED_TOAST
  setTimeout(() => { toast.value = '' }, 5000)
}
onMounted(() => {
  const s = session.value
  if (s && s.status === 'open' && s.closesAt <= col.now()) {
    const closed = store.closeSession(s)
    if (!('ok' in closed) && closed.outcome === 'adopted') celebrate()
  }
})

const displayStatus = computed(() => {
  if (session.value?.status === 'frozen') return { css: 'status-frozen', label: 'figé' }
  const s = decision.value?.status ?? 'voting'
  return { css: `status-${s}`, label: STATUS_LABELS[s] }
})

// ── Affiche de session (impression A4) ──
const closesAtLong = computed(() => session.value
  ? new Date(session.value.closesAt).toLocaleString('fr-FR', { dateStyle: 'long', timeStyle: 'short' })
  : '')
const posterRule = computed(() => {
  const f = protocol.value?.formula
  if (!f) return ''
  switch (method.value) {
    case 'consent': return 'Zéro objection maintenue à l\'échéance — le collectif consent.'
    case 'nuanced': return `${f.nuancedThresholdPct ?? 80} % de nuances positives (3 à 5) requis.`
    case 'binary': {
      const active = session.value ? store.activeVotes(session.value.id) : []
      const total = active.filter(v => v.value === 'for' || v.value === 'against').length
      const threshold = wotThreshold(Math.max(session.value?.corpusSize ?? 1, 1), total,
        f.majorityPct, f.baseExponent, f.gradientExponent, f.constantBase)
      return `Seuil actuel : ${threshold.toLocaleString('fr-FR')} pour — il descend quand la participation monte.`
    }
    case 'parametric': return `Le collectif retient la médiane de chaque curseur, cristallisée par le garant${f.parametricMinParticipants !== undefined ? ` (quorum ${f.parametricMinParticipants})` : ''}.`
    case 'election': return ELECTION_RULE
    default: return ''
  }
})
function printPoster() { window.print() }
</script>

<template>
  <!-- ld-v2 -->
  <div class="vote-room">
    <template v-if="decision && session && protocol">
      <div class="no-print vote-room__inner">
        <!-- En-tête -->
        <header class="vr__head">
          <NuxtLink :to="`/decisions/${decision.id}`" class="vr__back">
            <UIcon name="i-lucide-arrow-left" />
            <span>Fiche décision</span>
          </NuxtLink>
          <div class="vr__title-row">
            <h1 class="vr__title">{{ decision.title }}</h1>
            <span v-if="decision.status === 'adopted'" class="ld-stamp">井 {{ ADOPTED_STAMP }}</span>
          </div>
          <div class="vr__pills">
            <span class="status-pill" :class="displayStatus.css">{{ displayStatus.label }}</span>
            <span class="vr__protocol">{{ protocol.name }}</span>
            <span v-if="secret" class="vr__secret">
              <UIcon name="i-lucide-eye-off" />
              <span>{{ SECRET_DISPLAY }}</span>
            </span>
            <LdCountdown v-if="session.status === 'open'" :ends-at="session.closesAt" />
            <button class="ld-btn ld-btn--quiet vr__print" type="button" @click="printPoster()">
              <UIcon name="i-lucide-printer" />
              <span>Imprimer</span>
            </button>
          </div>
          <div class="vr__who">
            <span>{{ WHO_VOTES(eligibleIds.length, arrestedDate) }}</span>
            <LdAvatarStack :people="voterEntries" :size="28" :max="8" />
          </div>
        </header>

        <!-- Mode atelier -->
        <div v-if="workshop" class="vr__workshop">
          <UIcon name="i-lucide-users-round" />
          <span>{{ WORKSHOP_MODE }} — saisir pour</span>
          <select v-model="asId" class="vr__workshop-select">
            <option value="">moi-même</option>
            <option v-for="entry in voterEntries" :key="entry.person.id" :value="entry.person.id">
              {{ entry.person.displayName }}
            </option>
          </select>
        </div>

        <p v-if="session.status === 'open' && !inList" class="vr__consultative">
          Tu n'es pas dans la liste arrêtée — ta voix est consultative.
        </p>

        <!-- S'instruire, puis se prononcer -->
        <VoteInstruct :decision="decision" :secret="secret" />

        <VoteConsent
          v-if="method === 'consent'"
          :decision="decision" :session="session"
          :secret="secret" :can-act="canAct" :as-person-id="votingAs"
        />
        <VoteNuanced
          v-else-if="method === 'nuanced'"
          :decision="decision" :session="session" :protocol="protocol"
          :secret="secret" :can-act="canAct" :as-person-id="votingAs"
        />
        <VoteBinary
          v-else-if="method === 'binary'"
          :decision="decision" :session="session" :protocol="protocol"
          :secret="secret" :can-act="canAct" :as-person-id="votingAs"
        />
        <VoteParametric
          v-else-if="method === 'parametric' && decision.paramSpec"
          :decision="decision" :session="session" :protocol="protocol"
          :secret="secret" :can-act="canAct" :as-person-id="votingAs"
          :is-steward="isSteward"
          @adopted="celebrate()"
        />
        <VoteElection
          v-else-if="method === 'election'"
          :decision="decision" :session="session" :protocol="protocol"
          :secret="secret" :can-act="canAct" :as-person-id="votingAs"
        />

        <!-- Transversal : re-vote et discrétion -->
        <p class="vr__privacy">
          <UIcon name="i-lucide-shield" />
          <span>{{ VOTE_PRIVACY }}</span>
        </p>
        <VoteMyHistory v-if="col.me && voterId === col.me.id" :session="session" :voter-id="col.me.id" />
      </div>

      <!-- Affiche de session A4 -->
      <div class="print-only vr__poster">
        <h1>{{ decision.title }}</h1>
        <p v-if="decision.body" class="vr__poster-body">{{ decision.body }}</p>
        <hr>
        <p><strong>{{ WHO_VOTES(eligibleIds.length, arrestedDate) }}</strong></p>
        <p v-if="!secret">{{ voterEntries.map(e => e.person.displayName).join(' · ') }}</p>
        <p>{{ posterRule }}</p>
        <p><strong>Échéance :</strong> {{ closesAtLong }}</p>
        <p><strong>Comment participer :</strong> ouvre la salle de vote « {{ decision.title }} » dans libreDecision, ou confie ton geste en présence (mode atelier).</p>
        <p class="vr__poster-seal">井</p>
      </div>
    </template>

    <!-- Garde-fous -->
    <div v-else-if="!decision" class="ld-card vr__empty">
      <p>Cette décision est introuvable.</p>
      <NuxtLink to="/decisions" class="ld-btn ld-btn--ghost">Toutes les décisions</NuxtLink>
    </div>
    <div v-else class="ld-card vr__empty">
      <p>Cette décision n'a pas encore de session de vote.</p>
      <NuxtLink :to="`/decisions/${decisionId}`" class="ld-btn ld-btn--ghost">Fiche décision</NuxtLink>
    </div>

    <!-- Micro-célébration — aucune fanfare -->
    <Transition name="vr-toast">
      <div v-if="toast" class="vr__toast">
        <span class="ld-stamp">井 {{ ADOPTED_STAMP }}</span>
        <span>{{ toast }}</span>
      </div>
    </Transition>
  </div>
</template>

<style scoped>
.vote-room { max-width: 46rem; width: 100%; margin: 0 auto; }
.vote-room__inner { display: flex; flex-direction: column; gap: 1rem; }
.vr__head { display: flex; flex-direction: column; gap: 0.6rem; }
.vr__back {
  display: inline-flex; align-items: center; gap: 0.35rem; align-self: flex-start;
  font-size: 0.8125rem; font-weight: 700; color: var(--mood-text-muted); text-decoration: none;
}
.vr__back:hover { color: var(--mood-accent); }
.vr__title-row { display: flex; align-items: flex-start; gap: 0.9rem; flex-wrap: wrap; }
.vr__title {
  margin: 0; font-size: clamp(1.25rem, 4vw, 1.75rem); font-weight: 800;
  line-height: 1.25; letter-spacing: -0.01em; flex: 1; min-width: 0;
}
.vr__pills { display: flex; align-items: center; flex-wrap: wrap; gap: 0.5rem; }
.vr__protocol {
  font-size: 0.8125rem; font-weight: 700; color: var(--mood-accent);
  background: var(--mood-accent-soft); padding: 4px 13px; border-radius: var(--r-pill);
}
.vr__secret {
  display: inline-flex; align-items: center; gap: 0.3rem;
  font-size: 0.8125rem; font-weight: 700; color: var(--mood-status-fige);
  background: var(--mood-status-fige-bg); padding: 4px 13px; border-radius: var(--r-pill);
}
.vr__print { margin-left: auto; padding: 0.25rem 0.75rem; font-size: 0.8125rem; }
.vr__who {
  display: flex; align-items: center; flex-wrap: wrap; gap: 0.6rem 0.9rem;
  font-size: 0.9375rem; font-weight: 600; color: var(--mood-text-muted);
}
.vr__workshop {
  display: flex; align-items: center; flex-wrap: wrap; gap: 0.5rem;
  padding: 0.55rem 0.9rem; border-radius: var(--r-input);
  background: color-mix(in srgb, var(--mood-secondary) 10%, var(--mood-surface));
  color: var(--mood-secondary); font-size: 0.875rem; font-weight: 700;
}
.vr__workshop-select {
  min-height: 2.25rem; padding: 0.25rem 0.6rem; font-size: 0.875rem; font-weight: 600;
  box-shadow: inset 0 0 0 1.5px var(--mood-input-border);
}
.vr__consultative {
  margin: 0; padding: 0.55rem 0.9rem; border-radius: var(--r-input);
  background: var(--mood-status-fenetre-bg); color: var(--mood-status-fenetre);
  font-size: 0.875rem; font-weight: 600;
}
.vr__privacy {
  display: flex; align-items: baseline; gap: 0.45rem; margin: 0;
  font-size: 0.8125rem; color: var(--mood-text-muted);
}
.vr__empty {
  padding: 2rem; display: flex; flex-direction: column; align-items: center; gap: 1rem;
  text-align: center; font-weight: 600;
}
.vr__empty p { margin: 0; }
.vr__toast {
  position: fixed; left: 50%; bottom: 1.5rem; transform: translateX(-50%);
  z-index: 50; display: flex; align-items: center; gap: 0.75rem;
  background: var(--mood-surface); color: var(--mood-text);
  padding: 0.75rem 1.25rem; border-radius: var(--r-card);
  box-shadow: var(--shadow-raised); font-weight: 600; font-size: 0.9375rem;
  max-width: min(92vw, 30rem);
}
.vr-toast-enter-active, .vr-toast-leave-active { transition: opacity 0.12s ease, transform 0.12s ease; }
.vr-toast-enter-from, .vr-toast-leave-to { opacity: 0; transform: translateX(-50%) translateY(8px); }

/* Affiche A4 — noir sur blanc, sans ambiance */
.vr__poster { color: #111; font-size: 12pt; line-height: 1.5; }
.vr__poster h1 { font-size: 22pt; margin: 0 0 8pt; }
.vr__poster hr { border: none; border-top: 1pt solid #111; margin: 8pt 0; }
.vr__poster-body { white-space: pre-wrap; }
.vr__poster-seal { font-size: 28pt; text-align: right; margin-top: 16pt; }
</style>
