<script lang="ts">
	import { goto } from '$app/navigation';
	import { browser } from '$app/environment';
	import { RegisterPage } from '@manacore/shared-auth-ui';
	import { authStore } from '$lib/stores/auth.svelte';
	import '$lib/i18n';

	let error = $state('');
	let loading = $state(false);

	// Get redirect URL from sessionStorage (set by AuthGateModal in guest mode)
	const redirectTo = $derived.by(() => {
		if (browser) {
			const sessionRedirect = sessionStorage.getItem('auth-return-url');
			if (sessionRedirect) {
				// Clear it after reading
				sessionStorage.removeItem('auth-return-url');
				return sessionRedirect;
			}
		}
		return '/';
	});

	async function handleRegister(email: string, password: string) {
		loading = true;
		error = '';

		const result = await authStore.signUp(email, password);

		if (result.success) {
			if (result.needsVerification) {
				// Show verification message or redirect to verification page
				goto('/login?registered=true');
			} else {
				goto(redirectTo);
			}
		} else {
			error = result.error || 'Registrierung fehlgeschlagen';
		}

		loading = false;
	}
</script>

<RegisterPage
	appName="Clock"
	appLogo=""
	{loading}
	{error}
	onSubmit={handleRegister}
	loginHref="/login"
/>
