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

	let token = $state('');
	let error = $state('');
	let loading = $state(false);

	async function handleLogin() {
		if (!token.trim()) {
			error = 'Please enter your API token';
			return;
		}

		loading = true;
		error = '';

		try {
			// Test the token
			const res = await fetch('/api/trips', {
				headers: { 'Authorization': `Bearer ${token.trim()}` }
			});

			if (res.ok) {
				localStorage.setItem('api_token', token.trim());
				goto('/');
			} else {
				error = 'Invalid API token';
			}
		} catch {
			error = 'Connection failed';
		} finally {
			loading = false;
		}
	}
</script>

<div class="min-h-[calc(100vh-4rem)] 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-4">
				<svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 mx-auto text-primary mb-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
					<path d="M3 7l6-3 6 3 6-3v13l-6 3-6-3-6 3V7z"/>
					<path d="M9 4v13"/>
					<path d="M15 7v13"/>
				</svg>
				<h2 class="text-2xl font-bold text-base-content">Trips</h2>
				<p class="text-base-content/50 text-sm mt-1">Enter your API token 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">
					<label class="label" for="token">
						<span class="label-text">API Token</span>
					</label>
					<input
						id="token"
						type="password"
						placeholder="Bearer token"
						class="input input-bordered w-full"
						bind:value={token}
					/>
				</div>
				<button
					type="submit"
					class="btn btn-primary w-full mt-4"
					disabled={loading}
				>
					{#if loading}
						<span class="loading loading-spinner loading-sm"></span>
					{/if}
					Connect
				</button>
			</form>
		</div>
	</div>
</div>
