import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { CompareFutures } from '@/components/compare/compare-futures'
import { DemoDataBadge, PageHeader } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { GRID_SCENARIOS, SCENARIO_KEYS } from '@/lib/engine/grid-scenarios'
import { listTwins } from '@/lib/services/twin-service'

export const metadata: Metadata = { title: 'Compare Futures' }
export const dynamic = 'force-dynamic'

/**
 * Compare futures (5.0 §11–§12).
 *
 * The same grid, at the same instant, under two or three decisions — drawn side by side
 * with one shared camera, and differenced by the server rather than by the browser.
 *
 * Every pane is a sandbox solve. Nothing this page produces is applied to anything.
 */
export default async function CompareFuturesPage() {
  const user = await getCurrentUser()
  const { t } = await getI18n()
  if (!user?.permissions.has('twin.read')) return <PermissionGate />

  const twins = await listTwins()
  const initial = twins.find((twin) => twin.level === 'region')?.code ?? twins[0]?.code ?? ''

  return (
    <>
      <PageHeader
        title={t('compare.title')}
        subtitle={t('compare.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('compare.simulated')} />}
      />
      <CompareFutures
        twins={twins.map((twin) => ({ code: twin.code, name: twin.name, nameAr: twin.nameAr }))}
        scenarios={SCENARIO_KEYS.map((key) => ({
          key,
          label: GRID_SCENARIOS[key].label,
          labelAr: GRID_SCENARIOS[key].labelAr,
        }))}
        initialTwin={initial}
        canSimulate={user.permissions.has('twin.simulate')}
      />
    </>
  )
}
