<script setup lang="ts">
const { t } = useI18n()
const { user, fetchSession } = useAuth()
onMounted(() => {
  void fetchSession()
})
const loading = ref(false)
const toast = useToast()

const isUnverified = computed(() => Boolean(user.value && !user.value.emailVerified))

async function resendVerification() {
  if (loading.value || !user.value?.email) return

  loading.value = true
  try {
    // Better Auth will automatically resend verification when user signs up again
    // or we can call the sendVerificationEmail endpoint
    const apiCall = useApiCall()
    await apiCall('/api/auth/send-verification-email', {
      method: 'POST',
      body: {
        email: user.value.email
      }
    })

    toast.add({
      title: t('account.emailVerification.resentTitle'),
      description: t('account.emailVerification.resentDescription'),
      color: 'success'
    })
  } catch (error) {
    toast.add({
      title: t('account.emailVerification.resendFailed'),
      description: (error as Error).message,
      color: 'error'
    })
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div
    v-if="isUnverified"
    class="rounded-lg border border-warning-200 bg-warning-50 p-4 dark:border-warning-950 dark:bg-warning-950/20 mb-4"
  >
    <div class="flex items-start gap-3">
      <UIcon
        :name="useSolarIcon('mail-warning')"
        class="h-5 w-5 text-warning-600 dark:text-warning-400 flex-shrink-0 mt-0.5"
      />
      <div class="flex-1">
        <h3 class="font-medium text-warning-950 dark:text-warning-50">
          {{ t('account.emailVerification.title') }}
        </h3>
        <p class="mt-1 text-sm text-warning-900 dark:text-warning-100">
          {{ t('account.emailVerification.description', { email: user?.email }) }}
        </p>
        <UButton
          class="mt-3"
          color="warning"
          variant="soft"
          size="sm"
          :loading="loading"
          :disabled="loading"
          @click="resendVerification"
        >
          {{ t('account.emailVerification.resendButton') }}
        </UButton>
      </div>
    </div>
  </div>
</template>
