import type { ReactNode } from "react";

import { AppSidebar } from "@/components/app-sidebar";
import { SiteHeader } from "@/components/site-header";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import { ensureOrgSubscription } from "@/lib/billing/ensure-subscription";
import { listUserOrganizations } from "@/lib/data/organization";

export type DashboardShellProps = {
  session: {
    user: {
      id: string;
      name: string;
      email: string;
      role?: string | null;
      emailVerified?: boolean;
    };
  };
  activeOrganizationId: string;
  role: "owner" | "admin" | "member";
  children: ReactNode;
};

/* Shared sidebar+header chrome for every authenticated route that should
   show the app shell (/dashboard, /settings, /admin, /pricing-when-signed-in).
   Route-specific banners (UnverifiedEmail, PastDue, CancelScheduled, Usage)
   stay in /dashboard/layout.tsx — they don't belong on /settings or /admin. */
export async function DashboardShell({
  session,
  activeOrganizationId,
  role,
  children,
}: DashboardShellProps) {
  const organizations = await listUserOrganizations(session.user.id);
  const sub = await ensureOrgSubscription(activeOrganizationId);

  return (
    <SidebarProvider
      style={
        {
          "--sidebar-width": "calc(var(--spacing) * 72)",
          "--header-height": "calc(var(--spacing) * 12)",
        } as React.CSSProperties
      }
    >
      <AppSidebar
        variant="inset"
        user={session.user}
        organizations={organizations}
        activeOrganizationId={activeOrganizationId}
        currentPlan={sub.plan}
        isOwner={role === "owner"}
      />
      <SidebarInset className="dashboard-bg">
        <SiteHeader />
        <div className="flex flex-1 flex-col">
          <div className="@container/main flex flex-1 flex-col gap-2">
            <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">{children}</div>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  );
}
