<script setup lang="ts">
/**
 * Boite a outils — page principale des protocoles de vote.
 *
 * Liste les protocoles avec leurs details complets,
 * les configurations de formule, et le simulateur / explainer.
 */
const protocols = useProtocolsStore()
const auth = useAuthStore()

const showCreateModal = ref(false)
const creating = ref(false)
const formulaOpen = ref(false)

/** Creation form state. */
const newProtocol = reactive({
  name: '',
  description: '',
  vote_type: 'binary',
  formula_config_id: '',
})

onMounted(async () => {
  await Promise.all([
    protocols.fetchProtocols(),
    protocols.fetchFormulas(),
  ])
})

const voteTypeLabel = (voteType: string) => {
  switch (voteType) {
    case 'binary': return 'Binaire'
    case 'nuanced': return 'Nuance'
    default: return voteType
  }
}

const voteTypeColor = (voteType: string) => {
  switch (voteType) {
    case 'binary': return 'primary'
    case 'nuanced': return 'info'
    default: return 'neutral'
  }
}

const voteTypeOptions = [
  { label: 'Binaire (Pour/Contre)', value: 'binary' },
  { label: 'Nuance (6 niveaux)', value: 'nuanced' },
]

const formulaOptions = computed(() => {
  return protocols.formulas.map(f => ({
    label: f.name,
    value: f.id,
  }))
})

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('fr-FR', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  })
}

function openCreateModal() {
  newProtocol.name = ''
  newProtocol.description = ''
  newProtocol.vote_type = 'binary'
  newProtocol.formula_config_id = ''
  showCreateModal.value = true
}

async function createProtocol() {
  if (!newProtocol.name.trim() || !newProtocol.formula_config_id) return

  creating.value = true
  try {
    await protocols.createProtocol({
      name: newProtocol.name.trim(),
      description: newProtocol.description.trim() || null,
      vote_type: newProtocol.vote_type,
      formula_config_id: newProtocol.formula_config_id,
    })
    showCreateModal.value = false
    await protocols.fetchProtocols()
  }
  finally {
    creating.value = false
  }
}
</script>

<template>
  <div class="toolbox-page">
    <!-- Header -->
    <div class="toolbox-page__header">
      <div>
        <h1 class="toolbox-page__title">
          <UIcon name="i-lucide-wrench" class="toolbox-page__title-icon" />
          Boite a outils
        </h1>
        <p class="toolbox-page__subtitle">
          Modalites de vote et formules configurables
        </p>
      </div>
      <div class="toolbox-page__actions">
        <NuxtLink to="/protocols/formulas">
          <UButton variant="outline" icon="i-lucide-calculator" size="sm">
            Simulateur de formules
          </UButton>
        </NuxtLink>
        <UButton
          v-if="auth.isAuthenticated"
          icon="i-lucide-plus"
          size="sm"
          @click="openCreateModal"
        >
          Nouveau protocole
        </UButton>
      </div>
    </div>

    <!-- Loading state -->
    <template v-if="protocols.loading">
      <div class="space-y-3">
        <LoadingSkeleton v-for="i in 4" :key="i" :lines="4" card />
      </div>
    </template>

    <!-- Error state -->
    <template v-else-if="protocols.error">
      <div class="flex items-center gap-3 p-4 rounded-lg" style="background: var(--mood-surface); border: 1px solid var(--mood-border);">
        <UIcon name="i-lucide-alert-circle" class="text-xl" style="color: var(--mood-error);" />
        <p style="color: var(--mood-text);">{{ protocols.error }}</p>
      </div>
    </template>

    <template v-else>
      <!-- Protocols section -->
      <div class="toolbox-section">
        <h2 class="toolbox-section__title">
          Protocoles de vote
          <UBadge variant="subtle" size="xs">
            {{ protocols.protocols.length }}
          </UBadge>
        </h2>

        <div v-if="protocols.protocols.length === 0" class="toolbox-empty">
          <UIcon name="i-lucide-settings" class="text-3xl" />
          <p>Aucun protocole de vote configure</p>
        </div>

        <div v-else class="toolbox-protocol-grid">
          <NuxtLink
            v-for="protocol in protocols.protocols"
            :key="protocol.id"
            :to="`/protocols/${protocol.id}`"
            class="protocol-card"
          >
            <!-- Protocol header -->
            <div class="protocol-card__header">
              <h3 class="protocol-card__name">
                {{ protocol.name }}
              </h3>
              <div class="protocol-card__badges">
                <UBadge :color="(voteTypeColor(protocol.vote_type) as any)" variant="subtle" size="xs">
                  {{ voteTypeLabel(protocol.vote_type) }}
                </UBadge>
                <UBadge v-if="protocol.is_meta_governed" color="warning" variant="subtle" size="xs">
                  Meta-gouverne
                </UBadge>
              </div>
            </div>

            <p v-if="protocol.description" class="protocol-card__description">
              {{ protocol.description }}
            </p>

            <!-- Mode params -->
            <div v-if="protocol.mode_params" class="protocol-card__mode-params">
              <ModeParamsDisplay :mode-params="protocol.mode_params" />
            </div>

            <!-- Formula config summary -->
            <div class="protocol-card__formula">
              <h4 class="protocol-card__formula-title">
                Formule : {{ protocol.formula_config.name }}
              </h4>
              <div class="protocol-card__formula-grid">
                <div>
                  <span class="protocol-card__formula-label">Duree</span>
                  <span class="protocol-card__formula-value">{{ protocol.formula_config.duration_days }}j</span>
                </div>
                <div>
                  <span class="protocol-card__formula-label">Majorite</span>
                  <span class="protocol-card__formula-value">{{ protocol.formula_config.majority_pct }}%</span>
                </div>
                <div>
                  <span class="protocol-card__formula-label">Base</span>
                  <span class="protocol-card__formula-value">{{ protocol.formula_config.base_exponent }}</span>
                </div>
                <div>
                  <span class="protocol-card__formula-label">Gradient</span>
                  <span class="protocol-card__formula-value">{{ protocol.formula_config.gradient_exponent }}</span>
                </div>
                <div v-if="protocol.formula_config.smith_exponent !== null">
                  <span class="protocol-card__formula-label">Smith</span>
                  <span class="protocol-card__formula-value">{{ protocol.formula_config.smith_exponent }}</span>
                </div>
                <div v-if="protocol.formula_config.techcomm_exponent !== null">
                  <span class="protocol-card__formula-label">TechComm</span>
                  <span class="protocol-card__formula-value">{{ protocol.formula_config.techcomm_exponent }}</span>
                </div>
              </div>
            </div>
          </NuxtLink>
        </div>
      </div>

      <!-- Formula configurations section -->
      <div class="toolbox-section">
        <h2 class="toolbox-section__title">
          Configurations de formule
          <UBadge variant="subtle" size="xs">
            {{ protocols.formulas.length }}
          </UBadge>
        </h2>

        <div v-if="protocols.formulas.length === 0" class="toolbox-empty">
          <UIcon name="i-lucide-calculator" class="text-3xl" />
          <p>Aucune configuration de formule</p>
        </div>

        <div v-else class="formula-table-wrapper">
          <table class="formula-table">
            <thead>
              <tr>
                <th>Nom</th>
                <th>Duree</th>
                <th>Majorite</th>
                <th>B</th>
                <th>G</th>
                <th>C</th>
                <th>Smith</th>
                <th>TechComm</th>
                <th>Date</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="formula in protocols.formulas" :key="formula.id">
                <td class="formula-table__name">{{ formula.name }}</td>
                <td>{{ formula.duration_days }}j</td>
                <td>{{ formula.majority_pct }}%</td>
                <td class="font-mono">{{ formula.base_exponent }}</td>
                <td class="font-mono">{{ formula.gradient_exponent }}</td>
                <td class="font-mono">{{ formula.constant_base }}</td>
                <td class="font-mono">{{ formula.smith_exponent ?? '-' }}</td>
                <td class="font-mono">{{ formula.techcomm_exponent ?? '-' }}</td>
                <td class="formula-table__date">{{ formatDate(formula.created_at) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Formula explainer — collapsible -->
      <UCollapsible v-model:open="formulaOpen">
        <UButton
          variant="ghost"
          size="sm"
          :icon="formulaOpen ? 'i-lucide-chevron-up' : 'i-lucide-chevron-down'"
          class="formula-explainer-trigger"
        >
          <div class="flex items-center gap-2">
            <UIcon name="i-lucide-book-open" />
            <span>Reference : Formule de seuil WoT</span>
          </div>
        </UButton>
        <template #content>
          <div class="formula-explainer-content">
            <code class="formula-explainer-code">
              Seuil = C + B^W + (M + (1-M) * (1 - (T/W)^G)) * max(0, T-C)
            </code>
            <div class="formula-explainer-params">
              <div><strong>C</strong> = constante de base (plancher fixe)</div>
              <div><strong>B</strong> = exposant de base (B^W tend vers 0 si B &lt; 1)</div>
              <div><strong>W</strong> = taille du corpus WoT</div>
              <div><strong>T</strong> = nombre total de votes</div>
              <div><strong>M</strong> = ratio de majorite (M = majorite_pct / 100)</div>
              <div><strong>G</strong> = exposant du gradient d'inertie</div>
            </div>
            <USeparator />
            <p class="formula-explainer-note">
              L'inertie fonctionne ainsi : faible participation implique quasi-unanimite requise ;
              forte participation permet une majorite simple suffisante.
              Cela protege contre les votes precipites tout en permettant l'efficacite
              lorsque la communaute est mobilisee.
            </p>
            <UButton
              to="/protocols/formulas"
              label="Ouvrir le simulateur"
              variant="outline"
              size="xs"
              icon="i-lucide-calculator"
            />
          </div>
        </template>
      </UCollapsible>
    </template>

    <!-- Create protocol modal -->
    <UModal v-model:open="showCreateModal">
      <template #content>
        <div class="p-6 space-y-6">
          <h3 class="text-lg font-semibold" style="color: var(--mood-text);">
            Nouveau protocole de vote
          </h3>

          <div class="space-y-4">
            <div class="space-y-2">
              <label class="text-sm font-medium" style="color: var(--mood-text-muted);">
                Nom du protocole
              </label>
              <UInput v-model="newProtocol.name" placeholder="Ex: Vote standard G1" />
            </div>

            <div class="space-y-2">
              <label class="text-sm font-medium" style="color: var(--mood-text-muted);">
                Description (optionnel)
              </label>
              <UTextarea v-model="newProtocol.description" placeholder="Description du protocole..." :rows="2" />
            </div>

            <div class="space-y-2">
              <label class="text-sm font-medium" style="color: var(--mood-text-muted);">
                Type de vote
              </label>
              <USelect
                v-model="newProtocol.vote_type"
                :items="voteTypeOptions"
                value-key="value"
              />
            </div>

            <div class="space-y-2">
              <label class="text-sm font-medium" style="color: var(--mood-text-muted);">
                Configuration de formule
              </label>
              <USelect
                v-model="newProtocol.formula_config_id"
                :items="formulaOptions"
                placeholder="Selectionnez une formule..."
                value-key="value"
              />
            </div>
          </div>

          <div class="flex justify-end gap-3">
            <UButton variant="ghost" color="neutral" @click="showCreateModal = false">
              Annuler
            </UButton>
            <UButton
              :loading="creating"
              :disabled="!newProtocol.name.trim() || !newProtocol.formula_config_id"
              @click="createProtocol"
            >
              Creer le protocole
            </UButton>
          </div>
        </div>
      </template>
    </UModal>
  </div>
</template>

<style scoped>
.toolbox-page {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

/* --- Header --- */
.toolbox-page__header {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: space-between;
  gap: 1rem;
}

.toolbox-page__title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.5rem;
  font-weight: 800;
  color: var(--mood-text);
}

.toolbox-page__title-icon {
  color: var(--mood-accent);
}

.toolbox-page__subtitle {
  margin-top: 0.25rem;
  font-size: 0.875rem;
  color: var(--mood-text-muted);
}

.toolbox-page__actions {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

/* --- Section --- */
.toolbox-section {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.toolbox-section__title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.125rem;
  font-weight: 600;
  color: var(--mood-text);
}

.toolbox-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.75rem;
  padding: 2rem;
  text-align: center;
  color: var(--mood-text-muted);
  background: var(--mood-surface);
  border: 1px dashed var(--mood-border);
  border-radius: 0.75rem;
}

/* --- Protocol cards --- */
.toolbox-protocol-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
  gap: 1rem;
}

.protocol-card {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  padding: 1rem 1.25rem;
  background: var(--mood-surface);
  border: 1px solid var(--mood-border);
  border-radius: 0.75rem;
  text-decoration: none;
  transition: all 0.2s ease;
  cursor: pointer;
}

.protocol-card:hover {
  border-color: var(--mood-accent);
  box-shadow: 0 4px 12px var(--mood-shadow);
}

.protocol-card__header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 0.5rem;
}

.protocol-card__name {
  font-size: 0.9375rem;
  font-weight: 600;
  color: var(--mood-text);
}

.protocol-card__badges {
  display: flex;
  gap: 0.375rem;
  flex-shrink: 0;
}

.protocol-card__description {
  font-size: 0.8125rem;
  color: var(--mood-text-muted);
  line-height: 1.4;
}

.protocol-card__mode-params {
  padding-top: 0.25rem;
}

.protocol-card__formula {
  padding-top: 0.75rem;
  border-top: 1px solid var(--mood-border);
}

.protocol-card__formula-title {
  font-size: 0.6875rem;
  font-weight: 600;
  color: var(--mood-text-muted);
  text-transform: uppercase;
  letter-spacing: 0.04em;
  margin-bottom: 0.5rem;
}

.protocol-card__formula-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0.5rem;
  font-size: 0.75rem;
}

.protocol-card__formula-label {
  display: block;
  color: var(--mood-text-muted);
  font-size: 0.625rem;
}

.protocol-card__formula-value {
  font-weight: 600;
  color: var(--mood-text);
}

/* --- Formula table --- */
.formula-table-wrapper {
  background: var(--mood-surface);
  border: 1px solid var(--mood-border);
  border-radius: 0.75rem;
  overflow-x: auto;
}

.formula-table {
  width: 100%;
  font-size: 0.8125rem;
  border-collapse: collapse;
}

.formula-table th {
  text-align: left;
  padding: 0.75rem 1rem;
  font-weight: 600;
  font-size: 0.75rem;
  color: var(--mood-text-muted);
  border-bottom: 1px solid var(--mood-border);
}

.formula-table td {
  padding: 0.625rem 1rem;
  color: var(--mood-text-muted);
  border-bottom: 1px solid var(--mood-border);
}

.formula-table tr:last-child td {
  border-bottom: none;
}

.formula-table__name {
  font-weight: 600;
  color: var(--mood-text) !important;
}

.formula-table__date {
  font-size: 0.6875rem;
}

/* --- Formula explainer --- */
.formula-explainer-trigger {
  width: 100%;
  justify-content: space-between;
  background: var(--mood-surface);
  border: 1px solid var(--mood-border);
  border-radius: 0.75rem;
}

.formula-explainer-content {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  padding: 0 1.25rem 1.25rem;
  background: var(--mood-surface);
  border: 1px solid var(--mood-border);
  border-top: none;
  border-radius: 0 0 0.75rem 0.75rem;
}

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

.formula-explainer-params {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 0.375rem;
  font-size: 0.75rem;
  color: var(--mood-text-muted);
}

.formula-explainer-note {
  font-size: 0.8125rem;
  color: var(--mood-text-muted);
  line-height: 1.5;
  font-style: italic;
}
</style>
