<script lang="ts">
	import { goto } from '$app/navigation';

	let username = $state('');
	let password = $state('');
	let error = $state('');
	let loading = $state(false);

	async function handleLogin() {
		if (!username.trim() || !password) { error = 'Enter username and password'; return; }
		loading = true;
		error = '';
		try {
			const res = await fetch('/api/auth/login', {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ username: username.trim(), password }),
				credentials: 'include'
			});
			if (res.ok) {
				const data = await res.json();
				localStorage.setItem('session_token', data.token);
				goto('/');
			} else { error = 'Invalid credentials'; }
		} catch { error = 'Connection failed'; }
		finally { loading = false; }
	}
</script>

<div class="min-h-screen flex items-center justify-center px-4">
	<div class="card bg-base-200 shadow-xl w-full max-w-md border border-base-300">
		<div class="card-body">
			<div class="text-center mb-6">
				<div class="p-4 rounded-2xl bg-primary/15 inline-block mb-3">
					<svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<path d="M12 20V10"/>
						<path d="M18 20V4"/>
						<path d="M6 20v-4"/>
					</svg>
				</div>
				<h2 class="text-2xl font-bold text-base-content">Calorie Tracker</h2>
				<p class="text-base-content/50 text-sm mt-1">Sign in to continue</p>
			</div>

			{#if error}
				<div class="alert alert-error text-sm py-2"><span>{error}</span></div>
			{/if}

			<form onsubmit={(e) => { e.preventDefault(); handleLogin(); }}>
				<div class="form-control">
					<div class="text-xs text-base-content/50 font-medium uppercase tracking-wide mb-1">Username</div>
					<input type="text" class="input input-bordered w-full" bind:value={username} />
				</div>
				<div class="form-control mt-3">
					<div class="text-xs text-base-content/50 font-medium uppercase tracking-wide mb-1">Password</div>
					<input type="password" class="input input-bordered w-full" bind:value={password} />
				</div>
				<button type="submit" class="btn btn-primary w-full mt-5 gap-2" disabled={loading}>
					{#if loading}<span class="loading loading-spinner loading-sm"></span>{/if}
					Sign In
				</button>
			</form>
		</div>
	</div>
</div>
