import Link from 'next/link'

import { LogoMark, Wordmark } from '@/components/brand/logo'
import { LanguageSwitcher } from '@/components/site/language-switcher'
import { Badge, DemoDataBadge, LinkButton, Panel, SectionTitle } from '@/components/ui/display'
import { prisma } from '@/lib/db'
import { getI18n } from '@/lib/i18n/server'
import { REGIONS } from '@/lib/data/regions'
import { DNA_FEATURES } from '@/lib/engine/dna'
import { cn } from '@/lib/cn'

export const dynamic = 'force-dynamic'

const SECTIONS = [
  'problem',
  'solution',
  'how',
  'dna',
  'timeMachine',
  'prevention',
  'impact',
  'architecture',
  'team',
] as const

export default async function LandingPage() {
  const { t, locale } = await getI18n()

  // Real figures from the seeded grid — the landing page should not quote numbers the
  // product cannot back up.
  const [assetCount, patternCount, topPattern, incidentStats] = await Promise.all([
    prisma.asset.count(),
    prisma.failurePattern.count(),
    prisma.failurePattern.findUnique({ where: { code: 'FP-387' }, include: { dna: true } }),
    prisma.incident.aggregate({
      _avg: { nabdhLeadTimeMin: true },
      where: { nabdhLeadTimeMin: { gt: 0 } },
    }),
  ])

  const averageLead = Math.round(incidentStats._avg.nabdhLeadTimeMin ?? 0)

  return (
    <div className="min-h-dvh bg-base">
      <a
        href="#main"
        className="sr-only focus:not-sr-only focus:absolute focus:z-50 focus:m-3 focus:rounded-lg focus:bg-brand focus:px-4 focus:py-2 focus:text-sm focus:font-medium focus:text-on-brand"
      >
        {t('a11y.skipToContent')}
      </a>

      {/* ── Header ─────────────────────────────────────────────────────────── */}
      <header className="sticky top-0 z-40 border-b border-border/70 bg-base/85 backdrop-blur-xl">
        <div className="mx-auto flex h-16 max-w-7xl items-center justify-between gap-4 px-4 sm:px-6">
          <Link href="/" className="shrink-0">
            <Wordmark locale={locale} />
          </Link>

          <nav
            aria-label={t('a11y.mainNavigation')}
            className="hidden items-center gap-1 lg:flex"
          >
            {SECTIONS.slice(0, 6).map((section) => (
              <a
                key={section}
                href={`#${section}`}
                className="rounded-md px-3 py-1.5 text-xs font-medium text-text-muted transition-colors hover:bg-surface-2 hover:text-text"
              >
                {t(`landing.nav.${section}`)}
              </a>
            ))}
          </nav>

          <div className="flex items-center gap-2">
            <LanguageSwitcher compact />
            <LinkButton href="/login" variant="secondary" size="sm">
              {t('landing.hero.signIn')}
            </LinkButton>
          </div>
        </div>
      </header>

      <main id="main">
        {/* ── Hero ─────────────────────────────────────────────────────────── */}
        <section className="relative overflow-hidden border-b border-border">
          <div className="nabdh-grid-bg nabdh-radial absolute inset-0" aria-hidden />
          <div className="absolute inset-x-0 bottom-0 h-px bg-gradient-to-r from-transparent via-brand/40 to-transparent" aria-hidden />

          <div className="relative mx-auto max-w-7xl px-4 py-20 sm:px-6 sm:py-28">
            <div className="grid items-center gap-12 lg:grid-cols-[1.15fr_1fr]">
              <div>
                <Badge tone="brand" dot className="mb-6">
                  {t('landing.hero.eyebrow')}
                </Badge>

                <h1 className="text-5xl font-semibold tracking-tight text-text sm:text-7xl">
                  {t('landing.hero.title')}
                </h1>
                <p className="mt-2 text-2xl font-light tracking-[0.2em] text-text-faint sm:text-3xl">
                  {t('landing.hero.titleLocal')}
                </p>

                <p className="mt-6 text-xl font-medium text-brand sm:text-2xl">
                  {t('landing.hero.subtitle')}
                </p>

                <p className="mt-5 max-w-xl text-base leading-relaxed text-text-muted">
                  {t('landing.hero.body')}
                </p>

                <div className="mt-9 flex flex-wrap items-center gap-3">
                  <LinkButton href="/login" size="lg">
                    {t('landing.hero.explore')}
                  </LinkButton>
                  <LinkButton href="/demo" variant="outline" size="lg">
                    {t('landing.hero.launchDemo')}
                  </LinkButton>
                </div>

                <div className="mt-10 grid max-w-lg grid-cols-2 gap-x-8 gap-y-5 sm:grid-cols-4">
                  <HeroStat value={assetCount} label={t('landing.stats.assets')} />
                  <HeroStat value={REGIONS.length} label={t('landing.stats.regions')} />
                  <HeroStat value={patternCount} label={t('landing.stats.dnaPatterns')} />
                  <HeroStat
                    value={averageLead}
                    suffix={t('common.units.minutes')}
                    label={t('landing.stats.leadTime')}
                  />
                </div>
              </div>

              <HeroVisual t={t} />
            </div>

            <div className="mt-14 flex flex-wrap items-center gap-3">
              <DemoDataBadge label={t('common.simulatedFull')} title={t('common.simulatedTooltip')} />
              <p className="max-w-2xl text-xs leading-relaxed text-text-faint">
                {t('common.simulatedTooltip')}
              </p>
            </div>
          </div>
        </section>

        {/* ── Problem ──────────────────────────────────────────────────────── */}
        <Section id="problem" eyebrow={t('landing.nav.problem')} title={t('landing.problem.title')}>
          <div className="grid gap-10 lg:grid-cols-[1.2fr_1fr]">
            <div>
              <p className="text-lg leading-relaxed text-text">{t('landing.problem.lead')}</p>
              <p className="mt-5 leading-relaxed text-text-muted">{t('landing.problem.body')}</p>

              <ul className="mt-8 grid gap-2 sm:grid-cols-2">
                {(['demand', 'surges', 'renewables', 'weather', 'ageing', 'chain'] as const).map(
                  (item) => (
                    <li
                      key={item}
                      className="flex items-start gap-2.5 rounded-lg border border-border bg-surface/50 px-3 py-2.5 text-sm text-text-muted"
                    >
                      <span className="mt-1.5 size-1.5 shrink-0 rounded-full bg-warning" />
                      {t(`landing.problem.items.${item}`)}
                    </li>
                  ),
                )}
              </ul>
            </div>

            <Panel className="self-start p-6">
              <SectionTitle>{t('why.traditional')}</SectionTitle>
              <p className="mt-4 font-mono text-sm text-critical">{t('landing.problem.reactive')}</p>
              <div className="mt-5 h-px bg-border" />
              <p className="mt-4 text-sm leading-relaxed text-text-muted">
                {t('landing.problem.reactiveNote')}
              </p>
            </Panel>
          </div>
        </Section>

        {/* ── Solution ─────────────────────────────────────────────────────── */}
        <Section
          id="solution"
          eyebrow={t('landing.nav.solution')}
          title={t('landing.solution.title')}
          tinted
        >
          <p className="max-w-3xl text-lg leading-relaxed text-text">{t('landing.solution.lead')}</p>

          <div className="mt-10 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
            {(['q1', 'q2', 'q3', 'q4'] as const).map((key, index) => (
              <Panel key={key} className="p-6">
                <span className="tnum text-xs font-semibold text-brand">0{index + 1}</span>
                <h3 className="mt-3 text-base font-semibold text-text">
                  {t(`landing.solution.${key}`)}
                </h3>
                <p className="mt-2.5 text-sm leading-relaxed text-text-muted">
                  {t(`landing.solution.${key}Body`)}
                </p>
              </Panel>
            ))}
          </div>

          <div className="mt-10 rounded-[--radius-panel] border border-brand/30 bg-brand/8 px-6 py-5">
            <p className="text-center font-mono text-sm text-brand sm:text-base">
              {t('landing.solution.proactive')}
            </p>
          </div>
        </Section>

        {/* ── How it works ─────────────────────────────────────────────────── */}
        <Section id="how" eyebrow={t('landing.nav.how')} title={t('landing.how.title')}>
          <p className="max-w-3xl text-lg leading-relaxed text-text">{t('landing.how.lead')}</p>
          <p className="mt-4 max-w-3xl leading-relaxed text-text-muted">{t('landing.how.body')}</p>

          <ol className="mt-10 grid gap-4 lg:grid-cols-5">
            {(['step1', 'step2', 'step3', 'step4', 'step5'] as const).map((step, index) => (
              <li key={step} className="relative">
                <Panel className="h-full p-5">
                  <div className="flex size-8 items-center justify-center rounded-lg border border-brand/30 bg-brand/10 text-xs font-semibold text-brand">
                    {index + 1}
                  </div>
                  <h3 className="mt-4 text-sm font-semibold text-text">{t(`landing.how.${step}`)}</h3>
                  <p className="mt-2 text-xs leading-relaxed text-text-muted">
                    {t(`landing.how.${step}Body`)}
                  </p>
                </Panel>
              </li>
            ))}
          </ol>
        </Section>

        {/* ── Failure DNA ──────────────────────────────────────────────────── */}
        <Section id="dna" eyebrow={t('landing.nav.dna')} title={t('landing.dna.title')} tinted>
          <div className="grid gap-10 lg:grid-cols-[1fr_1.1fr]">
            <div>
              <p className="text-lg leading-relaxed text-text">{t('landing.dna.lead')}</p>
              <p className="mt-5 leading-relaxed text-text-muted">{t('landing.dna.body')}</p>
              <div className="mt-7 flex flex-wrap gap-2">
                <Badge tone="brand">{t('landing.dna.dimensions')}</Badge>
                <Badge tone="info">{t('landing.dna.inspectable')}</Badge>
                <Badge tone="accent">{t('landing.dna.deterministic')}</Badge>
              </div>
            </div>

            {topPattern?.dna ? (
              <Panel className="overflow-hidden">
                <div className="border-b border-border px-5 py-3.5">
                  <p className="text-xs text-text-muted">{t('landing.dna.example')}</p>
                  <p className="mt-1.5 text-sm font-semibold text-text">
                    {locale === 'ar' ? topPattern.nameAr : topPattern.name}
                  </p>
                </div>
                <div className="space-y-2 p-5">
                  {DNA_FEATURES.map((feature) => {
                    const value = topPattern.dna![feature] as number
                    return (
                      <div key={feature} className="flex items-center gap-3">
                        <span className="w-36 shrink-0 truncate text-[11px] text-text-muted">
                          {t(`dnaFeature.${feature}`)}
                        </span>
                        <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-surface-3">
                          <div
                            className="h-full rounded-full bg-gradient-to-r from-brand/60 to-brand"
                            style={{ width: `${Math.round(value * 100)}%` }}
                          />
                        </div>
                        <span className="tnum w-10 shrink-0 text-end text-[11px] text-text-faint">
                          {(value * 100).toFixed(0)}%
                        </span>
                      </div>
                    )
                  })}
                </div>
              </Panel>
            ) : null}
          </div>
        </Section>

        {/* ── Energy Time Machine ──────────────────────────────────────────── */}
        <Section
          id="timeMachine"
          eyebrow={t('landing.nav.timeMachine')}
          title={t('landing.timeMachine.title')}
        >
          <div className="grid gap-10 lg:grid-cols-[1fr_1.15fr]">
            <div>
              <p className="text-lg leading-relaxed text-text">{t('landing.timeMachine.lead')}</p>
              <p className="mt-5 leading-relaxed text-text-muted">{t('landing.timeMachine.body')}</p>
            </div>
            <TimeMachineVisual t={t} />
          </div>
        </Section>

        {/* ── Prevention ───────────────────────────────────────────────────── */}
        <Section
          id="prevention"
          eyebrow={t('landing.nav.prevention')}
          title={t('landing.prevention.title')}
          tinted
        >
          <div className="grid gap-10 lg:grid-cols-[1.1fr_1fr]">
            <div>
              <p className="text-lg leading-relaxed text-text">{t('landing.prevention.lead')}</p>
              <p className="mt-5 leading-relaxed text-text-muted">{t('landing.prevention.body')}</p>
              <p className="mt-7 rounded-lg border border-brand/30 bg-brand/8 px-4 py-3 text-sm font-medium text-brand">
                {t('landing.prevention.simulateFirst')}
              </p>
            </div>
            <PreventionVisual t={t} />
          </div>
        </Section>

        {/* ── Impact ───────────────────────────────────────────────────────── */}
        <Section id="impact" eyebrow={t('landing.nav.impact')} title={t('landing.impact.title')}>
          <p className="max-w-3xl text-lg leading-relaxed text-text">{t('landing.impact.lead')}</p>
          <p className="mt-3 max-w-3xl text-sm leading-relaxed text-watch">{t('landing.impact.note')}</p>

          <div className="mt-10 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
            {(
              [
                'downtime',
                'detection',
                'utilisation',
                'maintenance',
                'reliability',
                'renewables',
                'decisions',
              ] as const
            ).map((item) => (
              <div
                key={item}
                className="rounded-[--radius-panel] border border-border bg-surface/60 px-4 py-4"
              >
                <span className="block size-1.5 rounded-full bg-brand" />
                <p className="mt-3 text-sm leading-relaxed text-text">
                  {t(`landing.impact.items.${item}`)}
                </p>
              </div>
            ))}
          </div>
        </Section>

        {/* ── Architecture ─────────────────────────────────────────────────── */}
        <Section
          id="architecture"
          eyebrow={t('landing.nav.architecture')}
          title={t('landing.architecture.title')}
          tinted
        >
          <p className="max-w-3xl text-lg leading-relaxed text-text">
            {t('landing.architecture.lead')}
          </p>
          <p className="mt-4 max-w-3xl leading-relaxed text-text-muted">
            {t('landing.architecture.body')}
          </p>

          <div className="mt-10 space-y-3">
            {(['sources', 'ingestion', 'intelligence', 'experience'] as const).map((layer, index) => (
              <Panel key={layer} className="p-5">
                <div className="flex flex-wrap items-baseline gap-x-4 gap-y-1">
                  <span className="tnum text-xs font-semibold text-brand">0{index + 1}</span>
                  <h3 className="text-sm font-semibold text-text">
                    {t(`landing.architecture.layers.${layer}`)}
                  </h3>
                </div>
                <p className="mt-2 text-sm leading-relaxed text-text-muted">
                  {t(`landing.architecture.layers.${layer}Body`)}
                </p>
              </Panel>
            ))}
          </div>
        </Section>

        {/* ── Closing ──────────────────────────────────────────────────────── */}
        <Section id="team" eyebrow={t('landing.nav.team')} title={t('landing.team.title')}>
          <p className="max-w-3xl text-lg leading-relaxed text-text-muted">
            {t('landing.team.body')}
          </p>
          <div className="mt-8 flex flex-wrap gap-3">
            <LinkButton href="/login" size="lg">
              {t('landing.team.openConsole')}
            </LinkButton>
            <LinkButton href="/why-nabdh" variant="secondary" size="lg">
              {t('why.title')}
            </LinkButton>
          </div>
        </Section>
      </main>

      <footer className="border-t border-border bg-surface/40">
        <div className="mx-auto flex max-w-7xl flex-wrap items-center justify-between gap-4 px-4 py-8 sm:px-6">
          <div className="flex items-center gap-3">
            <LogoMark className="size-7 text-brand" />
            <div>
              <p className="text-xs text-text-muted">{t('landing.footer.rights')}</p>
              <p className="text-xs text-text-faint">{t('landing.footer.disclaimer')}</p>
            </div>
          </div>
          <p className="font-mono text-xs tracking-wide text-text-faint">{t('common.tagline')}</p>
        </div>
      </footer>
    </div>
  )
}

// ── Building blocks ─────────────────────────────────────────────────────────

function Section({
  id,
  eyebrow,
  title,
  children,
  tinted = false,
}: {
  id: string
  eyebrow: string
  title: string
  children: React.ReactNode
  tinted?: boolean
}) {
  return (
    <section
      id={id}
      className={cn('scroll-mt-16 border-b border-border', tinted && 'bg-surface/25')}
    >
      <div className="mx-auto max-w-7xl px-4 py-20 sm:px-6">
        <SectionTitle className="mb-3">{eyebrow}</SectionTitle>
        <h2 className="mb-8 text-3xl font-semibold tracking-tight text-text sm:text-4xl">{title}</h2>
        {children}
      </div>
    </section>
  )
}

function HeroStat({
  value,
  label,
  suffix,
}: {
  value: number
  label: string
  suffix?: string
}) {
  return (
    <div>
      <p className="tnum text-2xl font-semibold text-text">
        {value}
        {suffix ? <span className="ms-1 text-xs font-medium text-text-muted">{suffix}</span> : null}
      </p>
      <p className="mt-1 text-[11px] leading-tight text-text-faint">{label}</p>
    </div>
  )
}

/** A stylised risk trajectory: normal, rising, then the prevented divergence. */
function HeroVisual({ t }: { t: (key: string) => string }) {
  return (
    <Panel glow className="overflow-hidden">
      <div className="flex items-center justify-between border-b border-border px-5 py-3">
        <span className="text-xs font-medium text-text-muted">{t('timeMachine.trajectory')}</span>
        <span className="flex items-center gap-2 text-[11px] text-text-faint">
          <span className="size-1.5 rounded-full bg-brand nabdh-pulse" />
          {t('common.live')}
        </span>
      </div>

      <div className="p-5">
        <svg viewBox="0 0 400 180" className="w-full" role="img" aria-label={t('timeMachine.trajectory')}>
          <defs>
            <linearGradient id="riskFill" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#ef4444" stopOpacity="0.28" />
              <stop offset="100%" stopColor="#ef4444" stopOpacity="0" />
            </linearGradient>
            <linearGradient id="safeFill" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#24d07f" stopOpacity="0.22" />
              <stop offset="100%" stopColor="#24d07f" stopOpacity="0" />
            </linearGradient>
          </defs>

          {[0, 45, 90, 135, 180].map((y) => (
            <line key={y} x1="0" y1={y} x2="400" y2={y} stroke="#1e2d47" strokeWidth="1" />
          ))}

          {/* Unmitigated trajectory */}
          <path
            d="M0 150 L80 146 L150 132 L210 96 L260 54 L320 22 L400 12 L400 180 L0 180 Z"
            fill="url(#riskFill)"
          />
          <path
            d="M0 150 L80 146 L150 132 L210 96 L260 54 L320 22 L400 12"
            fill="none"
            stroke="#ef4444"
            strokeWidth="2.4"
            strokeLinecap="round"
          />

          {/* Mitigated trajectory, diverging at the moment of intervention */}
          <path
            d="M210 96 L260 118 L320 146 L400 158 L400 180 L210 180 Z"
            fill="url(#safeFill)"
          />
          <path
            d="M210 96 L260 118 L320 146 L400 158"
            fill="none"
            stroke="#24d07f"
            strokeWidth="2.4"
            strokeLinecap="round"
            className="nabdh-flow"
          />

          <line x1="210" y1="0" x2="210" y2="180" stroke="#24d07f" strokeWidth="1" strokeDasharray="3 4" />
          <circle cx="210" cy="96" r="4.5" fill="#05080f" stroke="#24d07f" strokeWidth="2.5" />
        </svg>

        <div className="mt-4 flex flex-wrap items-center justify-between gap-3 text-[11px]">
          <span className="flex items-center gap-2 text-critical">
            <span className="h-0.5 w-5 rounded bg-critical" />
            {t('timeMachine.withoutAction')}
          </span>
          <span className="flex items-center gap-2 text-brand">
            <span className="h-0.5 w-5 rounded bg-brand" />
            {t('timeMachine.withAction')}
          </span>
        </div>
      </div>
    </Panel>
  )
}

function TimeMachineVisual({ t }: { t: (key: string) => string }) {
  const frames = [
    { offset: 'now', state: 'normal' as const, label: 'states.normal' },
    { offset: '15', state: 'watch' as const, label: 'states.watch' },
    { offset: '30', state: 'warning' as const, label: 'states.warning' },
    { offset: '60', state: 'critical' as const, label: 'states.critical' },
  ]
  const colors = { normal: '#10b981', watch: '#fbbf24', warning: '#f97316', critical: '#ef4444' }

  return (
    <Panel className="overflow-hidden">
      <div className="border-b border-border px-5 py-3">
        <span className="text-xs font-medium text-text-muted">{t('timeMachine.timeline')}</span>
      </div>
      <div className="space-y-1 p-5">
        {frames.map((frame, index) => (
          <div
            key={frame.offset}
            className="flex items-center gap-4 rounded-lg px-3 py-3 transition-colors"
            style={{ backgroundColor: `${colors[frame.state]}0f` }}
          >
            <span className="tnum w-16 shrink-0 font-mono text-xs text-text-muted">
              {t(`timeMachine.offsets.${frame.offset}`)}
            </span>
            <span
              className="size-2.5 shrink-0 rounded-full"
              style={{ backgroundColor: colors[frame.state] }}
            />
            <span className="text-sm font-medium" style={{ color: colors[frame.state] }}>
              {t(frame.label)}
            </span>
            <span className="ms-auto h-1 flex-1 max-w-24 overflow-hidden rounded-full bg-surface-3">
              <span
                className="block h-full rounded-full"
                style={{
                  width: `${25 * (index + 1)}%`,
                  backgroundColor: colors[frame.state],
                }}
              />
            </span>
          </div>
        ))}
      </div>
    </Panel>
  )
}

function PreventionVisual({ t }: { t: (key: string) => string }) {
  const actions = [
    { key: 'load_transfer', reduction: 56 },
    { key: 'battery_discharge', reduction: 36 },
    { key: 'demand_response', reduction: 24 },
    { key: 'cooling_boost', reduction: 8 },
  ]

  return (
    <Panel className="overflow-hidden">
      <div className="border-b border-border px-5 py-3">
        <span className="text-xs font-medium text-text-muted">{t('recommendations.title')}</span>
      </div>
      <div className="space-y-3 p-5">
        {actions.map((action) => (
          <div key={action.key}>
            <div className="mb-1.5 flex items-baseline justify-between gap-3">
              <span className="text-xs text-text">{t(`actionType.${action.key}`)}</span>
              <span className="tnum text-xs font-medium text-brand">−{action.reduction}</span>
            </div>
            <div className="h-1.5 overflow-hidden rounded-full bg-surface-3">
              <div
                className="h-full rounded-full bg-gradient-to-r from-brand/50 to-brand"
                style={{ width: `${action.reduction}%` }}
              />
            </div>
          </div>
        ))}
      </div>
      <div className="border-t border-border bg-surface-2/50 px-5 py-4">
        <p className="text-[11px] text-text-muted">{t('recommendations.combinedNote')}</p>
      </div>
    </Panel>
  )
}
