<script setup lang="ts">
const auth = useAuth()
const route = useRoute()

const email = ref('')
const password = ref('')
const submitting = ref(false)
const error = ref<string | null>(null)

async function submit() {
  error.value = null
  submitting.value = true
  try {
    await auth.login(email.value, password.value)
    const redirect = (route.query.redirect as string) || '/dashboard'
    await navigateTo(redirect)
  } catch (e: any) {
    error.value = useErrMessage(e, 'Login failed')
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <section class="mx-auto max-w-md py-12">
    <h1 class="mb-2 text-2xl font-semibold">Sign in</h1>
    <p class="mb-6 text-sm text-zinc-400">Welcome back. Sign in to manage your events.</p>

    <form class="card space-y-4" @submit.prevent="submit">
      <div>
        <label class="label">Email</label>
        <input v-model="email" type="email" class="input" autocomplete="email" required />
      </div>
      <div>
        <label class="label">Password</label>
        <input v-model="password" type="password" class="input" autocomplete="current-password" required />
        <div class="mt-1 text-right text-xs">
          <NuxtLink to="/forgot-password" class="text-zinc-400 hover:text-zinc-200">Forgot password?</NuxtLink>
        </div>
      </div>
      <button class="btn-primary w-full" :disabled="submitting || !email || !password">
        {{ submitting ? 'Signing in…' : 'Sign in' }}
      </button>
      <p v-if="error" class="text-sm text-red-400">{{ error }}</p>
    </form>

    <p class="mt-6 text-center text-sm text-zinc-400">
      Don't have an account?
      <NuxtLink to="/signup" class="text-brand-400 hover:text-brand-300">Sign up</NuxtLink>
    </p>
  </section>
</template>
