<script>
    import { onMount } from 'svelte';
    import { navigate } from 'svelte-routing'; 
    import { writable } from 'svelte/store';


    let { componente } = $props();  
  
    const isAuthenticated = writable(false); 
    const isVerified = writable(false); 
  
    const redirect = window.location.pathname;
    const email = localStorage.getItem('email');
    const token = sessionStorage.getItem('token');
  
    const handleAccess = async () => {
      try {
        const response = await fetch('http://127.0.0.1:5007/api/login/validar', {
          method: 'POST',
          headers: {
            'Auth': String(token),
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ email, redirect }),
          credentials: "include"
        });
  
        if (response.ok) {
          isAuthenticated.set(true); // Actualiza el store
        }
      } catch (error) {
        console.error('Error durante la autenticación:', error);
      } finally {
        isVerified.set(true); // Marca la verificación como completada
      }
    };
  
    onMount(() => {
      handleAccess();
    });
  </script>
  
  {#if !$isVerified}
    <div class="spinner-border position-absolute top-50 start-50 translate-middle" role="status">
      <span class="visually-hidden">Cargando</span>
    </div>
  {:else}
    {#if $isAuthenticated}
      {@render componente()}
    {:else}
      {navigate('/')}  
    {/if}
  {/if}
  