<script lang="ts">
	import type { Snippet } from 'svelte';
	import { page } from '$app/stores';
	import { isAuthenticated, authLoading } from '$lib/stores/auth';
	import { login } from '$lib/auth';
	import DesktopSidebar from '$lib/components/layout/DesktopSidebar.svelte';
	import MobileTopBar from '$lib/components/layout/MobileTopBar.svelte';
	import BottomTabBar from '$lib/components/layout/BottomTabBar.svelte';
	import MobileDrawer from '$lib/components/layout/MobileDrawer.svelte';
	import UndoToast from '$lib/components/UndoToast.svelte';
	import * as m from '$lib/paraglide/messages';

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

	let drawerOpen = $state(false);

	// Detail routes render their own contextual header (back + title). On mobile
	// we hide the global MobileTopBar for those paths so the contextual header
	// becomes the only top chrome. BottomTabBar stays visible (user can still
	// jump between sections). Modo Compra covers everything with its own z-50
	// overlay, so it effectively hides bottom too — handled locally.
	const detailRoutePattern = /^\/(lists\/[0-9a-f-]+(?:\/session)?|tasks\/[0-9a-f-]+|notes\/[0-9a-f-]+)\/?$/;
	const isDetailRoute = $derived(detailRoutePattern.test($page.url.pathname));

	// When auth resolves as unauthenticated, redirect to Keycloak.
	// This runs after onAuthStateChange fires (authLoading = false), so there
	// is no race with Supabase's async localStorage initialisation.
	$effect(() => {
		if (!$authLoading && !$isAuthenticated) {
			login();
		}
	});
</script>

{#if $authLoading}
	<div class="flex h-screen items-center justify-center bg-background">
		<span class="text-sm text-text-secondary">{m.loading()}</span>
	</div>
{:else if $isAuthenticated}
	<!-- Mobile: column stack (top bar → main → bottom tab bar).
	     Desktop: row (sidebar | main). -->
	<div class="flex h-screen flex-col overflow-hidden bg-background md:flex-row">
		<DesktopSidebar />

		{#if !isDetailRoute}
			<MobileTopBar onMenu={() => (drawerOpen = true)} />
		{/if}
		<MobileDrawer bind:open={drawerOpen} />

		<main class="flex flex-1 flex-col overflow-hidden bg-background pb-16 md:pb-0">
			{@render children()}
		</main>

		<BottomTabBar />
		<UndoToast />
	</div>
{/if}
