import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { GridPhysicsConsole } from '@/components/physics/grid-physics-console'
import { DemoDataBadge, PageHeader } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { listTwins } from '@/lib/services/twin-service'

export const metadata: Metadata = { title: 'Grid Physics' }
export const dynamic = 'force-dynamic'

/**
 * Grid Physics (5.0).
 *
 * The solved side of the platform: an AC load flow with voltage angles and reactive
 * power, the validator that says whether the model is fit to be solved at all, and the
 * contingency scan that answers whether the grid survives losing any single thing.
 *
 * Nothing is solved on the client. Every figure on this page comes from a server route
 * that ran Newton–Raphson and reported its own convergence.
 */
export default async function GridPhysicsPage() {
  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 === 'national')?.code ?? twins[0]?.code ?? ''

  return (
    <>
      <PageHeader
        title={t('gridPhysics.title')}
        subtitle={t('gridPhysics.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('gridPhysics.note')} />}
      />
      <GridPhysicsConsole
        twins={twins.map((twin) => ({
          code: twin.code,
          name: twin.name,
          nameAr: twin.nameAr,
          level: twin.level,
        }))}
        initialTwin={initial}
        canSimulate={user.permissions.has('twin.simulate')}
      />
    </>
  )
}
