<template>
    <div class="event-form">
        <div v-if="success" class="success">
            <p>Thank you</p>
        </div>

        <form v-else @submit.prevent="onRsvpSubmit">
            <input v-model="name" type="text" placeholder="Name" required />
            <input
                v-model="email"
                type="email"
                placeholder="Email"
                required
                validate
            />
            <btn type="submit" :loading="loading" secondary>Submit</btn>
        </form>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import Btn from '@/components/Btn.vue'
import useKlaviyo from '@/composables/useKlaviyo'

const props = defineProps({
    eventName: String,
    eventDate: String,
})
const emit = defineEmits(['success'])

const { loading, success, error, subscribe, track } = useKlaviyo()

// Global "All RSVPs" list ID lives on the Events index doc
// const { data: eventsIndex } = await usePrisSingle('events')
// const allRsvpsListId = computed(
//     () => eventsIndex.value?.data?.all_rsvps_klaviyo_list_id,
// )
const allRsvpsListId = ''

const name = ref('')
const email = ref('')

const onRsvpSubmit = async () => {
    if (allRsvpsListId.value) {
        await subscribe({
            listId: allRsvpsListId.value,
            email: email.value,
            name: name.value,
            source: 'website_event_rsvp',
        })
    }

    // Append-only event for per-event segmentation in Klaviyo
    try {
        await track({
            email: email.value,
            metric: 'Submitted RSVP',
            properties: {
                event_name: props.eventName,
                event_date: props.eventDate,
            },
        })
    } catch (err) {
        console.error('Failed to track RSVP event', err)
    }
}

// Reset after success
watch(success, () => {
    if (success.value) {
        setTimeout(() => {
            emit('success')
            success.value = false
            name.value = ''
            email.value = ''
        }, 2000)
    }
})
</script>

<style lang="scss">
.event-form {
    width: desktop-vw(390px);
    height: 100%;

    .success {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        background: var(--theme-fg);
        color: var(--theme-bg);
        height: desktop-vw(78.5px);
    }

    input {
        background: var(--theme-fg);
        color: var(--theme-bg);
        display: block;
        width: 100%;
        border: solid var(--theme-bg);
        border-width: 1px 1px 0 1px;
        text-align: center;
    }
    .btn {
        width: 100%;
        border: 1px solid var(--theme-bg);
    }

    @include mobile {
        width: 100%;

        .success {
            height: mobile-vw(70px);
        }
    }
}
</style>
