<script setup lang="ts">
// <!-- ld-v2 --> « Exercice du mandat » (Δ7) — des FAITS COMPTÉS, jamais
// synthétisés : décisions tracées, objections listées, rapports rendus/dus.
// Le titulaire rend son rapport ici quand il est dû — contenu dépliable.
import type { Mandate } from '~/types/domain'
import { useCollectiveStore } from '~/stores/collective'
import { MANDATE_EXERCISE, STATUS_LABELS } from '~/lexicon'
import {
  OBJECTION_STATUS_LABELS,
  formatDay,
  mandateFacts,
  reportIntervalMs,
} from './mandateUi'

const props = defineProps<{ mandate: Mandate }>()

const col = useCollectiveStore()

const facts = computed(() => mandateFacts(props.mandate, col.decisions, col.objections))

const objectionRows = computed(() =>
  facts.value.objections.map(o => ({
    id: o.id,
    decisionId: o.decisionId,
    decisionTitle: col.decisions.find(d => d.id === o.decisionId)?.title ?? '—',
    argument: o.argument,
    statusLabel: OBJECTION_STATUS_LABELS[o.status],
    open: o.status === 'open',
  })),
)

const sortedReports = computed(() =>
  [...props.mandate.reports].sort((a, b) => (a.dueAt < b.dueAt ? -1 : 1)),
)

/** Le rapport dû maintenant, à rendre par le titulaire (moi). */
const dueReport = computed(() => {
  if (col.me?.id !== props.mandate.holderId) return undefined
  if (props.mandate.status !== 'active') return undefined
  return sortedReports.value.find(r => r.deliveredAt === undefined && r.dueAt <= col.now())
})

const reportText = ref('')

function deliverReport(): void {
  const target = dueReport.value
  if (!target || reportText.value.trim().length === 0) return
  target.deliveredAt = col.now()
  target.content = reportText.value.trim()
  // Cadence : le prochain rapport garde l'espacement existant, borné à l'échéance.
  const interval = reportIntervalMs(props.mandate)
  if (interval !== undefined) {
    const nextDue = new Date(new Date(target.dueAt).getTime() + interval).toISOString()
    if (nextDue < props.mandate.endsAt) props.mandate.reports.push({ dueAt: nextDue })
  }
  col.stamp(props.mandate)
  col.persist()
  reportText.value = ''
}
</script>

<template>
  <!-- ld-v2 -->
  <section class="mex ld-card">
    <h2 class="mex__title">
      <UIcon name="i-lucide-list-checks" />
      {{ MANDATE_EXERCISE }}
    </h2>
    <p class="mex__facts">{{ facts.line }}</p>

    <!-- Décisions tracées -->
    <div v-if="facts.traced.length" class="mex__block">
      <h3 class="mex__block-title">Décisions tracées</h3>
      <ul class="mex__list">
        <li v-for="d in facts.traced" :key="d.id">
          <NuxtLink :to="`/decisions/${d.id}`" class="mex__row">
            <span class="mex__row-title">{{ d.title }}</span>
            <span class="status-pill" :class="`status-${d.status}`">
              {{ STATUS_LABELS[d.status] }}
            </span>
          </NuxtLink>
        </li>
      </ul>
    </div>

    <!-- Objections — liste cliquable -->
    <div v-if="objectionRows.length" class="mex__block">
      <h3 class="mex__block-title">Objections</h3>
      <ul class="mex__list">
        <li v-for="o in objectionRows" :key="o.id">
          <NuxtLink :to="`/decisions/${o.decisionId}`" class="mex__row">
            <span class="mex__row-title">{{ o.argument }}</span>
            <span class="mex__obj-status" :class="{ 'mex__obj-status--open': o.open }">
              {{ o.statusLabel }}
            </span>
          </NuxtLink>
        </li>
      </ul>
    </div>

    <!-- Rapports — rendus dépliables, saisie quand dû -->
    <div v-if="sortedReports.length || dueReport" class="mex__block">
      <h3 class="mex__block-title">
        Rapports — {{ facts.reportsDelivered }}/{{ facts.reportsTotal }} rendus
      </h3>
      <ul class="mex__list">
        <li v-for="r in sortedReports" :key="r.dueAt">
          <details v-if="r.deliveredAt" class="mex__report">
            <summary class="mex__report-summary">
              <UIcon name="i-lucide-file-check-2" />
              <span>Rapport rendu le {{ formatDay(r.deliveredAt) }}</span>
              <span class="mex__report-due">dû le {{ formatDay(r.dueAt) }}</span>
            </summary>
            <p class="mex__report-content">{{ r.content }}</p>
          </details>
          <div v-else class="mex__report mex__report--pending">
            <UIcon name="i-lucide-file-clock" />
            <span>Rapport dû le {{ formatDay(r.dueAt) }}</span>
          </div>
        </li>
      </ul>

      <form v-if="dueReport" class="mex__deliver" @submit.prevent="deliverReport">
        <label class="mex__deliver-label" for="mex-report">
          Ton rapport est dû — quelques phrases suffisent.
        </label>
        <textarea
          id="mex-report"
          v-model="reportText"
          rows="4"
          lang="fr"
          spellcheck="true"
          placeholder="Ce qui a été fait, ce qui engage la suite…"
        />
        <button type="submit" class="ld-btn" :disabled="reportText.trim().length === 0">
          <UIcon name="i-lucide-send" />
          Rendre le rapport
        </button>
      </form>
    </div>
  </section>
</template>

<style scoped>
.mex { padding: 1.375rem 1.5rem; display: flex; flex-direction: column; gap: 1rem; }
.mex__title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin: 0;
  font-size: 1.0625rem;
  font-weight: 800;
}
.mex__facts {
  margin: 0;
  font-size: 0.9375rem;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}
.mex__block { display: flex; flex-direction: column; gap: 0.5rem; }
.mex__block-title {
  margin: 0;
  font-size: 0.75rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: var(--mood-text-muted);
}
.mex__list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 0.375rem; }
.mex__row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.75rem;
  padding: 0.5rem 0.75rem;
  border-radius: var(--r-input);
  background: var(--mood-accent-soft);
  text-decoration: none;
  color: var(--mood-text);
  transition: transform 0.1s ease;
}
.mex__row:hover { transform: translateY(-1px); }
.mex__row-title {
  font-size: 0.875rem;
  font-weight: 600;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.mex__obj-status {
  flex-shrink: 0;
  font-size: 0.75rem;
  font-weight: 700;
  color: var(--mood-text-muted);
}
.mex__obj-status--open { color: var(--mood-status-fenetre); }
.mex__report {
  border-radius: var(--r-input);
  background: var(--mood-accent-soft);
  padding: 0.5rem 0.75rem;
}
.mex__report-summary {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.875rem;
  font-weight: 600;
  cursor: pointer;
  list-style: none;
}
.mex__report-summary::-webkit-details-marker { display: none; }
.mex__report-due { margin-left: auto; font-size: 0.75rem; color: var(--mood-text-muted); }
.mex__report-content {
  margin: 0.625rem 0 0.25rem;
  font-size: 0.875rem;
  line-height: 1.55;
  color: var(--mood-text);
  white-space: pre-line;
}
.mex__report--pending {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.875rem;
  font-weight: 600;
  color: var(--mood-status-fenetre);
  background: var(--mood-status-fenetre-bg);
}
.mex__deliver { display: flex; flex-direction: column; gap: 0.625rem; margin-top: 0.375rem; }
.mex__deliver-label { font-size: 0.875rem; font-weight: 600; }
.mex__deliver textarea {
  width: 100%;
  padding: 0.625rem 0.875rem;
  font: inherit;
  font-size: 0.9375rem;
  color: var(--mood-text);
  background: var(--mood-input-bg);
  border: none;
  border-radius: var(--r-input);
  box-shadow: inset 0 0 0 1px var(--mood-input-border);
  resize: vertical;
}
.mex__deliver textarea:focus {
  outline: none;
  box-shadow: inset 0 0 0 2px var(--mood-input-focus);
}
.mex__deliver .ld-btn { align-self: flex-start; }
</style>
