<script lang="ts">
	import AppShell from '$lib/components/layout/AppShell.svelte';
	import Navbar from '$lib/components/layout/Navbar.svelte';
	import MobileTabBar from '$lib/components/layout/MobileTabBar.svelte';
	import CommandPalette from '$lib/components/layout/CommandPalette.svelte';
	import FitnessAssistantDrawer from '$lib/components/assistant/FitnessAssistantDrawer.svelte';

	let { children, data } = $props();
	let commandOpen = $state(false);
	let assistantEntryDate = $state<string | null>(null);
	const visibleApps = data?.visibleApps || ['trips', 'fitness', 'inventory', 'budget', 'reader', 'media'];
	const userName = data?.user?.display_name || '';
	const useAtelierShell = data?.useAtelierShell || false;

	function openCommand() {
		commandOpen = true;
	}

	function closeCommand() {
		commandOpen = false;
	}

	function handleKeydown(e: KeyboardEvent) {
		if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
			e.preventDefault();
			commandOpen = !commandOpen;
		}
	}

	function handleAssistantOpen(event: Event) {
		const detail = (event as CustomEvent<{ entryDate?: string }>).detail;
		assistantEntryDate = detail?.entryDate || null;
		commandOpen = true;
	}
</script>

<svelte:window onkeydown={handleKeydown} onopenassistant={handleAssistantOpen} />

{#if useAtelierShell}
	<AppShell onOpenCommand={openCommand} {visibleApps} {userName}>
		{@render children()}
	</AppShell>
	<FitnessAssistantDrawer bind:open={commandOpen} onclose={closeCommand} entryDate={assistantEntryDate} />
{:else}
	<div class="app">
		<Navbar onOpenCommand={openCommand} {visibleApps} />

		<main>
			{@render children()}
		</main>

		<MobileTabBar {visibleApps} />
		<CommandPalette bind:open={commandOpen} onclose={closeCommand} />
	</div>
{/if}

<style>
	.app {
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}
	main {
		flex: 1;
		padding: 0 16px;
		width: 100%;
		max-width: 100%;
		margin: 0 auto;
	}

	@media (min-width: 768px) {
		main {
			padding: 0;
			max-width: 1380px;
		}
	}
</style>
