<script setup lang="ts">
const auth = useDngAuth()
const displayName = ref('')
const email = ref('')
const password = ref('')
const confirmation = ref('')
const ageConfirmed = ref(false)
const busy = ref(false)
const error = ref('')
const confirmationSent = ref(false)

function messageFrom(cause: unknown) {
  const value = cause as { data?: { msg?: string; message?: string; error_description?: string }; message?: string }
  return value.data?.msg ?? value.data?.message ?? value.data?.error_description ?? value.message ?? 'Registration failed. Try again.'
}

async function finishSignIn() {
  const requested = localStorage.getItem('dng-post-auth-redirect')
  localStorage.removeItem('dng-post-auth-redirect')
  const destination = requested?.startsWith('/') && !requested.startsWith('//') ? requested : '/dashboard'
  await navigateTo(destination, { replace: true })
}

async function submit() {
  error.value = ''
  if (displayName.value.trim().length < 2) {
    error.value = 'Enter a name with at least 2 characters.'
    return
  }
  if (password.value.length < 8) {
    error.value = 'Password must contain at least 8 characters.'
    return
  }
  if (password.value !== confirmation.value) {
    error.value = 'Passwords do not match.'
    return
  }
  if (!ageConfirmed.value) {
    error.value = 'You must confirm that you are at least 13 years old.'
    return
  }
  busy.value = true
  try {
    const result = await auth.signUp(displayName.value, email.value, password.value)
    if (result.session) await finishSignIn()
    else confirmationSent.value = true
  } catch (cause) {
    error.value = messageFrom(cause)
  } finally {
    busy.value = false
  }
}

onMounted(async () => {
  await auth.restore()
  if (auth.session.value) await navigateTo('/dashboard', { replace: true })
})
</script>

<template>
  <AuthCard eyebrow="CREATE YOUR ACCOUNT" title="ENTER THE ALPHA." subtitle="Your email keeps your worlds, characters, and campaign access recoverable across devices.">
    <div v-if="confirmationSent" class="form-success" role="status">
      CHECK YOUR EMAIL. We sent a confirmation link to {{ email }}. Open it to activate your account.
    </div>
    <form v-else class="auth-form" @submit.prevent="submit">
      <label>DISPLAY NAME<input v-model="displayName" name="name" autocomplete="name" maxlength="80" required placeholder="How your party sees you"></label>
      <label>EMAIL<input v-model="email" name="email" type="email" autocomplete="email" required placeholder="you@example.com"></label>
      <label>PASSWORD<input v-model="password" name="password" type="password" autocomplete="new-password" minlength="8" required placeholder="At least 8 characters"></label>
      <label>CONFIRM PASSWORD<input v-model="confirmation" name="password-confirmation" type="password" autocomplete="new-password" minlength="8" required placeholder="Repeat your password"></label>
      <label class="consent"><input v-model="ageConfirmed" type="checkbox" required><span>I am at least 13 years old and accept the 13+ content boundary.</span></label>
      <p v-if="error" class="form-error" role="alert">{{ error }}</p>
      <button :disabled="busy">{{ busy ? 'CREATING ACCOUNT…' : 'CREATE ACCOUNT →' }}</button>
    </form>
    <template #footer>Already have an account? <NuxtLink class="form-link" to="/auth/sign-in">SIGN IN</NuxtLink></template>
  </AuthCard>
</template>

<style scoped>
.consent{grid-template-columns:18px 1fr!important;align-items:start!important;font:400 10px/1.5 var(--body)!important;letter-spacing:0!important;color:var(--muted)!important}.consent input{width:16px!important;min-height:16px!important;margin:1px 0 0;padding:0!important;accent-color:var(--acid)}
</style>
