import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import Link from "next/link";

// Every admin nav section, keyed by permission key.
// A user with `permissions: null` (default) sees everything — full super-admin.
// A user with a `permissions` array only sees/accesses the sections listed.
const ALL_SECTIONS = [
  { key: "dashboard", href: "/admin", label: "Dashboard" },
  { key: "videos", href: "/admin/videos", label: "Videos" },
  { key: "categories", href: "/admin/categories", label: "Categories" },
  { key: "plans", href: "/admin/plans", label: "Membership Plans" },
  { key: "products", href: "/admin/products", label: "Shop Products" },
  { key: "posts", href: "/admin/posts", label: "Community Posts" },
  { key: "funding", href: "/admin/funding", label: "Funding Dashboard" },
  { key: "analytics", href: "/admin/analytics", label: "Visitor Analytics" },
  { key: "users", href: "/admin/users", label: "Users & Roles" },
  { key: "settings", href: "/admin/settings", label: "Site Settings" },
];

export default async function AdminLayout({ children }: { children: React.ReactNode }) {
  const session = await auth();
  if (!session?.user || (session.user as any).role !== "admin") {
    redirect("/login");
  }

  let permissions: string[] | null = null;
  try {
    const raw = (session.user as any).permissions;
    if (raw) permissions = JSON.parse(raw);
  } catch {
    permissions = null;
  }

  const links = permissions ? ALL_SECTIONS.filter((s) => permissions!.includes(s.key)) : ALL_SECTIONS;

  return (
    <div className="max-w-7xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold">Admin Panel</h1>
        <Link href="/" className="text-red-500 text-sm">← Back to site</Link>
      </div>
      <div className="flex gap-6">
        <nav className="w-52 shrink-0 space-y-1 text-sm">
          {links.map((l) => (
            <Link key={l.href} href={l.href} className="block px-3 py-2 rounded hover:bg-neutral-800">
              {l.label}
            </Link>
          ))}
        </nav>
        <div className="flex-1 min-w-0">{children}</div>
      </div>
    </div>
  );
}
