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

import { DemoRunner } from '@/components/demo/demo-runner'
import { Wordmark } from '@/components/brand/logo'
import { ErrorState, LinkButton } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { getDemoState } from '@/lib/services/demo-service'

export const metadata: Metadata = { title: 'Demo mode' }
export const dynamic = 'force-dynamic'

/**
 * Demo Mode lives outside the console layout on purpose: no sidebar, no top bar, no
 * administrative controls — just the story, so a projector shows the argument and
 * nothing else (§52).
 */
export default async function DemoPage({
  searchParams,
}: {
  searchParams: Promise<{ stage?: string }>
}) {
  const user = await getCurrentUser()
  if (!user) redirect('/login?next=/demo')

  const { t, locale } = await getI18n()

  if (!user.permissions.has('demo.run')) {
    return (
      <div className="flex min-h-dvh flex-col items-center justify-center gap-6 px-4">
        <Wordmark locale={locale} />
        <ErrorState
          title={t('common.permissionDenied')}
          body={t('common.permissionDeniedBody')}
          action={
            <LinkButton href="/command-center" variant="secondary" size="sm">
              {t('common.back')}
            </LinkButton>
          }
        />
      </div>
    )
  }

  const { stage } = await searchParams
  const initial = await getDemoState(Math.max(1, Number(stage) || 1), locale, { running: true })

  return <DemoRunner initial={initial} />
}
