"use client";

import { useEffect, useMemo } from "react";
import { usePathname, useRouter } from "next/navigation";
import { useAuth } from "@/presentation/hooks/use-auth";
import AdminLayout from "@/presentation/components/layout/admin-layout";
import { PageHeaderProvider } from "@/presentation/hooks/use-page-header";
import { ROUTES, ROUTE_PERMISSION } from "@/shared/constants";
import { Loader2 } from "lucide-react";

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const { isAuthenticated, loading, hasPermission } = useAuth();
  const pathname = usePathname();
  const router = useRouter();

  // Resolve the permission this route requires (prefix match covers detail pages
  // like /tickets/[id]). Routes not in the map are open to any authenticated user.
  const requiredCode = useMemo(() => {
    const entry = Object.entries(ROUTE_PERMISSION).find(
      ([prefix]) => pathname === prefix || pathname.startsWith(`${prefix}/`),
    );
    return entry?.[1];
  }, [pathname]);

  const allowed = !requiredCode || hasPermission(requiredCode);

  // Direct deep-link without the permission: send them back to the overview.
  useEffect(() => {
    if (!loading && isAuthenticated && !allowed) {
      router.replace(ROUTES.dashboard);
    }
  }, [loading, isAuthenticated, allowed, router]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-background">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  if (!isAuthenticated || !allowed) {
    return null;
  }

  return (
    <PageHeaderProvider>
      <AdminLayout>{children}</AdminLayout>
    </PageHeaderProvider>
  );
}
