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

  import { urlG } from "../stores/urlStore";

  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($urlG+"/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="d-flex justify-content-center position-absolute top-50 start-50">
  <div class="spinner-border" role="status">
    <span class="visually-hidden">Loading...</span>
  </div>
</div>
{:else}
  {#if $isAuthenticated}
    {@render componente()}
  {:else}
    {window.location.replace('/')}  
  {/if}
{/if}  
