import { redirect } from "next/navigation";
import { cookies } from "next/headers";
import { getDashboardUser } from "@/lib/view-as";
import BackendShell from "@/components/backend-shell";
import ViewAsBanner from "./view-as-banner";

// Organizer surface. Any authenticated user may enter (admins included, same
// as the Supabase-era version) -- their data is scoped to their own events
// by the page queries (there's no RLS backstop anymore; every db/queries/*
// function that reads "my" data takes organizerId explicitly, and it's this
// layout's session that supplies it). Platform-admin tools (categories,
// settings, gallery) live under /admin. An admin "viewing as" an organizer
// gets that organizer's id here instead (see src/lib/view-as.ts), read-only.
export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
  const { user, viewingAs } = await getDashboardUser();

  if (!user) {
    redirect("/login");
  }

  const theme = (await cookies()).get("be-theme")?.value === "light" ? "light" : "dark";

  return (
    <BackendShell role="organizer" userEmail={user.email ?? ""} initialTheme={theme}>
      {viewingAs && <ViewAsBanner name={viewingAs.name} email={viewingAs.email} />}
      {children}
    </BackendShell>
  );
}
