import { auth0 } from "@/lib/auth0"
import { cookies } from "next/headers"
import { redirect } from "next/navigation"
import { ReactNode } from "react"
import { ViewModeProvider } from "../app/ViewModeContext"
import { PrivacyModeProvider } from "../app/PrivacyModeContext"
import { DashboardShell } from "@/components/dashboard-shell"
import { getCachedDashboardData } from "@/lib/cached-dashboard-data"

export default async function DashboardLayout({ children }: { children: ReactNode }) {
  const session = await auth0.getSession()
  if (!session) return null

  const [data, cookieStore] = await Promise.all([
    getCachedDashboardData(session.user.sub),
    cookies(),
  ])
  if (!data.onboardingCompleted) {
    redirect("/onboarding")
  }

  const serverOrgId = cookieStore.get("currentOrganizationId")?.value ?? null

  return (
    <ViewModeProvider
      user={session.user}
      initialOrganizations={data.organizations}
      serverOrgId={serverOrgId}
    >
      <PrivacyModeProvider
        userId={session.user.sub}
        initialPrivacyMode={data.privacyMode}
        initialCanUsePrivacyMode={data.canUsePrivacyMode}
      >
        <DashboardShell user={session.user} initialSubscription={data.subscription}>
          {children}
        </DashboardShell>
      </PrivacyModeProvider>
    </ViewModeProvider>
  )
}
