"use client";
import type React from "react";
import { useEffect, useMemo, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import AdminLeftNavigation from "@/components/AdminLeftNavigation";
import { useAuth } from "@/context/AuthContext";
import {
LayoutDashboard,
Download,
Layers,
Boxes,
Store,
Users,
Settings,
LucideMail,
Wand2,
} from "lucide-react";
const navItems = [
{ label: "Dashboard", href: "/admin", icon: },
{ label: "Imports", href: "/admin/import-status", icon: },
{ label: "Mappings", href: "/admin/mapping", icon: },
{ label: "Products", href: "/admin/products", icon: },
{ label: "Merchants", href: "/admin/merchants", icon: },
{ label: "Platforms", href: "/admin/platforms", icon: },
{ label: "Enrichment", href: "/admin/enrichment", icon: },
{ label: "Users", href: "/admin/users", icon: },
{ label: "Settings", href: "/admin/settings", icon: },
{ label: "List Emails", href: "/admin/email", icon: },
{ label: "Send an Email", href: "/admin/email/send", icon: },
];
export default function AdminLayout({
children,
}: {
children: React.ReactNode;
}) {
const [collapsed, setCollapsed] = useState(false);
const { user, loading } = useAuth();
const router = useRouter();
const pathname = usePathname();
// Where to send people back after login
const next = useMemo(
() => encodeURIComponent(pathname || "/admin"),
[pathname]
);
/**
* ✅ AUTH GUARD
* Redirects happen in useEffect (NOT during render)
*/
useEffect(() => {
if (loading) return;
// Not logged in
if (!user) {
router.replace(`/login?next=${next}`);
return;
}
// Logged in but not admin
if (user.role !== "ADMIN") {
router.replace("/");
}
}, [loading, user, router, next]);
// While loading OR redirecting, render nothing
if (loading) return null;
if (!user) return null;
if (user.role !== "ADMIN") return null;
return (
setCollapsed((v) => !v)}
items={navItems}
/>
{/* Main column */}
{/* Top bar */}
{/* Content */}
{children}
);
}