<script lang="ts">
	import { post } from 'src/lib/requests.svelte';
	import 'src/styles/forms.css';
	import { userStore } from '../UserStore.svelte';
	import { goto } from '$app/navigation';

	let submitted = $state(false);

	let loginData = $state({
		email: '',
		password: ''
	});

	let errorMessage = $state('');

	async function onSubmit() {
		submitted = true;
		errorMessage = '';

		try {
			const req = await post('login', loginData);
			userStore.user = req;
			goto('/');
		} catch (e) {
			loginData.password = '';
			if (e instanceof Response) {
				errorMessage = await e.json();
			} else {
				errorMessage = 'Server could not perform login';
			}
		}
	}
</script>

<svelte:head>
	<title>Login</title>
</svelte:head>

<div class="login-page">
	<div>
		<h1>Login</h1>
		<form on:submit|preventDefault={onSubmit} class:submitted>
			<fieldset>
				<label for="email">Email</label>
				<input type="email" required name="email" bind:value={loginData.email} />
			</fieldset>
			<fieldset>
				<label for="password">Password</label>
				<input required name="password" type="password" bind:value={loginData.password} />
				{#if errorMessage}
					<span class="form-msg error">
						{errorMessage}
						<!--Either the password or the email are incorrect-->
					</span>
				{/if}
			</fieldset>
			<button> Login </button>
			<div class="spacer"></div>
			<a class="simple-link text-center w100 spacer" href="/register"> Register </a>
		</form>
	</div>
</div>

<style lang="scss">
	/* Login Page */
	.login-page {
		display: grid;
		place-items: center;
		margin-bottom: 40px;
		& > div {
			width: 40vw;
		}
		h1 {
			text-align: center;
		}
	}
</style>
