<!-- app/pages/auth.vue -->

<script setup lang="ts">
/**
 * Combined Authentication Page
 *
 * Features:
 * - Tab navigation (Login / Register)
 * - Redirects logged-in users to homepage
 * - Stores intended destination for post-login redirect
 */

const route = useRoute()
const { loggedIn } = useAuth()

// Redirect if already logged in
if (loggedIn.value) {
  navigateTo('/')
}

// Active tab state
const activeTab = ref<'login' | 'register'>('login')

// Set tab from query param if present
onMounted(() => {
  if (route.query.tab === 'register') {
    activeTab.value = 'register'
  }
})

// Error message from OAuth callback
const errorMessage = computed(() => {
  if (route.query.error === 'login_failed') {
    return 'Login fehlgeschlagen. Bitte versuchen Sie es erneut.'
  }
  return null
})

// Set page meta
definePageMeta({
  layout: 'auth', // Optional: Use separate layout for auth pages
})
</script>

<template>
  <CommonHeader />

  <div class="container mx-auto max-w-lg px-4 py-12 sm:py-16">
    <div class="mb-10 text-center">
      <h1 class="text-4xl font-light tracking-tight">
        Willkommen
      </h1>
      <p class="mt-3 text-lg text-white/80">
        Melden Sie sich an oder erstellen Sie ein Konto
      </p>
    </div>

    <!-- Error Alert -->
    <Alert v-if="errorMessage" class="mb-6 border-destructive bg-destructive/10 text-white">
      <AlertCircle class="h-5 w-5 text-destructive" />
      <AlertTitle class="text-destructive">Fehler</AlertTitle>
      <AlertDescription class="text-white/90">{{ errorMessage }}</AlertDescription>
    </Alert>

    <!-- Tabs -->
    <Tabs v-model="activeTab" class="w-full">
      <TabsList class="mb-6 grid w-full grid-cols-2">
        <TabsTrigger value="login">
          Anmelden
        </TabsTrigger>
        <TabsTrigger value="register">
          Registrieren
        </TabsTrigger>
      </TabsList>

      <!-- Login Tab -->
      <TabsContent value="login">
        <Card class="p-6 sm:p-8">
          <CardHeader class="px-0 pt-0">
            <CardTitle class="text-2xl font-medium">Anmelden</CardTitle>
            <CardDescription class="text-white/70 mt-2">
              Melden Sie sich mit Ihrer E-Mail-Adresse an
            </CardDescription>
          </CardHeader>
          <CardContent class="px-0 pb-0">
            <AuthLoginForm />
          </CardContent>
        </Card>
      </TabsContent>

      <!-- Register Tab -->
      <TabsContent value="register">
        <Card class="p-6 sm:p-8">
          <CardHeader class="px-0 pt-0">
            <CardTitle class="text-2xl font-medium">Konto erstellen</CardTitle>
            <CardDescription class="text-white/70 mt-2">
              Erstellen Sie ein neues experimenta-Konto
            </CardDescription>
          </CardHeader>
          <CardContent class="px-0 pb-0">
            <AuthRegisterForm />
          </CardContent>
        </Card>
      </TabsContent>
    </Tabs>
  </div>

  <CommonFooter />
</template>
