<script lang="ts">
  import { authStore } from "$lib/stores/auth.svelte";
  import { goto } from "$app/navigation";
  import { onMount } from "svelte";
  import { page } from "$app/stores";
  import type { Snippet } from "svelte";

  let { 
    children,
    requireAuth = true,
    allowedRoles = [],
    maxLevel = 3,
    redirectTo = "/"
  }: {
    children: Snippet;
    requireAuth?: boolean;
    allowedRoles?: string[];
    maxLevel?: number;
    redirectTo?: string;
  } = $props();

  let isChecking = $state(true);
  let hasAccess = $state(false);

  onMount(() => {
    checkAccess();
  });

  function checkAccess() {
    isChecking = true;

    // Aguardar um pouco para o authStore carregar do localStorage
    setTimeout(() => {
      // Verificar autenticação
      if (requireAuth && !authStore.autenticado) {
        const currentPath = window.location.pathname;
        window.location.href = `${redirectTo}?error=auth_required&redirect=${encodeURIComponent(currentPath)}`;
        return;
      }

      // Verificar roles
      if (allowedRoles.length > 0 && authStore.usuario) {
        const hasRole = allowedRoles.includes(authStore.usuario.role.nome);
        if (!hasRole) {
          const currentPath = window.location.pathname;
          window.location.href = `${redirectTo}?error=access_denied&route=${encodeURIComponent(currentPath)}`;
          return;
        }
      }

      // Verificar nível
      if (authStore.usuario && authStore.usuario.role.nivel > maxLevel) {
        const currentPath = window.location.pathname;
        window.location.href = `${redirectTo}?error=access_denied&route=${encodeURIComponent(currentPath)}`;
        return;
      }

      hasAccess = true;
      isChecking = false;
    }, 100);
  }
</script>

{#if isChecking}
  <div class="flex justify-center items-center min-h-screen">
    <div class="text-center">
      <span class="loading loading-spinner loading-lg text-primary"></span>
      <p class="mt-4 text-base-content/70">Verificando permissões...</p>
    </div>
  </div>
{:else if hasAccess}
  {@render children()}
{/if}

