<template>
  <section class="section-padding">
    <div class="container-content mx-auto max-w-3xl">

    <!-- Formulaire -->
    <UiScrollReveal>
      <div class="message-form-card">
        <h3 class="font-display text-lg font-bold form-title mb-4">Laisser un message</h3>

        <form v-if="!submitted" class="space-y-3" @submit.prevent="send">
          <input
            v-model="form.author"
            type="text"
            placeholder="Votre nom"
            class="msg-input"
          />
          <p class="hint-text text-xs -mt-1 px-1">Pour recevoir une réponse, laissez votre e-mail dans le message.</p>
          <select v-model="form.type" class="msg-input msg-input--select">
            <option value="question">Question</option>
            <option value="suggestion">Suggestion</option>
            <option value="retour">Retour d'expérience</option>
          </select>
          <textarea
            v-model="form.text"
            placeholder="Votre message"
            rows="3"
            class="msg-input resize-none"
          />
          <div class="flex justify-end">
            <button type="submit" class="btn-primary text-sm" :disabled="sending || !canSend">
              <div v-if="sending" class="i-lucide-loader-2 h-4 w-4 animate-spin mr-2" />
              Envoyer
            </button>
          </div>
        </form>

        <div v-else class="text-center py-6">
          <div class="i-lucide-heart-handshake h-10 w-10 text-primary mx-auto mb-3" />
          <p class="msg-confirm-title font-display text-lg font-semibold">Merci pour votre message !</p>
          <p class="msg-confirm-sub text-sm mt-2 max-w-md mx-auto leading-relaxed">
            Il sera lu et traité dans un délai... humainement raisonnable.
          </p>
          <p class="msg-confirm-note text-xs mt-4 italic">
            Chaque message est un premier pas dans l'aventure.
          </p>
        </div>
      </div>
    </UiScrollReveal>

    <!-- 2 derniers messages publiés -->
    <UiScrollReveal v-if="messages?.length" :delay="100">
      <div class="mt-8 space-y-4">
        <h3 class="font-display text-lg font-bold section-title text-center">Derniers messages</h3>
        <div v-for="msg in messages.slice(0, 2)" :key="msg.id" class="message-card">
          <!-- En-tête auteur -->
          <div class="flex items-center gap-2 mb-2">
            <span class="msg-author font-semibold text-sm">{{ msg.author }}</span>
            <span class="type-pill">{{ typeLabel(msg.type) }}</span>
            <span class="msg-date text-xs ml-auto">{{ formatDate(msg.createdAt) }}</span>
          </div>
          <!-- Texte du message -->
          <p class="msg-text text-sm leading-relaxed">{{ msg.text }}</p>
          <!-- Réponse -->
          <div v-if="msg.reply?.text" class="reply-thread">
            <div class="reply-connector" aria-hidden="true" />
            <div class="reply-block">
              <div class="flex items-center gap-1.5 mb-1">
                <div class="i-lucide-corner-down-right h-3 w-3 reply-icon" />
                <span class="reply-author text-xs font-semibold">Le Librodrome</span>
              </div>
              <p class="reply-text text-sm leading-relaxed italic">{{ msg.reply.text }}</p>
            </div>
          </div>
        </div>
        <div class="text-center">
          <NuxtLink to="/messages" class="btn-ghost text-sm">
            Voir tous les messages
            <div class="i-lucide-arrow-right ml-1 h-3.5 w-3.5" />
          </NuxtLink>
        </div>
      </div>
    </UiScrollReveal>
    </div>
  </section>
</template>

<script setup lang="ts">
const { data: messages } = await useFetch('/api/messages')

const form = reactive({ author: '', text: '', type: 'question' })
const sending = ref(false)
const submitted = ref(false)

const canSend = computed(() => form.text.trim().length > 0)

const TYPE_LABELS: Record<string, string> = {
  reaction: 'Réaction',
  question: 'Question',
  suggestion: 'Suggestion',
  retour: 'Retour',
}

function typeLabel(type: string) {
  return TYPE_LABELS[type] ?? type
}

async function send() {
  if (!canSend.value) return
  sending.value = true
  try {
    await $fetch('/api/messages', { method: 'POST', body: form })
    submitted.value = true
  }
  catch {
    alert('Erreur lors de l\'envoi du message.')
  }
  finally {
    sending.value = false
  }
}

function formatDate(iso: string) {
  const date = new Date(iso)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)

  if (minutes < 1) return 'à l\'instant'
  if (minutes < 60) return `il y a ${minutes} min`
  if (hours < 24) return `il y a ${hours}h`
  if (days < 30) return `il y a ${days}j`
  return date.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' })
}
</script>

<style scoped>
/* ── Couleurs adaptatives (dark + light) ── */
.form-title       { color: hsl(var(--color-text)); }
.hint-text        { color: hsl(var(--color-text) / 0.35); }
.section-title    { color: hsl(var(--color-text) / 0.85); }
.msg-author       { color: hsl(var(--color-text) / 0.75); }
.msg-date         { color: hsl(var(--color-text) / 0.38); }
.msg-text         { color: hsl(var(--color-text) / 0.78); white-space: pre-line; }
.msg-confirm-title { color: hsl(var(--color-text) / 0.95); }
.msg-confirm-sub  { color: hsl(var(--color-text) / 0.6); }
.msg-confirm-note { color: hsl(var(--color-primary) / 0.65); }
.reply-icon       { color: hsl(var(--color-primary) / 0.5); }
.reply-author     { color: hsl(var(--color-primary) / 0.8); }
.reply-text       { color: hsl(var(--color-text) / 0.62); }

/* ── Carte formulaire ── */
.message-form-card {
  background: hsl(var(--color-surface));
  border: 1px solid hsl(var(--color-text) / 0.1);
  border-radius: 0.75rem;
  padding: 1.5rem;
}

.msg-input {
  width: 100%;
  padding: 0.5rem 0.75rem;
  border-radius: 0.5rem;
  border: 1px solid hsl(var(--color-text) / 0.12);
  background: hsl(var(--color-bg));
  color: hsl(var(--color-text));
  font-size: 0.875rem;
  font-family: inherit;
  transition: border-color 0.2s;
}

.msg-input--select {
  width: auto;
  cursor: pointer;
}

.msg-input::placeholder {
  color: hsl(var(--color-text) / 0.35);
}

.msg-input:focus {
  outline: none;
  border-color: hsl(var(--color-primary) / 0.5);
}

/* ── Carte message ── */
.message-card {
  background: hsl(var(--color-surface));
  border: 1px solid hsl(var(--color-text) / 0.1);
  border-radius: 0.75rem;
  padding: 1rem 1.25rem;
}

.type-pill {
  font-size: 0.6rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  padding: 0.1rem 0.45rem;
  border-radius: 9999px;
  background: hsl(var(--color-primary) / 0.1);
  color: hsl(var(--color-primary) / 0.7);
}

/* ── Réponse avec liaison graphique ── */
.reply-thread {
  position: relative;
  display: flex;
  gap: 0;
  margin-top: 0.75rem;
  padding-left: 1.25rem;
}

.reply-connector {
  position: absolute;
  left: 0.5rem;
  top: -0.5rem;
  bottom: 0.5rem;
  width: 2px;
  background: linear-gradient(
    to bottom,
    hsl(var(--color-primary) / 0.35),
    hsl(var(--color-primary) / 0.15)
  );
  border-radius: 2px;
}

.reply-block {
  flex: 1;
  background: hsl(var(--color-primary) / 0.05);
  border-left: 2px solid hsl(var(--color-primary) / 0.25);
  border-radius: 0 0.5rem 0.5rem 0;
  padding: 0.6rem 0.875rem;
}
</style>
