<script lang="ts">
  import Header from '$lib/components/Header.svelte';
  import Sidebar from '$lib/components/Sidebar.svelte';
  import Toast from '$lib/components/Toast.svelte';
  import { toast } from '$lib/stores/toast.js';
  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 sidebarOpen = false;
  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
  $: if (browser && mounted && !$auth.isAuthenticated && $page.url.pathname !== '/login') {
    goto('/login');
  }

  function toggleSidebar() {
    sidebarOpen = !sidebarOpen;
  }
</script>

<div class="min-h-screen bg-gray-50">
  {#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 $auth.isAuthenticated}
    <!-- Internal Layout with Sidebar -->
    <div class="flex h-screen overflow-hidden">
      <!-- Sidebar -->
      <Sidebar bind:open={sidebarOpen} />
      
      <!-- Main content -->
      <div class="flex-1 flex flex-col overflow-hidden">
        <Header {toggleSidebar} />
        
        <main class="flex-1 overflow-auto">
          <slot />
        </main>
      </div>
    </div>
  {:else}
    <!-- Login Layout -->
    <main class="flex-1">
      <slot />
    </main>
  {/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>
