import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import VolunteerNav from "@/components/VolunteerNav";
import Topbar from "@/components/Topbar";

export default async function PortalLayout({ children }: { children: React.ReactNode }) {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) redirect("/login");

  const { data: profile } = await supabase
    .from("profiles")
    .select("full_name, email, role")
    .eq("id", user.id)
    .single();

  if (!profile) {
    await supabase.auth.signOut();
    redirect("/login");
  }
  // Admins belong in the admin dashboard, not the volunteer portal.
  if (profile.role === "admin") {
    redirect("/");
  }

  return (
    <div className="flex min-h-screen bg-sand">
      <VolunteerNav />
      <div className="flex min-w-0 flex-1 flex-col">
        <Topbar
          name={profile.full_name || "Volunteer"}
          email={profile.email}
          profileHref="/portal/profile"
        />
        <main className="flex-1 overflow-y-auto p-6">{children}</main>
      </div>
    </div>
  );
}
