<script lang="ts">
	import { page, navigating } from '$app/stores';
	import { Sidebar, Header, MobileNav, MobileMenu } from '$lib/components/layout';
	import EmailVerificationBanner from '$lib/components/EmailVerificationBanner.svelte';

	let { children, data } = $props();

	let sidebarCollapsed = $state(false);
	let mobileMenuOpen = $state(false);

	// Get page title from route data or default
	const pageTitle = $derived(getPageTitle($page.url.pathname));

	function getPageTitle(path: string): string {
		const titles: Record<string, string> = {
			'/dashboard': 'Dashboard',
			'/profile': 'My Profile',
			'/events': 'Events',
			'/payments': 'Payments',
			'/documents': 'Documents',
			'/board/members': 'Members',
			'/board/dues': 'Dues Management',
			'/board/events': 'Manage Events',
			'/admin/users': 'User Management',
			'/admin/settings': 'Settings'
		};

		for (const [route, title] of Object.entries(titles)) {
			if (path.startsWith(route)) return title;
		}

		return 'Monaco USA';
	}

	function toggleSidebar() {
		sidebarCollapsed = !sidebarCollapsed;
	}

	function openMobileMenu() {
		mobileMenuOpen = true;
	}

	function closeMobileMenu() {
		mobileMenuOpen = false;
	}
</script>

<div class="flex h-screen overflow-hidden bg-gradient-to-br from-slate-50 via-white to-slate-100">
	<a href="#main-content" class="sr-only focus:not-sr-only focus:fixed focus:left-4 focus:top-4 focus:z-50 focus:rounded-md focus:bg-white focus:px-4 focus:py-2 focus:text-sm focus:font-medium focus:text-monaco-600 focus:shadow-lg focus:ring-2 focus:ring-monaco-500">
		Skip to content
	</a>

	{#if $navigating}
		<div class="fixed inset-x-0 top-0 z-50 h-0.5 bg-monaco-200">
			<div class="h-full animate-pulse bg-monaco-600" style="width: 90%; animation: progress 1s ease-in-out infinite;"></div>
		</div>
	{/if}

	<!-- Desktop Sidebar -->
	<div class="hidden lg:block">
		<Sidebar
			member={data.member}
			currentPath={$page.url.pathname}
			collapsed={sidebarCollapsed}
			onToggle={toggleSidebar}
		/>
	</div>

	<!-- Main Content Area -->
	<div class="flex flex-1 flex-col overflow-hidden">
		<!-- Header -->
		<Header member={data.member} title={pageTitle} onMenuToggle={openMobileMenu} />

		<!-- Email Verification Banner -->
		{#if !data.emailVerified}
			<EmailVerificationBanner email={data.member.email} />
		{/if}

		<!-- Page Content -->
		<main id="main-content" class="flex-1 overflow-y-auto pb-20 lg:pb-0">
			<div class="container mx-auto max-w-7xl p-4 lg:p-6">
				{@render children()}
			</div>
		</main>
	</div>

	<!-- Mobile Bottom Navigation -->
	<MobileNav member={data.member} currentPath={$page.url.pathname} onMenuOpen={openMobileMenu} />

	<!-- Mobile Menu Overlay -->
	<MobileMenu
		member={data.member}
		currentPath={$page.url.pathname}
		open={mobileMenuOpen}
		onClose={closeMobileMenu}
	/>
</div>
