<template>
  <div class="verify-page">
    <div class="verify-box">
      <div v-if="state === 'verifying'" class="verify-status">
        <div class="section-label">Ghost Guild</div>
        <p>Verifying your login link&hellip;</p>
      </div>

      <div v-else-if="state === 'error'" class="verify-status">
        <div class="section-label">Login Failed</div>
        <p class="error-msg">{{ errorMessage }}</p>
        <NuxtLink to="/" class="btn btn-primary">Back to home</NuxtLink>
      </div>
    </div>
  </div>
</template>

<script setup>
definePageMeta({ layout: false })

const state = ref('verifying')
const errorMessage = ref('')

onMounted(async () => {
  const hash = window.location.hash.slice(1)

  if (!hash) {
    state.value = 'error'
    errorMessage.value = 'No login token found. Please request a new login link.'
    return
  }

  try {
    const data = await $fetch('/api/auth/verify', {
      method: 'POST',
      body: { token: hash },
    })

    await navigateTo(data.redirectUrl, { replace: true })
  } catch (err) {
    state.value = 'error'
    const status = err?.response?.status
    if (status === 401) {
      errorMessage.value = 'This login link is invalid or has expired. Please request a new one.'
    } else if (status === 403) {
      errorMessage.value = err?.data?.statusMessage || 'Your account is not active. Please contact support.'
    } else {
      errorMessage.value = 'Something went wrong. Please try again or request a new login link.'
    }
  }
})
</script>

<style scoped>
.verify-page {
  min-height: 100vh;
  background: var(--bg);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
}

.verify-box {
  border: 1px dashed var(--border);
  padding: 2rem 2.5rem;
  max-width: 420px;
  width: 100%;
}

.verify-status {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.error-msg {
  color: var(--ember);
}
</style>
