<!-- src/routes/admin/+page.svelte -->
<script lang="ts">
  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';
  import LoginForm from '$lib/components/LoginForm.svelte';
  import AdminNavigation from '$lib/components/AdminNavigation.svelte';
  
  let isAuthenticated = false;
  let isLoading = true;

  onMount(async () => {
    // Prüfe ob bereits eingeloggt
    try {
      const res = await fetch('/api/admin/check-auth');
      isAuthenticated = res.ok;
    } catch (error) {
      console.error('Auth check failed:', error);
      isAuthenticated = false;
    }
    isLoading = false;
  });

  async function handleLogin(event: CustomEvent<{success: boolean}>) {
    if (event.detail.success) {
      isAuthenticated = true;
    }
  }

  async function handleLogout() {
    try {
      await fetch('/api/admin/logout', { method: 'POST' });
      isAuthenticated = false;
      goto('/admin');
    } catch (error) {
      console.error('Logout failed:', error);
    }
  }
</script>

<div class="min-h-screen bg-gray-50 py-8">
  <div class="max-w-2xl mx-auto px-4">
    {#if isLoading}
      <div class="flex justify-center items-center h-64">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
      </div>
    {:else if !isAuthenticated}
      <div class="bg-white rounded-lg shadow-md p-6">
        <h1 class="text-3xl font-bold text-gray-900 mb-6 text-center">Admin Login</h1>
        <LoginForm on:loginResult={handleLogin} />
      </div>
    {:else}
      <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex justify-between items-center mb-6">
          <h1 class="text-3xl font-bold text-gray-900">Admin-Bereich</h1>
          <button
            on:click={handleLogout}
            class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md transition-colors"
          >
            Logout
          </button>
        </div>
        
        <AdminNavigation />
      </div>
    {/if}
  </div>
</div>