<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({
		username: '',
		email: '',
		password: ''
	});

	let errorMessage = $state('');

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

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

<svelte:head>
	<title>Register</title>
</svelte:head>

<div class="login-page">
	<div>
		<h1>Register</h1>
		<form on:submit|preventDefault={onSubmit} class:submitted>
			<fieldset>
				<label for="username">Username</label>
				<input required name="username" bind:value={loginData.username} />
				<!--{{if .UserError}}
                    <span class="form-msg error">
                        Username already in use
                    </span>
                {{end}}-->
			</fieldset>
			<fieldset>
				<label for="email">Email</label>
				<input type="email" required name="email" bind:value={loginData.email} />
				<!-- {{if .EmailError}}
                    <span class="form-msg error">
                        Email already in use
                    </span>
                {{end}} -->
			</fieldset>
			<fieldset>
				<label for="password">Password</label>
				<input required name="password" type="password" bind:value={loginData.password} />
				<!-- {{if .PasswordToLong}}
                    <span class="form-msg error">
                        Password is to long
                    </span>
                {{end}} -->
			</fieldset>
			{#if errorMessage}
				<div class="form-msg error">
					{errorMessage}
				</div>
			{/if}
			<button> Register </button>
			<div class="spacer"></div>
			<a class="simple-link text-center w100" href="/login"> Login </a>
		</form>
	</div>
</div>

<style lang="scss">
	.login-page {
		display: grid;
		place-items: center;
		margin-bottom: 40px;

		& > div {
			width: 40vw;
		}

		h1 {
			text-align: center;
		}
	}
</style>
