<script lang="ts">
	import { auth } from '$lib/stores/auth.svelte';
	import { goto } from '$app/navigation';
	import { onMount } from 'svelte';
	import { page } from '$app/state';
	import type { PageData } from './$types';

	let { data }: { data: PageData } = $props();

	// Get user type from layout data
	let user = $derived(data.user?.data?.me);
	let isTeamMember = $derived(user?.__typename === 'TeamProfileType');
	let isCustomer = $derived(user?.__typename === 'CustomerProfileType');

	// Determine the correct dashboard based on user type
	function getDefaultDashboard(): string {
		if (isTeamMember) return '/team';
		if (isCustomer) return '/customer';
		return '/';
	}

	// Redirect authenticated users away from login page
	$effect(() => {
		if (auth.isAuthenticated && user) {
			const returnTo = page.url.searchParams.get('return_to');
			// If return_to is provided and is a valid internal route, use it
			// Otherwise redirect to the appropriate dashboard
			if (
				returnTo &&
				returnTo.startsWith('/') &&
				!returnTo.startsWith('/login') &&
				!returnTo.startsWith('/register')
			) {
				goto(returnTo);
			} else {
				goto(getDefaultDashboard());
			}
		}
	});

	// Redirect to Kratos login on mount
	onMount(() => {
		// If already authenticated, the effect above will handle redirect
		if (auth.isAuthenticated) return;

		const returnTo = page.url.searchParams.get('return_to');

		// If no return_to param, use the referrer (where they came from)
		if (!returnTo && document.referrer) {
			try {
				const referrerUrl = new URL(document.referrer);
				const currentOrigin = window.location.origin;

				// If they came from the same app, redirect back there
				if (referrerUrl.origin === currentOrigin && referrerUrl.pathname !== '/login') {
					auth.redirectToLogin(document.referrer);
					return;
				}
			} catch (e) {
				console.error('Invalid referrer URL:', e);
			}
		}

		// Otherwise use the provided return_to or default to login callback
		// We use /login as the return_to so the effect above can determine the right dashboard
		auth.redirectToLogin(returnTo || `${window.location.origin}/login`);
	});
</script>

<svelte:head>
	<title>Sign In - Nexus</title>
</svelte:head>

<section class="flex min-h-[calc(100vh-3.5rem)] items-center justify-center p-4">
	<div class="text-center">
		<div class="mb-4 text-lg text-theme-secondary">Redirecting to login...</div>
		<div
			class="mx-auto h-8 w-8 animate-spin rounded-full border-4 border-primary-500/30 border-t-primary-500"
		></div>
	</div>
</section>
