<script setup lang="ts">
const { login, register, loginWithGoogle, loading, error } = useAuth()

const mode = ref<'login' | 'register'>('login')
const email = ref('')
const password = ref('')

async function onSubmit() {
  const success = mode.value === 'login'
    ? await login(email.value, password.value)
    : await register(email.value, password.value)

  if (success) {
    await navigateTo('/')
  }
}
</script>

<template>
  <div class="max-w-sm mx-auto space-y-6">
    <div class="text-center">
      <h1 class="text-2xl font-bold">
        {{ mode === 'login' ? 'Iniciar sesion' : 'Crear cuenta' }}
      </h1>
      <p class="text-sm text-muted mt-1">
        {{ mode === 'login' ? 'Accede a tu cuenta de Vuelato' : 'Registrate para guardar vuelos' }}
      </p>
    </div>

    <UButton
      label="Continuar con Google"
      icon="i-simple-icons-google"
      color="neutral"
      variant="outline"
      block
      @click="loginWithGoogle"
    />

    <USeparator label="o" />

    <form class="space-y-4" @submit.prevent="onSubmit">
      <UFormField label="Email">
        <UInput v-model="email" type="email" placeholder="tu@email.com" icon="i-lucide-mail" required />
      </UFormField>

      <UFormField label="Contrasena">
        <UInput v-model="password" type="password" placeholder="••••••••" icon="i-lucide-lock" required :minlength="6" />
      </UFormField>

      <UAlert v-if="error" color="error" :title="error" icon="i-lucide-alert-circle" />

      <UButton
        type="submit"
        :label="mode === 'login' ? 'Iniciar sesion' : 'Crear cuenta'"
        :loading="loading"
        block
      />
    </form>

    <p class="text-center text-sm">
      <template v-if="mode === 'login'">
        No tienes cuenta?
        <UButton variant="link" label="Registrate" @click="mode = 'register'" />
      </template>
      <template v-else>
        Ya tienes cuenta?
        <UButton variant="link" label="Inicia sesion" @click="mode = 'login'" />
      </template>
    </p>
  </div>
</template>
