import type { Locale } from "@/i18n/routing";

import { Suspense } from "react";

import { UnverifiedEmailBanner } from "@/components/auth/unverified-email-banner";
import { CancelScheduledBanner } from "@/components/billing/cancel-scheduled-banner";
import { PastDueBanner } from "@/components/billing/past-due-banner";
import { DashboardShell } from "@/components/dashboard/dashboard-shell";
import { UsageSection } from "@/components/dashboard/usage-section";
import { Skeleton } from "@/components/ui/skeleton";
import { requireOrgMember } from "@/lib/auth-guards";
import { ensureOrgSubscription } from "@/lib/billing/ensure-subscription";

export default async function DashboardLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  const { session, activeOrganizationId, role } = await requireOrgMember({
    locale: locale as Locale,
  });
  const isUnverified = !session.user.emailVerified;

  // Used by the dashboard-only banners (past-due, cancel-scheduled). The
  // shell itself calls ensureOrgSubscription too — but the helper is
  // idempotent and cached, so the duplicate call is essentially free.
  const sub = await ensureOrgSubscription(activeOrganizationId);

  return (
    <DashboardShell session={session} activeOrganizationId={activeOrganizationId} role={role}>
      {isUnverified && <UnverifiedEmailBanner email={session.user.email} locale={locale} />}
      {sub.status === "past_due" && <PastDueBanner />}
      {sub.cancelAtPeriodEnd && sub.currentPeriodEnd && (
        <CancelScheduledBanner plan={sub.plan} endsAt={sub.currentPeriodEnd} />
      )}
      <Suspense fallback={<Skeleton className="h-20 w-full" />}>
        <UsageSection organizationId={activeOrganizationId} />
      </Suspense>
      {children}
    </DashboardShell>
  );
}
