<script lang="ts">
	import '../app.css';
	import { onMount } from 'svelte';
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { auth } from '$lib/stores/auth';
	import Sidebar from '$lib/components/Sidebar.svelte';

	// Public routes that don't require authentication
	const publicRoutes = ['/login', '/auth/callback/google'];

	$: isPublicRoute = publicRoutes.some(route => $page.url.pathname.startsWith(route));

	onMount(async () => {
		const authenticated = await auth.checkAuth();

		if (!authenticated && !isPublicRoute) {
			goto('/login');
		}
	});

	// Reactive check for route changes
	$: if (!$auth.loading && !$auth.authenticated && !isPublicRoute) {
		goto('/login');
	}
</script>

{#if $auth.loading}
	<div class="min-h-screen flex items-center justify-center" style="background: #fdf8f3;">
		<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
	</div>
{:else if isPublicRoute}
	<slot />
{:else if $auth.authenticated}
	<div class="flex h-screen" style="background: #fdf8f3;">
		<Sidebar />
		<!-- Main content automatically expands when sidebar collapses thanks to flex-1 -->
		<main class="flex-1 overflow-auto p-6 transition-all duration-300">
			<div class="max-w-7xl mx-auto">
				<slot />
			</div>
		</main>
	</div>
{/if}
