"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import { AdminSidebar } from "@/components/admin/AdminSidebar";

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  const { user, loading, isSuperAdmin, permissions } = useAuth();
  const router = useRouter();

  // Access to the dashboard requires at least one elevated permission, or being
  // a SuperAdmin. Guests (no permissions) are sent to their own dashboard.
  const hasDashboardAccess = isSuperAdmin || permissions.length > 0;

  useEffect(() => {
    if (loading) return;
    if (!user) {
      router.push("/login");
      return;
    }
    if (!hasDashboardAccess) {
      router.push("/dashboard");
    }
  }, [user, loading, hasDashboardAccess, router]);

  if (loading || !user || !hasDashboardAccess) {
    return null;
  }

  return (
    <div className="flex">
      <AdminSidebar />
      <main className="flex-1 p-8 bg-surface min-h-screen">{children}</main>
    </div>
  );
}
