<script lang="ts">
	import './layout.css';
	import type { LayoutData } from './$types';
	import type { Snippet } from 'svelte';
	import { onMount, onDestroy } from 'svelte';
	import { theme } from '$lib/stores/theme.svelte';
	import { unreadCounts } from '$lib/stores/unreadCounts.svelte';
	import TopNav from '$lib/components/nav/TopNav.svelte';
	import MenuOverlay from '$lib/components/layout/MenuOverlay.svelte';
	import logoIcon from '$lib/assets/logo-icon.png';

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

	let sidebarOpen = $state(false);
	let user = $derived(data.user);
	let isAuthenticated = $derived(!!user);

	function openSidebar() {
		sidebarOpen = true;
	}

	function closeSidebar() {
		sidebarOpen = false;
	}

	onMount(() => {
		theme.init();
		// Start polling for unread counts if authenticated
		if (isAuthenticated) {
			unreadCounts.startPolling();
		}
	});

	onDestroy(() => {
		unreadCounts.stopPolling();
	});
</script>

<svelte:head>
	<link rel="icon" href={logoIcon} />
	<title>Nexus</title>
</svelte:head>

<div class="flex min-h-dvh flex-col bg-theme text-theme">
	<TopNav {user} onMenuClick={openSidebar} />
	<MenuOverlay {user} open={sidebarOpen} onClose={closeSidebar} />

	<!-- Main Content -->
	<main class="flex-1 pt-14">
		{@render children()}
	</main>
</div>
