<script lang="ts">
	import { auth } from '$lib/stores/auth.svelte';
	import { TreePine } from 'lucide-svelte';
	import { getStats, loginWithCookie } from '$lib/api/admin';
	import { toast } from '$lib/stores/toast.svelte';

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

	async function handleLogin() {
		if (!token.trim()) return;
		loading = true;
		error = '';
		try {
			await loginWithCookie(token.trim());
			await getStats(); // Validate cookie session
			auth.loginCookieSession();
			toast.success('Authenticated');
		} catch (e: any) {
			auth.logout();
			error = 'Invalid token';
		} finally {
			loading = false;
		}
	}

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

<div class="login-screen">
	<div class="login-card">
		<div class="login-logo">
			<TreePine size={32} strokeWidth={2} />
		</div>
		<h1>TREEHOUSE</h1>
		<p class="subtitle">Mission Control</p>

		<div class="login-form">
			<input
				type="password"
				placeholder="Auth token"
				bind:value={token}
				onkeydown={handleKeydown}
			/>
			{#if error}
				<p class="error">{error}</p>
			{/if}
			<button class="login-btn" onclick={handleLogin} disabled={loading || !token.trim()}>
				{loading ? 'Verifying...' : 'Authenticate'}
			</button>
		</div>
	</div>
</div>

<style>
	.login-screen {
		min-height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
		background: var(--bg);
	}
	.login-card {
		background: var(--surface-1);
		border: 1px solid var(--border);
		border-radius: var(--radius-lg);
		padding: 40px;
		width: 360px;
		text-align: center;
	}
	.login-logo {
		color: var(--accent);
		margin-bottom: 16px;
	}
	h1 {
		font-size: var(--font-size-lg);
		font-weight: 700;
		letter-spacing: 0.15em;
		color: var(--text-bright);
		margin-bottom: 4px;
	}
	.subtitle {
		font-size: var(--font-size-sm);
		color: var(--text-muted);
		font-family: var(--font-mono);
		margin-bottom: 32px;
	}
	.login-form {
		display: flex;
		flex-direction: column;
		gap: 12px;
	}
	input {
		background: var(--surface-0);
		border: 1px solid var(--border);
		border-radius: var(--radius);
		padding: 10px 14px;
		text-align: center;
		font-family: var(--font-mono);
		font-size: var(--font-size-sm);
		transition: border-color var(--duration) var(--ease);
	}
	input:focus {
		outline: none;
		border-color: var(--border-focus);
	}
	.error {
		color: var(--rose);
		font-size: var(--font-size-xs);
	}
	.login-btn {
		background: var(--accent);
		border: none;
		border-radius: var(--radius);
		padding: 10px;
		color: white;
		font-weight: 600;
		cursor: pointer;
		transition: background var(--duration) var(--ease);
	}
	.login-btn:hover:not(:disabled) {
		background: var(--accent-hover);
	}
	.login-btn:disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}
</style>
