<script setup lang="ts">
const route = useRoute()
const config = useRuntimeConfig()
const apiBase = config.public.apiBase as string

const token = computed(() => String(route.params.token || ''))
const status = ref<'loading' | 'ready' | 'done' | 'error'>('loading')
const email = ref('')
const error = ref<string | null>(null)
const submitting = ref(false)

onMounted(async () => {
  try {
    const r = await $fetch<{ email: string }>(`/unsubscribe/${token.value}`, { baseURL: apiBase })
    email.value = r.email
    status.value = 'ready'
  } catch (e: any) {
    status.value = 'error'
    error.value = e?.data?.error || 'This link is invalid or has expired.'
  }
})

async function confirm() {
  submitting.value = true
  error.value = null
  try {
    await $fetch(`/unsubscribe/${token.value}`, { baseURL: apiBase, method: 'POST' })
    status.value = 'done'
  } catch (e: any) {
    error.value = e?.data?.error || 'Something went wrong — please try again.'
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <section class="mx-auto max-w-md py-12">
    <h1 class="mb-6 text-2xl font-semibold">Unsubscribe</h1>

    <div v-if="status === 'loading'" class="card text-sm text-zinc-400">Loading…</div>

    <div v-else-if="status === 'ready'" class="card space-y-4 text-sm">
      <p>You'll stop receiving GuestGuard emails sent to:</p>
      <p class="font-mono text-zinc-200">{{ email }}</p>
      <p class="text-zinc-400">
        This includes RSVPs, reminders, and host messages. Account-related emails
        (security, password resets) will still reach you.
      </p>
      <button class="btn-primary w-full" :disabled="submitting" @click="confirm">
        {{ submitting ? 'Unsubscribing…' : 'Unsubscribe me' }}
      </button>
      <p v-if="error" class="text-sm text-red-400">{{ error }}</p>
    </div>

    <div v-else-if="status === 'done'" class="card text-sm">
      <p class="mb-2 font-medium text-brand-300">Done.</p>
      <p class="text-zinc-400">
        We've added <span class="text-zinc-200">{{ email }}</span> to our suppression list.
        Future emails to that address will be silently dropped.
      </p>
    </div>

    <div v-else class="card text-sm">
      <p class="mb-2 font-medium text-red-400">Can't unsubscribe</p>
      <p class="text-zinc-400">{{ error }}</p>
    </div>
  </section>
</template>
