<template>
	<div class="content">
		<h2 class="heading">Log in</h2>

		<form
			class="form create"
			@submit.prevent="signup"
		>
			<div
				v-if="errorMsg"
				class="form-section form-error"
			>{{ errorMsg }}</div>

			<div class="form-section">
				<div class="form-row">
					<input
						v-model="username"
						placeholder="Username or e-mail"
						maxlength="500"
						class="input"
					>
				</div>

				<div class="form-row">
					<input
						v-model="password"
						type="password"
						minlength="8"
						maxlength="500"
						placeholder="Password"
						class="input"
					>
				</div>
			</div>

			<div
				v-if="config.captchaEnabled"
				class="form-row captcha"
			>
				<VueHcaptcha
					:sitekey="config.captchaKey"
					@verify="(token) => captchaToken = token"
					@expired="() => captchaToken = null"
					@error="() => captchaToken = null"
				/>
			</div>

			<div class="form-row form-actions">
				<a
					href="/account/create"
					class="link"
				>Sign up</a>

				<button
					:disabled="!username || !password"
					class="button button-submit"
				>Log in</button>
			</div>
		</form>
	</div>
</template>

<script setup>
import { ref } from 'vue';
import VueHcaptcha from '@hcaptcha/vue3-hcaptcha';

import { post } from '../../assets/js/api';
import { navigate } from '../../assets/js/navigate';

const config = CONFIG;

const username = ref('');
const password = ref('');

const errorMsg = ref(null);

async function signup() {
	try {
		await post('/session', {
			username: username.value,
			password: password.value,
		});

		navigate('/');
	} catch (error) {
		errorMsg.value = error.message;
	}
}
</script>

<style scoped>
.content {
	display: flex;
	flex-grow: 1;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}

.create {
	background: var(--background);
	padding: 1rem;
	border-radius: .5rem;
}

.name {
	position: relative;

	.input {
		padding-left: 1.65rem;
	}

	.prefix {
		color: var(--shadow);
		position: absolute;
		top: 1px;
		left: .25rem;
		letter-spacing: .1rem;
		padding: .5rem;
	}
}

.access {
	font-weight: bold;
	margin-bottom: .75rem;
	cursor: pointer;
}

.access-description {
	margin: .25rem 0 0 1.25rem;
	color: var(--shadow);
	font-size: .9rem;
	font-weight: normal;
}

.nsfw {
	margin-right: .5rem;
	font-weight: bold;
	color: var(--error);
}

.captcha {
	justify-content: center;
}

.form-actions {
	justify-content: space-between;
	align-items: center;
}
</style>
