<script lang="ts">
  import Header from '$lib/components/Header.svelte';
  import { toast } from '$lib/stores/toast.js';
  import Toast from '$lib/components/Toast.svelte';
  import { onMount } from 'svelte';
  import { auth } from '$lib/stores/auth.js';
  import { goto } from '$app/navigation';
  import { page } from '$app/stores';
  import { browser } from '$app/environment';
  import '../app.css';

  export let data;

  let mounted = false;

  onMount(() => {
    if (data.user && !$auth.isAuthenticated) {
      auth.setUser(data.user);
    }
    mounted = true;
  });

  // Guard reactivo global: redirige a /login si no está autenticado en rutas protegidas
  const publicRoutes = ['/login', '/register', '/forgot-password', '/reset-password'];
  $: if (browser && mounted && !$auth.isAuthenticated &&
       !publicRoutes.some(r => $page.url.pathname.startsWith(r))) {
    goto('/login');
  }

  $: showHeader = !publicRoutes.some(r => $page.url.pathname.startsWith(r));
</script>

<div class="min-h-screen bg-gray-50 font-sans">
  {#if !mounted}
    <!-- Esperando inicialización de sesión -->
    <div class="flex items-center justify-center min-h-screen bg-gray-50">
      <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
    </div>
  {:else}
  {#if showHeader}
    <Header />
  {/if}
  
  <main class="flex-1">
    <slot />
  </main>
  
  <!-- Footer with version -->
  <footer class="py-4 text-center border-t border-gray-200 bg-white">
    <p class="text-xs text-gray-400">ServiceManagerWeb v1.9.0 · © 2026 Aduanasoft</p>
  </footer>
  {/if}
  
  <!-- Toast notifications -->
  {#each $toast.toasts as toastMessage (toastMessage.id)}
    <Toast
      type={toastMessage.type}
      message={toastMessage.message}
      duration={toastMessage.duration}
      on:dismiss={() => toast.dismiss(toastMessage.id)}
    />
  {/each}
</div>