import type { Metadata } from 'next'

import { PageHeader, Panel, PanelBody, PanelHeader, SectionTitle } from '@/components/ui/display'
import { getI18n } from '@/lib/i18n/server'
import { prisma } from '@/lib/db'
import { formatNumber } from '@/lib/i18n/translate'

export const metadata: Metadata = { title: 'Why NABDH?' }
export const dynamic = 'force-dynamic'

const PILLARS = ['dna', 'timeMachine', 'explainable', 'preventive', 'copilot'] as const
const COMPARISON = ['detection', 'explanation', 'future', 'action'] as const

/**
 * The innovation summary (§53).
 *
 * Its job is to make the difference between "monitoring" and "prediction" concrete, so
 * the lead-time figure comes from the incident record rather than from a slide.
 */
export default async function WhyNabdhPage() {
  const { t, locale } = await getI18n()

  const [incidents, patternCount, assetCount] = await Promise.all([
    prisma.incident.findMany({
      where: { nabdhLeadTimeMin: { gt: 0 } },
      select: { nabdhLeadTimeMin: true, thresholdLeadMin: true },
    }),
    prisma.failurePattern.count(),
    prisma.asset.count(),
  ])

  const averageAdvantage = incidents.length
    ? incidents.reduce(
        (sum, incident) => sum + (incident.nabdhLeadTimeMin - incident.thresholdLeadMin),
        0,
      ) / incidents.length
    : 0

  return (
    <>
      <PageHeader title={t('why.title')} subtitle={t('why.subtitle')} />

      {/* The two operating models, side by side */}
      <div className="grid gap-4 lg:grid-cols-2">
        <Panel className="border-critical/25 p-6">
          <SectionTitle>{t('why.traditional')}</SectionTitle>
          <p className="mt-4 font-mono text-base text-critical">{t('why.traditionalFlow')}</p>
          <p className="mt-4 text-sm leading-relaxed text-text-muted">
            {t('landing.problem.reactiveNote')}
          </p>
        </Panel>

        <Panel glow className="p-6">
          <SectionTitle>{t('why.nabdh')}</SectionTitle>
          <p className="mt-4 font-mono text-base text-brand">{t('why.nabdhFlow')}</p>
          <p className="mt-4 text-sm leading-relaxed text-text-muted">
            {t('landing.solution.lead')}
          </p>
          <p className="tnum mt-5 border-t border-border pt-4 text-sm text-text">
            {t('incidents.replay.leadAdvantage', {
              minutes: formatNumber(locale, averageAdvantage, { maximumFractionDigits: 0 }),
            })}
          </p>
        </Panel>
      </div>

      {/* Pillars */}
      <div className="mt-6 grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
        {PILLARS.map((pillar, index) => (
          <Panel key={pillar} className="p-5">
            <span className="tnum text-xs font-semibold text-brand">0{index + 1}</span>
            <h2 className="mt-2.5 text-sm font-semibold text-text">
              {t(`why.pillars.${pillar}`)}
            </h2>
            <p className="mt-2 text-xs leading-relaxed text-text-muted">
              {t(`why.pillars.${pillar}Body`)}
            </p>
          </Panel>
        ))}
      </div>

      {/* Point-by-point comparison */}
      <Panel className="mt-6">
        <PanelHeader title={t('why.title')} subtitle={t('common.taglineLong')} />
        <PanelBody>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <caption className="sr-only">{t('why.title')}</caption>
              <thead>
                <tr className="border-b border-border text-[11px] uppercase tracking-wide text-text-faint">
                  <th scope="col" className="px-3 py-2 text-start">
                    {t('why.comparison.aspect')}
                  </th>
                  <th scope="col" className="px-3 py-2 text-start">
                    {t('why.traditional')}
                  </th>
                  <th scope="col" className="px-3 py-2 text-start text-brand">
                    {t('why.nabdh')}
                  </th>
                </tr>
              </thead>
              <tbody>
                {COMPARISON.map((aspect) => (
                  <tr key={aspect} className="border-b border-border/60">
                    <th scope="row" className="px-3 py-3 text-start font-medium text-text">
                      {t(`why.comparison.${aspect}`)}
                    </th>
                    <td className="px-3 py-3 text-text-muted">
                      {t(`why.comparison.${aspect}Traditional`)}
                    </td>
                    <td className="px-3 py-3 text-text">
                      {t(`why.comparison.${aspect}Nabdh`)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </PanelBody>
      </Panel>

      <div className="mt-6 grid gap-3 sm:grid-cols-3">
        <Panel className="p-5">
          <p className="tnum text-3xl font-semibold text-brand">
            {formatNumber(locale, assetCount)}
          </p>
          <p className="mt-1 text-xs text-text-muted">{t('landing.stats.assets')}</p>
        </Panel>
        <Panel className="p-5">
          <p className="tnum text-3xl font-semibold text-brand">
            {formatNumber(locale, patternCount)}
          </p>
          <p className="mt-1 text-xs text-text-muted">{t('landing.stats.dnaPatterns')}</p>
        </Panel>
        <Panel className="p-5">
          <p className="tnum text-3xl font-semibold text-brand">
            {formatNumber(locale, averageAdvantage, { maximumFractionDigits: 0 })}
            <span className="ms-1 text-sm font-normal text-text-muted">
              {t('common.units.minutes')}
            </span>
          </p>
          <p className="mt-1 text-xs text-text-muted">{t('landing.stats.leadTime')}</p>
        </Panel>
      </div>
    </>
  )
}
