<!-- src/lib/components/LoginForm.svelte -->
<script lang="ts">
  import { createEventDispatcher } from 'svelte';
  
  const dispatch = createEventDispatcher<{
    loginResult: { success: boolean; error?: string };
  }>();

  let password = '';
  let isLoading = false;
  let error = '';

  async function handleSubmit() {
    if (!password.trim()) {
      error = 'Bitte Passwort eingeben';
      return;
    }

    isLoading = true;
    error = '';

    try {
      const res = await fetch('/api/admin/login', {
        method: 'POST',
        body: JSON.stringify({ passwort: password }),
        headers: { 'Content-Type': 'application/json' }
      });

      if (res.ok) {
        dispatch('loginResult', { success: true });
      } else {
        const data = await res.json().catch(() => ({}));
        error = data.message || 'Falsches Passwort';
        dispatch('loginResult', { success: false, error });
      }
    } catch (err) {
      error = 'Verbindungsfehler. Bitte versuchen Sie es erneut.';
      dispatch('loginResult', { success: false, error });
    } finally {
      isLoading = false;
    }
  }

  function handleKeydown(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      handleSubmit();
    }
  }
</script>

<form on:submit|preventDefault={handleSubmit} class="space-y-4">
  <div>
    <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
      Passwort
    </label>
    <input
      id="password"
      type="password"
      bind:value={password}
      on:keydown={handleKeydown}
      placeholder="Admin-Passwort eingeben"
      disabled={isLoading}
      class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100"
      required
    />
  </div>

  {#if error}
    <div class="bg-red-50 border border-red-200 rounded-md p-3">
      <p class="text-sm text-red-800">{error}</p>
    </div>
  {/if}

  <button
    type="submit"
    disabled={isLoading || !password.trim()}
    class="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white font-medium py-2 px-4 rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
  >
    {#if isLoading}
      <span class="flex items-center justify-center">
        <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
        </svg>
        Wird eingeloggt...
      </span>
    {:else}
      Anmelden
    {/if}
  </button>
</form>
