<script>
	import { applyAction, enhance } from '$app/forms';
	import { page } from '$app/stores';
	import { receive, send } from '$lib/utils/helpers';
	import { t } from 'svelte-i18n';

	/** @type {import('./$types').ActionData} */
	export let form;

	/** @type {import('./$types').SubmitFunction} */
	const handleLogin = async () => {
		return async ({ result }) => {
			await applyAction(result);
		};
	};

	let message = '';
	if ($page.url.searchParams.get('message')) {
		message = $page.url.search.split('=')[1].replaceAll('%20', ' ');
	}
</script>

<div class="container">
	<form class="content" method="POST" action="?/login" use:enhance={handleLogin}>
		<h1 class="step-title">{$t('user.login')}</h1>
		{#if form?.errors}
			{#each form?.errors as error (error.id)}
				<h4
					class="step-subtitle warning"
					in:receive|global={{ key: error.id }}
					out:send|global={{ key: error.id }}
				>
					{$t(error.key)}
				</h4>
			{/each}
		{/if}

		{#if message}
			<h4 class="step-subtitle">{message}</h4>
		{/if}

		<input type="hidden" name="next" value={$page.url.searchParams.get('next')} />
		<div class="input-box">
			<span class="label">{$t('user.email')}:</span>
			<input class="input" type="email" name="email" placeholder="{$t('placeholder.email')} " />
		</div>
		<div class="input-box">
			<span class="label">{$t('password')}:</span>
			<div class="input-wrapper">
				<input
					class="input"
					type="password"
					name="password"
					placeholder={$t('placeholder.password')}
				/>
				<a href="/auth/password/request-change" class="forgot-password">{$t('forgot_password')}?</a>
			</div>
		</div>
		<div class="btn-container">
			<button class="button-dark">{$t('login')} </button>
		</div>
	</form>
</div>

<style>
	.input-wrapper {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		width: 100%;
		max-width: 444px;
		margin-top: 30px;
	}

	.forgot-password {
		margin-top: 0.5rem;
		font-size: 0.9em;
	}
</style>
