<template>
  <!-- 🌌 Latar belakang fullscreen -->
  <section
    class="relative min-h-screen w-full flex flex-col items-center justify-center text-center overflow-hidden bg-gradient-to-br from-indigo-900 via-purple-900 to-blue-900 text-white p-6">
    <!-- 🌟 Bintang Berkedip -->
    <div class="absolute inset-0 overflow-hidden z-0">
      <div v-for="(star, i) in stars" :key="i" class="absolute bg-white rounded-full animate-twinkle" :style="{
        top: star.top + '%',
        left: star.left + '%',
        width: star.size + 'px',
        height: star.size + 'px',
        animationDelay: star.delay + 's',
        opacity: star.opacity
      }"></div>
    </div>

    <!-- 🌈 Cahaya lembut -->
    <div
      class="absolute w-[600px] h-[600px] bg-blue-400/10 blur-[200px] rounded-full top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
    </div>

    <!-- 💬 Konten utama -->
    <div class="relative z-10 max-w-lg w-full space-y-6 animate-fade-in">
      <h2 class="text-4xl font-extrabold text-yellow-300 drop-shadow-[0_0_20px_rgba(255,255,255,0.3)]">
        💬 Buku Tamu
      </h2>

      <p class="text-blue-100">{{ saySomething }}</p>

      <!-- 📝 Form -->
      <form @submit.prevent="submitMessage"
        class="bg-white/10 backdrop-blur-md border border-white/20 p-6 rounded-2xl shadow-lg space-y-4">
        <input v-model="form.name" type="text" placeholder="Nama Anda"
          class="w-full px-4 py-2 rounded-lg bg-white/20 text-white placeholder-gray-300 focus:ring-2 focus:ring-yellow-400 outline-none"
          required />
        <textarea v-model="form.message" rows="3" placeholder="Tulis ucapan Anda..."
          class="w-full px-4 py-2 rounded-lg bg-white/20 text-white placeholder-gray-300 focus:ring-2 focus:ring-yellow-400 outline-none"
          required></textarea>

        <select v-model="form.attendance" class="w-full px-4 py-3 rounded-xl border-2 border-orange-400 
         focus:ring-2 focus:ring-orange-500 focus:border-orange-500 
         bg-gradient-to-r from-yellow-50 to-orange-50 text-gray-800 
         appearance-none transition-all duration-300 cursor-pointer">
          <option value="hadir" class="bg-white text-gray-800">✅ Hadir</option>
          <option value="tidak_hadir" class="bg-white text-gray-800">❌ Tidak Hadir</option>
          <option value="mungkin" class="bg-white text-gray-800">🤔 Mungkin</option>
        </select>


        <button type="submit"
          class="bg-yellow-400 text-gray-900 font-semibold px-6 py-2.5 rounded-full shadow-lg hover:bg-yellow-500 transition-all duration-300 transform hover:scale-105">
          Kirim ✨
        </button>
      </form>

      <!-- 💌 Pesan -->
      <div v-if="messages.length" class="mt-10 space-y-4 text-left max-h-[300px] overflow-y-auto">
        <transition-group name="fade" tag="div">
          <div class="space-y-4">
            <div v-for="msg in messages" :key="msg.id" class="bg-white rounded-xl shadow-md p-4 text-left">
              <div class="flex items-center justify-between mb-2">
                <span class="font-bold text-orange-800">{{ msg.nama }}</span>
                <span :class="getAttendanceClass(msg.status_kehadiran)" class="text-sm px-2 py-1 rounded-lg">
                  {{ formatAttendance(msg.status_kehadiran) }}
                </span>
              </div>
              <p class="text-gray-700">{{ msg.pesan }}</p>
            </div>
          </div>
        </transition-group>
      </div>
    </div>

    <!-- 🌠 Ornamen bawah -->
    <div
      class="absolute bottom-0 left-0 right-0 h-[200px] bg-gradient-to-t from-indigo-900 via-purple-800/30 to-transparent">
    </div>
  </section>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRuntimeConfig } from '#app';

const route = useRoute();
const config = useRuntimeConfig();
const backendUrl = config.public.apiBaseUrl;
const invitationCode = route.params.code || '';
const guest = route.query.code

const props = defineProps({
  messages: {
    type: Array,
    required: false,
    default: () => []
  }
})

const messages = ref([...props.messages])

const form = ref({ name: '', message: '', attendance: 'hadir' });

onMounted(() => {
  messages.value = props.messages || []
})

// Fungsi untuk mengirim data RSVP ke backend
const submitMessage = async () => {
  if (!form.value.name || !form.value.message) {
    alert('Nama dan ucapan harus diisi!');
    return;
  }

  try {
    console.log('POST to:', `${backendUrl}/api/rsvp/${invitationCode}`, {
      nama: form.value.name,
      pesan: form.value.message,
      status_kehadiran: form.value.attendance,
    });
    const response = await fetch(`${backendUrl}/api/rsvp/${invitationCode}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        nama: form.value.name,
        pesan: form.value.message,
        status_kehadiran: form.value.attendance,
      }),
    });

    if (!response.ok) {
      throw new Error(`Gagal menyimpan RSVP`);
    }

    const result = await response.json();
    messages.value.push(result.data);
    form.value = { name: '', message: '', attendance: 'hadir' };
    alert(result.message);
  } catch (error) {
    console.error('Error menyimpan RSVP:', error);
    alert('Terjadi kesalahan saat menyimpan RSVP.');
  }
};

// Fungsi untuk mengatur kelas CSS berdasarkan status kehadiran
const getAttendanceClass = (attendance) => {
  switch (attendance) {
    case 'hadir':
      return 'bg-green-100 text-green-700';
    case 'tidak_hadir':
      return 'bg-red-100 text-red-700';
    case 'mungkin':
      return 'bg-yellow-100 text-yellow-700';
    default:
      return 'bg-gray-100 text-gray-700';
  }
};

// Fungsi untuk memformat teks kehadiran
const formatAttendance = (attendance) => {
  switch (attendance) {
    case 'hadir':
      return 'Hadir';
    case 'tidak_hadir':
      return 'Tidak Hadir';
    case 'mungkin':
      return 'Mungkin';
    default:
      return attendance;
  }
};
</script>

<style scoped>
/* 🌟 Animasi bintang berkedip */
@keyframes twinkle {

  0%,
  100% {
    opacity: 0.3;
    transform: scale(1);
  }

  50% {
    opacity: 1;
    transform: scale(1.3);
  }
}

.animate-twinkle {
  animation: twinkle 3.5s ease-in-out infinite;
}

/* ✨ Fade animasi */
@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in {
  animation: fade-in 1.2s ease-out;
}

/* Pesan baru fade */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.4s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* Scrollbar halus */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 9999px;
}
</style>