<!--
	SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
	SPDX-License-Identifier: AGPL-3.0-or-later
-->
<template>
	<main>
		<h1>Register</h1>
		<div class="card">
			<h2>Regular User</h2>
			<p>
				Set up an authentication method and choose a username to register a new user.
			</p>
			<h3>Authentication Method</h3>
			<p v-if="sessionStore.authenticationProvider">
				Provider: {{ sessionStore.authenticationProvider }}
				<br>Identifier: {{ sessionStore.authenticationName }}
				<br><button type="button" @click="clearProvider">Clear Method</button>
			</p>
			<LogIn v-else />
			<form @submit.prevent="register(false)">
				<h3>User Details</h3>
				<p>
					<label>
						Username
						<input type="text" v-model="username" required>
					</label>
				</p>
				<p>
					<button
						type="submit"
						:disabled="!sessionStore.authenticationProvider"
					>
						Register new user
					</button>
				</p>
			</form>
		</div>
		<div class="alternatively">
			&ndash; or &ndash;
		</div>
		<div class="card">
			<h2>Anonymous User</h2>
			<p>
				If you do not wish to deal with logins you may create an
				anonymous user authenticated with a session cookie stored on
				this device. Since there's no persistent authentication for the
				user should you lose the session cookie you will also lose
				access to the user.
			</p>
			<p>
				<button type="button" @click="register(true)">
					Create anonymous user
				</button>
			</p>
		</div>
	</main>
</template>

<script setup lang="ts">
useHead({
	title: "Register",
});

const sessionStore = useSessionStore();
const username = ref("");

async function clearProvider() {
	sessionStore.logOut();
}
async function register(anonymous: boolean) {
	let session;
	try {
		session = await $fetch("/api/auth/account", {
			method: "POST",
			body: anonymous ? undefined : {
				name: username.value,
			},
		});
	} catch (err: any) {
		alert(err.data?.message ?? err.message);
		return;
	}
	sessionStore.update(session);
	if (session.account) {
		await navigateTo("/account/settings");
	}
}
</script>

<style scoped>
.alternatively {
	margin-block: 1rem;
}
.card {
	background: color-mix(in oklab, var(--background), grey 20%);
	padding: 0.5rem;
	border-radius: 0.5rem;
}
.card h2 {
	margin-block-start: 0;
}
</style>
