<script lang="ts">
  import { useQuery } from "convex-svelte";
  import { api } from "@sgse-app/backend/convex/_generated/api";
  import type { Id } from "@sgse-app/backend/convex/_generated/dataModel";
  import { authStore } from "$lib/stores/auth.svelte";
  import { loginModalStore } from "$lib/stores/loginModal.svelte";
  import { AlertTriangle } from "lucide-svelte";

  interface Props {
    recurso: string;
    acao: string;
    children?: any;
  }

  let { recurso, acao, children }: Props = $props();

  let verificando = $state(true);
  let permitido = $state(false);

  const permissaoQuery = $derived(
    authStore.usuario
      ? useQuery(api.permissoesAcoes.verificarAcao, {
          usuarioId: authStore.usuario._id as Id<"usuarios">,
          recurso,
          acao,
        })
      : null
  );

  $effect(() => {
    if (!authStore.autenticado) {
      verificando = false;
      permitido = false;
      const currentPath = window.location.pathname;
      loginModalStore.open(currentPath);
      return;
    }

    if (permissaoQuery?.error) {
      verificando = false;
      permitido = false;
    } else if (permissaoQuery && !permissaoQuery.isLoading) {
      // Backend retorna null quando permitido
      verificando = false;
      permitido = true;
    }
  });
</script>

{#if verificando}
  <div class="flex items-center justify-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 permitido}
  {@render children?.()}
{:else}
  <div class="flex items-center justify-center min-h-screen">
    <div class="text-center">
      <div class="p-4 bg-error/10 rounded-full inline-block mb-4">
        <AlertTriangle class="h-16 w-16 text-error" strokeWidth={2} />
      </div>
      <h2 class="text-2xl font-bold text-base-content mb-2">Acesso Negado</h2>
      <p class="text-base-content/70">
        Você não tem permissão para acessar esta ação.
      </p>
    </div>
  </div>
{/if}
