import { getCookie } from '../../lib/cookies'
import { cn } from '../../lib/utils'
import { LayoutProvider } from '../../context/layout-provider'
import { SearchProvider } from '../../context/search-provider'
import { SidebarInset, SidebarProvider } from '../ui/sidebar'
import { AppSidebar } from './app-sidebar'
import { SkipToMain } from '../skip-to-main'
import { type SidebarData } from './types'

type AuthenticatedLayoutProps = {
  children?: React.ReactNode
  /** Called when user confirms sign-out. Pass your app's logout handler here. */
  onSignOut?: () => void
  /** Override sidebar navigation data (nav groups, teams, user). */
  sidebarData?: SidebarData
  /** URL for the user profile / settings page shown in the sidebar user menu. */
  profileUrl?: string
}

export function AuthenticatedLayout({ children, onSignOut, sidebarData, profileUrl }: AuthenticatedLayoutProps) {
  const defaultOpen = getCookie('sidebar_state') !== 'false'
  return (
    <SearchProvider>
      <LayoutProvider>
        <SidebarProvider defaultOpen={defaultOpen}>
          <SkipToMain />
          <AppSidebar onSignOut={onSignOut} sidebarData={sidebarData} profileUrl={profileUrl} />
          <SidebarInset
            className={cn(
              // Set content container, so we can use container queries
              '@container/content',

              // If layout is fixed, set the height
              // to 100svh to prevent overflow
              'has-data-[layout=fixed]:h-svh',

              // If layout is fixed and sidebar is inset,
              // set the height to 100svh - spacing (total margins) to prevent overflow
              'peer-data-[variant=inset]:has-data-[layout=fixed]:h-[calc(100svh-(var(--spacing)*4))]'
            )}
          >
            {children}
          </SidebarInset>
        </SidebarProvider>
      </LayoutProvider>
    </SearchProvider>
  )
}
