<script lang="ts">
	import favicon from '$lib/assets/favicon.svg';
	import { authStore } from '$lib/auth';
	import { onMount } from 'svelte';
	import { SvelteToast } from '@zerodevx/svelte-toast';
	import '../app.css';

	let { children } = $props();

	// Initialize auth state on mount
	onMount(() => {
		authStore.initialize();
	});

	// Subscribe to auth state
	let auth = $state({ user: null as any, token: null as string | null, loading: true });
	authStore.subscribe((state) => {
		auth = state;
	});

	function logout() {
		authStore.logout();
	}
</script>

<svelte:head>
	<link rel="icon" href={favicon} />
</svelte:head>

{#if auth.loading}
	<div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-tokyo-bg to-tokyo-bg-dark">
		<div class="text-center">
			<div class="animate-spin rounded-full h-16 w-16 border-4 border-tokyo-bg-highlight border-t-tokyo-blue mx-auto mb-4"></div>
			<p class="text-tokyo-fg-dark animate-pulse">Loading your library...</p>
		</div>
	</div>
{:else if !auth.token}
	<!-- Auth required -->
	<div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-tokyo-bg to-tokyo-bg-dark">
		<div class="text-center animate-slide-in">
			<div class="mb-8">
				<h1 class="text-4xl font-bold text-tokyo-fg mb-2">📚 Bookmann</h1>
				<p class="text-tokyo-fg-dark text-lg">Your personal digital library</p>
			</div>
			<div class="space-x-6">
				<a
					href="/login"
					class="btn-primary inline-flex items-center text-sm font-medium shadow-lg hover:shadow-tokyo-purple/25"
				>
					Sign In
				</a>
				<a
					href="/register"
					class="btn-secondary inline-flex items-center text-sm font-medium"
				>
					Create Account
				</a>
			</div>
			<div class="mt-12 text-tokyo-fg-dark text-sm">
				<p>Organize • Read • Enjoy</p>
			</div>
		</div>
	</div>
{:else}
	<!-- Authenticated user -->
	<header class="bg-tokyo-bg-dark border-b border-tokyo-bg-highlight shadow-lg">
		<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
			<div class="flex justify-between items-center py-4">
				<div class="flex items-center space-x-4">
					<h1 class="text-2xl font-bold text-tokyo-fg">📚 Bookmann</h1>
					<span class="hidden sm:inline text-sm text-tokyo-fg-dark">•</span>
					<span class="hidden sm:inline text-sm text-tokyo-fg-dark">Welcome back, {auth.user?.username}</span>
				</div>
				<div class="flex items-center space-x-4">
					<span class="text-sm text-tokyo-fg">Hello, <span class="text-tokyo-cyan font-medium">{auth.user?.username}</span></span>
					<button
						onclick={logout}
						class="btn-danger inline-flex items-center text-sm font-medium shadow-lg hover:shadow-tokyo-red/25 transition-all duration-200"
					>
						Sign Out
					</button>
				</div>
			</div>
		</div>
	</header>

	<main class="max-w-7xl mx-auto py-8 sm:px-6 lg:px-8 min-h-[calc(100vh-80px)]">
		{@render children()}
	</main>
{/if}

<!-- Toast notifications -->
<SvelteToast />
