<script lang="ts">
	import { goto } from "@sapper/app";
	import { login } from "../components/stores";
	import { postLogin } from "../lib/api";

	$: if ($login) {
		goto("/");
	}
	let username = "";
	let password = "";
	let status = "";
</script>

<svelte:head>
	<title>Login - Skyblock Data Tracker</title>
</svelte:head>

<div id="content">
	<form
		on:submit={async event => {
			event.preventDefault();
			try {
				login.set(await postLogin({ username, password }));
			} catch (e) {
				username = "";
				password = "";
				try {
					status = (await e.response.json()).message;
				} catch (e2) {
					status = "Unknown error";
				}
			}
		}}
	>
		<h2>Login</h2>
		<p id="status">{status}</p>
		<input type="text" placeholder="Username" bind:value={username} />
		<input type="password" placeholder="Password" bind:value={password} />
		<input type="submit" value="Login" />
	</form>
</div>

<style lang="scss">
	@use "../styles/Form";
	div#content {
		display: grid;
		place-items: center;
		width: 100%;
	}
</style>
