<script lang="ts">
	import { goto } from '$app/navigation';
	import { base } from '$app/paths';
	import { _ } from 'svelte-i18n';
	let username = '';
	let password = '';
	let error = '';
	let loading = false;

	async function handleSubmit(event: Event) {
		event.preventDefault();
		error = '';
		loading = true;
		try {
			const res = await fetch(`/api/login.php`, {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ username, password })
			});
			const data = await res.json();
			if (res.ok) {
				localStorage.setItem('token', data.token);
				localStorage.setItem('user_display_name', data.user.user_display_name);
				goto(`${base}/dashboard`, { replaceState: true });
			} else {
				error = data.message || $_('login.login_failed');
			}
		} catch (e) {
			error = $_('login.network_error');
		} finally {
			loading = false;
		}
	}
</script>

<main
	class="flex min-h-screen sm:items-center justify-center bg-timberwolf dark:bg-gunmetal"
	style="
		background-image: url('{base}/images/login-background.jpg');
		background-size: cover;
		background-"
>
	<div class="w-full sm:max-w-md sm:rounded-lg bg-timberwolf dark:bg-gunmetal dark:text-timberwolf p-8 shadow-lg">
		<h1 class="mb-6 text-center text-2xl font-bold">{$_('login.title')}</h1>
		{#if error}
			<div class="mb-4 rounded bg-red-100 p-2 text-sm text-red-700">{error}</div>
		{/if}
		<form on:submit|preventDefault={handleSubmit} class="space-y-4">
			<div>
				<label for="username" class="mb-1 block text-sm font-medium">{$_('login.username')}</label>
				<input
					id="username"
					type="text"
					bind:value={username}
					required
					class="w-full rounded border px-3 py-2 dark:bg-gunmetal focus:border-forest-green focus:ring focus:outline-none"
				/>
			</div>
			<div>
				<label for="password" class="mb-1 block text-sm font-medium">{$_('login.password')}</label>
				<input
					id="password"
					type="password"
					bind:value={password}
					required
					class="w-full rounded border px-3 py-2 dark:bg-gunmetal focus:border-forest-green focus:ring focus:outline-none"
				/>
			</div>
			<button
				type="submit"
				class="w-full rounded bg-forest-green-400 hover:bg-forest-green-500  dark:bg-forest-green-600 py-2 font-semibold text-gunmetal dark:hover:bg-forest-green-700 dark:hover:text-timberwolf cursor-pointer disabled:opacity-80"
				disabled={loading}
			>
				{#if loading}{$_('login.loading')}...{:else}{$_('login.login')}{/if}
			</button>
		</form>
	</div>
</main>
