<script lang="ts">
	import { authStore } from '$lib/stores/auth.svelte.js';
	import { goto } from '$app/navigation';
	import { LogIn, User, Lock, ArrowRight } from 'lucide-svelte';

	let username = $state('');
	let password = $state('');
	let isLoading = $state(false);

	async function handleSubmit(e: Event) {
		e.preventDefault();

		if (!username || !password) {
			authStore.error = 'Bitte alle Felder ausfüllen';
			return;
		}

		isLoading = true;
		await authStore.login(username, password);
		isLoading = false;
	}
</script>

<div class="login-container">
	<div class="card login-card">
		<h1>Anmelden</h1>
		<p class="subtitle">Willkommen im Smarten Klassenzimmer</p>

		{#if authStore.error}
			<div class="alert alert-error">
				<div class="alert-content">
					{authStore.error}
				</div>
				<button onclick={() => authStore.clearError()} class="btn-ghost" style="padding: 0; min-height: auto; width: auto;">×</button>
			</div>
		{/if}

		<form onsubmit={handleSubmit}>
			<div class="form-group">
				<label for="username" class="form-label">Benutzername</label>
				<input
					type="text"
					id="username"
					class="form-input"
					bind:value={username}
					placeholder="Benutzername eingeben"
					disabled={isLoading}
					required
				/>
			</div>

			<div class="form-group">
				<label for="password" class="form-label">Passwort</label>
				<input
					type="password"
					id="password"
					class="form-input"
					bind:value={password}
					placeholder="Passwort eingeben"
					disabled={isLoading}
					required
				/>
			</div>

			<button type="submit" class="btn btn-primary btn-block" disabled={isLoading}>
				{#if isLoading}
					<span class="loading-spinner" style="width: 1rem; height: 1rem; border-width: 2px;"></span>
				{/if}
				{isLoading ? 'Anmeldung läuft...' : 'Anmelden'}
			</button>
		</form>

		<p class="forgot-password-link text-center text-sm mt-md">
			<a href="/forgot-password">Passwort vergessen?</a>
		</p>

		<p class="register-link text-center text-sm mt-sm">
			Noch kein Konto? <a href="/register">Hier registrieren</a>
		</p>
	</div>
</div>

<style>
	.login-container {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 100vh;
		background: var(--neutral-50);
		padding: var(--space-md);
	}

	.login-card {
		width: 100%;
		max-width: 400px;
		/* Card styles come from global css */
	}

	h1 {
		margin: 0 0 var(--space-xs);
		font-family: var(--font-heading);
		font-size: var(--text-2xl);
		text-align: center;
	}

	.subtitle {
		color: var(--neutral-500);
		text-align: center;
		margin: 0 0 var(--space-xl);
	}
</style>
