import type { Metadata } from 'next'
import { redirect } from 'next/navigation'

import { PermissionGate } from '@/components/console/permission-gate'
import { LiveGridConsole } from '@/components/live-grid/live-grid-console'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { buildInitialGrid } from '@/lib/services/live-grid-service'

export const metadata: Metadata = { title: 'NABDH — Live 3D Grid' }
export const dynamic = 'force-dynamic'

/**
 * The immersive Live 3D Grid (§96).
 *
 * Outside the console layout on purpose: no sidebar, no command bar, nothing to click by
 * accident during a presentation. It opens on a stable grid and every scenario control is
 * one press away, so a judge can pick a heat wave or a demand surge and watch the scene
 * answer inside a minute (§97).
 */
export default async function LiveGridDemoPage({
  searchParams,
}: {
  searchParams: Promise<{ twin?: string; scenario?: string }>
}) {
  const user = await getCurrentUser()
  if (!user) redirect('/login')
  if (!user.permissions.has('twin.read')) return <PermissionGate />

  const { t } = await getI18n()
  const { twin, scenario } = await searchParams

  // Pinned to the platform's demonstration instant — a summer-peak afternoon — the same
  // clock every other demo surface runs on. Without it a presentation held at midnight
  // would show a grid with reserve to spare and an optimiser correctly recommending
  // nothing, which is true and useless.
  const initial = await buildInitialGrid({
    twinCode: twin ?? 'TWIN-RGN-RYD',
    scenario: scenario ?? null,
    demoClock: true,
    canSimulate: user.permissions.has('twin.simulate'),
  })
  if (!initial) return <PermissionGate />

  return (
    <main className="min-h-dvh bg-surface px-3 py-3 sm:px-5" data-testid="live-grid-immersive">
      <header className="mb-3 flex flex-wrap items-baseline justify-between gap-3">
        <div>
          <h1 className="text-xl font-semibold tracking-tight text-text">{t('liveGrid.title')}</h1>
          <p className="text-[12px] text-text-muted">{t('liveGrid.subtitle')}</p>
        </div>
        <p className="max-w-md text-[11px] leading-relaxed text-text-faint">{t('liveGrid.readOnly')}</p>
      </header>

      <LiveGridConsole initial={initial} wallMode />
    </main>
  )
}
