import Link from "next/link";
import { Mic, Plus } from "lucide-react";
import { requireAuth } from "@/lib/auth/guards";
import { getEffectivePlan } from "@/lib/billing/subscription";
import { SidebarNav } from "@/components/app/sidebar-nav";
import { UserMenu } from "@/components/app/user-menu";
import { Button } from "@/components/ui/button";

// Authed, DB-backed dashboard — never statically prerender.
export const dynamic = "force-dynamic";

export default async function AppLayout({ children }: { children: React.ReactNode }) {
  const session = await requireAuth();
  const { key: plan } = await getEffectivePlan(
    session.user.id,
    session.session.activeOrganizationId
  );
  const isAdmin = session.user.role === "admin";

  return (
    <div className="flex min-h-screen flex-col">
      <header className="sticky top-0 z-30 flex h-16 items-center justify-between border-b border-border bg-background/85 px-4 backdrop-blur-md md:px-6">
        <Link href="/dashboard" className="flex items-center gap-2.5 font-display font-bold tracking-tight">
          <span className="flex h-9 w-9 items-center justify-center rounded-2xl bg-brand text-brand-foreground">
            <Mic className="h-5 w-5" />
          </span>
          <span className="hidden sm:inline">PodcastYes</span>
        </Link>
        <div className="flex items-center gap-3">
          <Button asChild size="sm">
            <Link href="/episodes/new">
              <Plus className="h-4 w-4" /> New episode
            </Link>
          </Button>
          <UserMenu
            name={session.user.name}
            email={session.user.email}
            image={session.user.image}
            isAdmin={isAdmin}
          />
        </div>
      </header>

      <div className="flex flex-1">
        <aside className="hidden w-64 shrink-0 border-r border-border bg-background md:block">
          <div className="sticky top-16">
            <SidebarNav plan={plan} />
          </div>
        </aside>
        <main className="flex-1 bg-secondary/50">
          <div className="container max-w-6xl py-8 md:py-10">{children}</div>
        </main>
      </div>
    </div>
  );
}
