import type { Metadata } from 'next'
import Link from 'next/link'

import { PermissionGate } from '@/components/console/permission-gate'
import { AgentFlow } from '@/components/intelligence/agent-flow'
import { CascadeTimeline } from '@/components/intelligence/cascade-timeline'
import { FutureBranches } from '@/components/intelligence/future-branches'
import { JudgeMode } from '@/components/intelligence/judge-mode'
import {
  OperatingEnvelopePanel,
  PhysicsValidationPanel,
} from '@/components/intelligence/physics-panel'
import { RootCausePanel } from '@/components/intelligence/root-cause-panel'
import { TrustDialog } from '@/components/intelligence/trust-dialog'
import { UncertaintyPanel } from '@/components/intelligence/uncertainty-panel'
import { CascadeTree } from '@/components/intelligence/cascade-tree'
import { StrategyTable } from '@/components/intelligence/strategy-table'
import { WeakSignalsPanel } from '@/components/intelligence/weak-signals-panel'
import { NationalMap } from '@/components/map/national-map'
import {
  Badge,
  DemoDataBadge,
  ErrorState,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
  SectionTitle,
  StatCard,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import { demoPerturbation } from '@/lib/demo/config'
import { analyseAsset, futureBranches, pickFocusAsset } from '@/lib/services/intelligence-service'
import { getMapData } from '@/lib/services/map-service'

export const metadata: Metadata = { title: 'Hackathon Mode' }
export const dynamic = 'force-dynamic'

/**
 * Hackathon Mode (§46) with Judge Mode inside it (§47).
 *
 * One page that carries the whole journey — observe, understand, predict, simulate,
 * prevent — so a panel with three minutes does not have to navigate a console they have
 * never seen. It runs under the demo scenario by default, which is the only way the
 * story is legible in January; every figure on it is still computed live.
 */
const STEPS = ['observe', 'understand', 'predict', 'simulate', 'prevent'] as const

export default async function HackathonPage({
  searchParams,
}: {
  searchParams: Promise<{ asset?: string; live?: string }>
}) {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()
  if (!user?.permissions.has('presentation.use')) return <PermissionGate />

  const { asset, live } = await searchParams
  // The demo scenario is the default because the failure story is a peak-summer event;
  // `?live=1` drops it and runs the page against present conditions instead.
  const perturbation = live === '1' ? undefined : demoPerturbation()

  const assetCode = asset?.trim() || (await pickFocusAsset({ perturbation }))
  const intel = assetCode
    ? await analyseAsset(assetCode, { perturbation, includeLeadTime: true })
    : null

  if (!intel) {
    return (
      <>
        <PageHeader title={t('hackathon.title')} subtitle={t('hackathon.subtitle')} />
        <ErrorState title={t('errors.NOT_FOUND')} body={assetCode ?? ''} />
      </>
    )
  }

  const [branches, map] = await Promise.all([futureBranches(intel), getMapData({ ts: intel.ts })])
  const { orchestration } = intel
  const dna = intel.dnaMatches[0]

  return (
    <>
      <PageHeader
        title={t('hackathon.title')}
        subtitle={t('hackathon.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />}
        action={
          <div className="flex min-w-0 max-w-full flex-wrap items-center gap-3">
            {/* The button a judge reaches for (§51, §109). */}
            <TrustDialog assetCode={intel.assetCode} label={t('common.proveIt')} />
            <Link
              href={`/war-room?asset=${encodeURIComponent(intel.assetCode)}`}
              className="text-xs font-medium text-brand hover:underline"
            >
              {t('warRoom.title')}
            </Link>
          </div>
        }
      />

      {/* The journey, named, so a reader knows which stage each panel belongs to. */}
      <ol className="mb-6 flex flex-wrap items-center gap-2">
        {STEPS.map((step, index) => (
          <li key={step} className="flex items-center gap-2">
            <span className="rounded-full border border-brand/35 bg-brand/8 px-3 py-1 text-[11px] font-medium text-brand">
              {formatNumber(locale, index + 1)}. {t(`hackathon.step.${step}`)}
            </span>
            {index < STEPS.length - 1 ? (
              <span aria-hidden className="text-text-faint">
                →
              </span>
            ) : null}
          </li>
        ))}
      </ol>

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard
          label={t('commandCenter.cards.gridStability')}
          value={formatNumber(locale, intel.snapshot.stabilityIndex, { maximumFractionDigits: 1 })}
          state={intel.snapshot.state}
        />
        <StatCard
          label={t('aiOps.unifiedRisk')}
          value={formatNumber(locale, orchestration.unifiedRisk, { maximumFractionDigits: 0 })}
          unit="%"
          emphasis
          state={
            orchestration.unifiedRisk >= 70
              ? 'critical'
              : orchestration.unifiedRisk >= 45
                ? 'warning'
                : 'normal'
          }
          hint={intel.assetCode}
        />
        <StatCard
          label={t('dna.topMatches')}
          value={dna ? formatNumber(locale, dna.similarity, { maximumFractionDigits: 0 }) : '—'}
          unit="%"
          hint={dna?.pattern.code}
          href="/failure-dna"
        />
        <StatCard
          label={t('preventionWindow.eventIn')}
          value={
            intel.prediction.etaMinutes === null
              ? '—'
              : formatNumber(locale, intel.prediction.etaMinutes)
          }
          unit={t('common.minutes')}
          hint={t('preventionWindow.estimated')}
          state={intel.prediction.etaMinutes !== null && intel.prediction.etaMinutes < 60 ? 'critical' : 'watch'}
        />
      </div>

      {/* 1. Observe */}
      <div className="mt-6 grid gap-4 lg:grid-cols-[1fr_22rem]">
        <Panel>
          <PanelHeader title={t('map.title')} subtitle={t('map.subtitle')} />
          <PanelBody className="pt-0">
            <NationalMap regions={map.regions} assets={map.assets} compact />
          </PanelBody>
        </Panel>
        <WeakSignalsPanel result={intel.weakSignals} leadMinutes={intel.leadTime?.leadMinutes ?? null} />
      </div>

      {/* Traditional versus NABDH (§34) */}
      {intel.leadTime ? (
        <Panel className="mt-6">
          <PanelHeader
            title={t('hackathon.traditionalTitle')}
            subtitle={t('hackathon.leadTimeHint')}
            action={<Badge tone="accent">{t('futures.estimate')}</Badge>}
          />
          <PanelBody className="pt-0">
            <div className="grid gap-3 sm:grid-cols-3">
              <div className="rounded-lg border border-border bg-surface-2/50 p-3">
                <SectionTitle>{t('hackathon.nabdhDetection')}</SectionTitle>
                <p className="tnum mt-1 text-xl font-semibold text-brand">
                  {intel.leadTime.patternAtMin === null
                    ? '—'
                    : `${formatNumber(locale, Math.abs(intel.leadTime.patternAtMin))} ${t('common.minutes')}`}
                </p>
                <p className="mt-0.5 text-[10px] text-text-faint">{t('weakSignals.patternFound')}</p>
              </div>
              <div className="rounded-lg border border-border bg-surface-2/50 p-3">
                <SectionTitle>{t('hackathon.traditionalAlarm')}</SectionTitle>
                <p className="tnum mt-1 text-xl font-semibold text-text-muted">
                  {intel.leadTime.alarmAtMin === null
                    ? '—'
                    : `${formatNumber(locale, Math.abs(intel.leadTime.alarmAtMin))} ${t('common.minutes')}`}
                </p>
                <p className="mt-0.5 text-[10px] text-text-faint">{t('weakSignals.traditionalSilent')}</p>
              </div>
              <div className="rounded-lg border border-normal/35 bg-normal/8 p-3">
                <SectionTitle>{t('hackathon.leadTime')}</SectionTitle>
                <p className="tnum mt-1 text-xl font-semibold text-normal">
                  {formatNumber(locale, intel.leadTime.leadMinutes)} {t('common.minutes')}
                </p>
                <p className="mt-0.5 text-[10px] text-text-faint">{t('common.simulated')}</p>
              </div>
            </div>
          </PanelBody>
        </Panel>
      ) : null}

      {/* 2. Understand */}
      <div className="mt-6 grid gap-4 lg:grid-cols-2">
        <RootCausePanel result={intel.rootCause} />
        <AgentFlow flow={orchestration.flow} />
      </div>

      {/* 3. Predict and 4. Simulate */}
      {/* 4.0: how confident, and whether the plan is physically allowed (§14, §11). On
          this page above all — a judge is here to interrogate the claim, not to admire
          it. */}
      <div className="mt-6 grid gap-4 lg:grid-cols-2">
        <div className="min-w-0">
          <UncertaintyPanel view={intel.uncertainty} />
        </div>
        <div className="min-w-0 space-y-4">
          <OperatingEnvelopePanel envelope={intel.envelope} />
          <PhysicsValidationPanel
            verdict={intel.physics.verdict}
            checks={intel.physics.checks}
            summary={intel.physics.summary}
            summaryAr={intel.physics.summaryAr}
            confidence={intel.physics.confidence}
          />
        </div>
      </div>

      <CascadeTimeline result={intel.cascade} className="mt-6" />

      <div className="mt-6">
        <CascadeTree
          tree={intel.cascadeTree}
          breakpoints={intel.breakpoints}
          contained={intel.cascade.affectedAssets <= 1}
        />
      </div>
      <FutureBranches branches={branches} horizonMin={intel.prediction.horizonMin} className="mt-6" />

      {/* 5. Prevent */}
      <StrategyTable strategies={intel.optimisation.strategies} className="mt-6" />

      <div className="mt-6">
        <JudgeMode defaultAsset={intel.assetCode} />
      </div>
    </>
  )
}
