<script lang="ts">
	import './layout.css';
	import type { LayoutData } from './$types';
	import favicon from '$lib/assets/logo-icon.png';
	import { theme } from '$lib/stores/theme.svelte';
	import { unreadCounts } from '$lib/stores/unreadCounts.svelte';
	import { page } from '$app/state';
	import { onMount, onDestroy, type Snippet } from 'svelte';
	import TopNav from '$lib/components/nav/TopNav.svelte';
	import MenuOverlay from '$lib/components/layout/MenuOverlay.svelte';
	import TeamNav from '$lib/components/nav/TeamNav.svelte';
	import AdminNav from '$lib/components/nav/AdminNav.svelte';
	import CustomerNav from '$lib/components/nav/CustomerNav.svelte';
	import BusinessFooter from '$lib/components/BusinessFooter.svelte';
	import OffCanvasRight from '$lib/components/layout/OffCanvasRight.svelte';
	import ChatPanel from '$lib/components/chat/ChatPanel.svelte';
	import ChatToggle from '$lib/components/chat/ChatToggle.svelte';
	import { chat } from '$lib/stores/chat.svelte';

	let { data, children }: { data: LayoutData; children: Snippet } = $props();
	let sidebarOpen = $state(false);
	let user = $derived(data.user?.data?.me ?? null);
	let isAuthenticated = $derived(!!user);

	// Public routes that show BusinessFooter instead of bottom nav
	const publicRoutes = [
		'/',
		'/services',
		'/about',
		'/contact',
		'/careers',
		'/press',
		'/blog',
		'/help',
		'/privacy',
		'/terms',
		'/cookies',
		'/login',
		'/register',
		'/logout',
		'/standard',
		'/pricing'
	];
	let isPublicRoute = $derived(publicRoutes.includes(page.url.pathname));

	// Route-based nav selection
	let isTeamRoute = $derived(page.url.pathname.startsWith('/team'));
	let isAdminRoute = $derived(page.url.pathname.startsWith('/admin'));
	let isCustomerRoute = $derived(page.url.pathname.startsWith('/customer'));

	function openSidebar() {
		sidebarOpen = true;
	}

	function closeSidebar() {
		sidebarOpen = false;
	}

	// Start/stop polling based on authentication state
	$effect(() => {
		if (isAuthenticated) {
			unreadCounts.startPolling();
		} else {
			unreadCounts.stopPolling();
			unreadCounts.resetCounts();
			chat.disconnect();
		}
	});

	onMount(() => {
		theme.init();
	});

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

<svelte:head>
	<link rel="icon" href={favicon} />
	<title>{isPublicRoute ? 'Nexus Cleaning Solutions | Nexus v5.0' : 'Nexus v5.0'}</title>
</svelte:head>

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

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

	{#if isPublicRoute}
		<BusinessFooter />
	{:else if isTeamRoute}
		<TeamNav />
	{:else if isAdminRoute}
		<AdminNav />
	{:else if isCustomerRoute}
		<CustomerNav />
	{/if}

	<OffCanvasRight />

	<!-- Chat for authenticated users on non-public routes -->
	{#if isAuthenticated && !isPublicRoute}
		<ChatToggle />
		<ChatPanel />
	{/if}
</div>
