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

onMounted(async () => {
  try {
    const session = await auth.restore()
    if (!session) throw new Error('This recovery link is invalid or expired.')
    ready.value = true
  } catch (cause) {
    error.value = cause instanceof Error ? cause.message : 'Could not verify the recovery link.'
  }
})

async function submit() {
  error.value = ''
  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
  }
  busy.value = true
  try {
    await auth.updatePassword(password.value)
    await navigateTo('/dashboard', { replace: true })
  } catch (cause) {
    const value = cause as { data?: { msg?: string; message?: string }; message?: string }
    error.value = value.data?.msg ?? value.data?.message ?? value.message ?? 'Could not update the password.'
  } finally {
    busy.value = false
  }
}
</script>

<template>
  <AuthCard eyebrow="SECURE RECOVERY" title="CHOOSE A NEW PASSWORD." subtitle="Set a new password for your Dungeons & Ground account.">
    <p v-if="!ready && !error" class="form-success">VERIFYING RECOVERY LINK…</p>
    <form v-if="ready" class="auth-form" @submit.prevent="submit">
      <label>NEW 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>
      <p v-if="error" class="form-error" role="alert">{{ error }}</p>
      <button :disabled="busy">{{ busy ? 'UPDATING…' : 'UPDATE PASSWORD →' }}</button>
    </form>
    <p v-else-if="error" class="form-error" role="alert">{{ error }}</p>
    <template #footer><NuxtLink class="form-link" to="/auth/sign-in">BACK TO SIGN IN</NuxtLink></template>
  </AuthCard>
</template>
