'use client'

import type { ReactNode } from 'react'

import { LiveGridProvider } from '@/components/providers/live-grid-provider'
import { AppModeProvider } from '@/components/providers/app-mode-provider'
import { useI18n } from '@/components/providers/i18n-provider'
import { MobileNav, Sidebar } from './sidebar'
import { Topbar } from './topbar'
import { ModeBanner } from './mode-banner'
import { CopilotDock } from './copilot-dock'
import type { NavGroup, NavItem } from '@/lib/navigation'
import type { LiveSnapshot } from '@/lib/services/live-snapshot'

/**
 * The console frame.
 *
 * A client component so the sidebar, command bar and every live tile below share one
 * EventSource through `LiveGridProvider`, and one operating mode through
 * `AppModeProvider`. The pages themselves stay server components — only the frame and
 * the individual live islands hydrate.
 *
 * The sidebar sits on the inline-start edge, which resolves to the left in English and
 * the right in Arabic without a second layout (§4).
 */
export function ConsoleShell({
  user,
  groups,
  specials,
  initialSnapshot,
  permissions,
  dataHealth,
  footer,
  children,
}: {
  user: { name: string; nameAr: string; email: string; role: string }
  groups: NavGroup[]
  specials: NavItem[]
  initialSnapshot: LiveSnapshot | null
  permissions: string[]
  dataHealth: number | null
  footer: ReactNode
  children: ReactNode
}) {
  const { t } = useI18n()

  return (
    <AppModeProvider>
      <LiveGridProvider initial={initialSnapshot}>
        <div className="flex min-h-dvh">
          <a
            href="#console-main"
            className="sr-only focus:not-sr-only focus:absolute focus:z-50 focus:m-3 focus:rounded-lg focus:bg-brand focus:px-4 focus:py-2 focus:text-sm focus:font-medium focus:text-on-brand"
          >
            {t('a11y.skipToContent')}
          </a>

          <Sidebar groups={groups} specials={specials} footer={footer} />

          <div className="flex min-w-0 flex-1 flex-col">
            <Topbar
              user={user}
              permissions={permissions}
              dataHealth={dataHealth}
              sidebarTrigger={<MobileNav groups={groups} specials={specials} footer={footer} />}
            />
            <ModeBanner />
            <main id="console-main" className="flex-1 px-4 py-6 sm:px-6 lg:px-8">
              {children}
            </main>
          </div>

          <CopilotDock canSimulate={permissions.includes('twin.simulate')} />
        </div>
      </LiveGridProvider>
    </AppModeProvider>
  )
}
