<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 text-white 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="text-white/30 text-xs -mt-1 px-1">Pour recevoir une réponse, laissez votre e-mail dans le message.</p>
          <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="text-white/90 font-display text-lg font-semibold">Merci pour votre message !</p>
          <p class="text-white/55 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="text-primary/60 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 text-white/80 text-center">Derniers messages</h3>
        <div v-for="msg in messages.slice(0, 2)" :key="msg.id" class="message-card">
          <p class="text-white/80 text-sm leading-relaxed">{{ msg.text }}</p>
          <div class="mt-2 flex items-center gap-2 text-xs text-white/40">
            <span class="font-semibold text-white/60">{{ msg.author }}</span>
            <span>&middot;</span>
            <span>{{ formatDate(msg.createdAt) }}</span>
          </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: '' })
const sending = ref(false)
const submitted = ref(false)

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

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>
.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;
  transition: border-color 0.2s;
}

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

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

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