<script lang="ts">
	import { setContext, onMount } from 'svelte';
	import { invalidateAll } from '$app/navigation';
	import type { LayoutData } from './$types';
	import AppSidebar from '$lib/components/sidebar/app-sidebar.svelte';
	import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
	import { Separator } from '$lib/components/ui/separator/index.js';
	import * as Sidebar from '$lib/components/ui/sidebar/index.js';
	import { companyStore } from '$lib/stores/company.svelte';
	import ExchangeRateGuard from '$lib/components/dashboard/exchange_rate/exchange-rate-guard.svelte';

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

	// Hacer disponible el usuario en el contexto para los componentes hijos
	setContext('user', data.user);

	// Inicializar el store con las compañías pre-cargadas desde el servidor
	onMount(() => {
		if (data.companies) {
			companyStore.initialize(data.companies);
		}

		// Escuchar cambios de compañía y recargar datos
		const handleCompanyChange = () => {
			invalidateAll();
		};
		window.addEventListener('companyChanged', handleCompanyChange);

		return () => {
			window.removeEventListener('companyChanged', handleCompanyChange);
		};
	});
</script>

<Sidebar.Provider>
	<AppSidebar />
	<Sidebar.Inset class="overflow-x-hidden">
		<header
			class="flex h-16 shrink-0 items-center gap-2 transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-12"
		>
			<div class="flex items-center gap-2 px-4">
				<Sidebar.Trigger class="-ml-1" />
				<Separator orientation="vertical" class="mr-2 data-[orientation=vertical]:h-4" />
				<!--
				<Breadcrumb.Root>
					<Breadcrumb.List>
						<Breadcrumb.Item class="hidden md:block">
							<Breadcrumb.Link href="/dashboard">Dashboard</Breadcrumb.Link>
						</Breadcrumb.Item>
						<Breadcrumb.Separator class="hidden md:block" />
						<Breadcrumb.Item>
							<Breadcrumb.Page>Inicio</Breadcrumb.Page>
						</Breadcrumb.Item>
					</Breadcrumb.List>
				</Breadcrumb.Root>
				-->
			</div>
		</header>
		<div class="flex flex-1 flex-col gap-4 overflow-x-hidden p-4 pt-0">
			<!-- Contenido de cada página -->
			{@render children?.()}
		</div>
	</Sidebar.Inset>
</Sidebar.Provider>

<ExchangeRateGuard overlayClass="bg-black/5" />
