<template>
  <div class="min-h-full py-16 bg-gray-50">
    <div class="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="bg-white rounded-xl shadow-lg p-8 text-center">
        <div v-if="loading" class="py-12">
          <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-6">
            <svg class="w-8 h-8 text-blue-600 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
          </div>
          <p class="text-lg text-gray-600">Newsletter-Anmeldung wird bestätigt...</p>
        </div>

        <div v-else-if="error" class="py-12">
          <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-6">
            <svg class="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </div>
          <h1 class="text-3xl font-display font-bold text-gray-900 mb-4">
            Fehler
          </h1>
          <p class="text-lg text-gray-600 mb-8">
            {{ error }}
          </p>
          <NuxtLink
            to="/newsletter/subscribe"
            class="inline-block px-6 py-3 bg-primary-600 text-white font-semibold rounded-lg hover:bg-primary-700 transition-colors"
          >
            Zurück zur Anmeldung
          </NuxtLink>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

useHead({
  title: 'Newsletter bestätigen - Harheimer TC',
})

const route = useRoute()
const loading = ref(true)
const error = ref('')

onMounted(async () => {
  const token = route.query.token

  if (!token) {
    error.value = 'Bestätigungstoken fehlt'
    loading.value = false
    return
  }

  try {
    // Rufe den API-Endpoint auf, der die Bestätigung durchführt
    const response = await $fetch(`/api/newsletter/confirm?token=${token}`)
    
    // Wenn erfolgreich, weiterleiten zur Bestätigungsseite
    if (response.alreadyConfirmed) {
      await navigateTo('/newsletter/confirmed?already=true')
    } else {
      await navigateTo('/newsletter/confirmed')
    }
  } catch (err) {
    console.error('Fehler bei Newsletter-Bestätigung:', err)
    error.value = err.data?.statusMessage || err.message || 'Fehler bei der Newsletter-Bestätigung'
    loading.value = false
  }
})
</script>

