<script setup lang="ts">
const toast = useToast()

const captchaToken = ref('')
const captchaSvg = ref('')

async function fetchCaptcha() {
  try {
    const res = await $fetch<{ code: number; data: { token: string; svg: string } }>(
      '/api/auth/captcha'
    )
    captchaToken.value = res.data.token
    captchaSvg.value = res.data.svg
  } catch {
    captchaSvg.value = ''
  }
}

function handleSuccess() {
  navigateTo('/login?registered=1')
}

function handleError(message: string) {
  toast.add({ title: message, color: 'error' })
}

onMounted(() => {
  fetchCaptcha()
})

useHead({ title: '注册' })
</script>

<template>
  <div class="flex items-center justify-center min-h-[calc(100vh-200px)] py-8">
    <UCard class="w-full max-w-[400px]">
      <template #header>
        <h1 class="text-xl font-semibold">创建账号</h1>
        <p class="text-sm text-(--ui-text-muted) mt-1">填写信息开始使用</p>
      </template>

      <RegisterForm
        :captcha-svg="captchaSvg"
        :captcha-token="captchaToken"
        @refresh-captcha="fetchCaptcha"
        @success="handleSuccess"
        @error="handleError"
      />

      <template #footer>
        <p class="text-sm text-center text-(--ui-text-muted)">
          已有账号？
          <NuxtLink to="/login" class="text-(--ui-primary) hover:underline">去登录</NuxtLink>
        </p>
      </template>
    </UCard>
  </div>
</template>
