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

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 ?? 'Sign-in failed. Check your email and password.'
}

async function submit() {
  busy.value = true
  error.value = ''
  try {
    await auth.signIn(email.value, password.value)
    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 })
  } 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="ACCOUNT ACCESS" title="WELCOME BACK." subtitle="Sign in to continue your private worlds and shared campaigns.">
    <form class="auth-form" @submit.prevent="submit">
      <label>EMAIL<input v-model="email" name="email" type="email" autocomplete="email" required placeholder="you@example.com"></label>
      <label><span class="field-row"><span>PASSWORD</span><NuxtLink to="/auth/forgot-password">FORGOT?</NuxtLink></span><input v-model="password" name="password" type="password" autocomplete="current-password" required placeholder="Your password"></label>
      <p v-if="error" class="form-error" role="alert">{{ error }}</p>
      <button :disabled="busy">{{ busy ? 'SIGNING IN…' : 'SIGN IN →' }}</button>
    </form>
    <template #footer>New to D&G? <NuxtLink class="form-link" to="/auth/sign-up">CREATE ACCOUNT</NuxtLink></template>
  </AuthCard>
</template>
