'use client'

import { useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { useTranslations } from 'next-intl'
import {
  AlertTriangle,
  ArrowRight,
  CheckCircle2,
  HardDrive,
  Lock,
  PackageCheck,
  RefreshCw,
  Rocket,
  Server,
  ShieldCheck,
} from 'lucide-react'
import { AppLayout } from '@/components/layout'
import { GlassCard } from '@/components/ui/glass-card'
import {
  apiClient,
  type AwoooIStatusCleanupDashboardSnapshot,
  type BackupDrReadinessMatrixSnapshot,
  type DeliveryClosureWorkbenchSnapshot,
  type GiteaPrivateInventoryP0ScorecardSnapshot,
  type RebootAutoRecoveryDrillPreflightSnapshot,
  type GiteaWorkflowRunnerHealthSnapshot,
  type RuntimeSurfaceInventorySnapshot,
} from '@/lib/api-client'

type DeliveryTone = 'ok' | 'warn' | 'danger' | 'neutral'
type DeliveryTranslator = ReturnType<typeof useTranslations>

interface DeliveryData {
  statusCleanup: AwoooIStatusCleanupDashboardSnapshot | null
  privateInventory: GiteaPrivateInventoryP0ScorecardSnapshot | null
  gitea: GiteaWorkflowRunnerHealthSnapshot | null
  runtime: RuntimeSurfaceInventorySnapshot | null
  backup: BackupDrReadinessMatrixSnapshot | null
}

interface DeliveryLane {
  id: string
  title: string
  description: string
  percent: number
  status: string
  metric: string
  blockerCount: number
  nextAction: string
  href: string
  tone: DeliveryTone
  Icon: typeof Rocket
}

interface DeliveryFocusRow {
  id: string
  title: string
  action: string
  percent: number
  blockerCount: number
  tone: DeliveryTone
  Icon: typeof Rocket
}

const SOURCE_COUNT = 6

const EMPTY_DATA: DeliveryData = {
  statusCleanup: null,
  privateInventory: null,
  gitea: null,
  runtime: null,
  backup: null,
}

const clampPercent = (value: number | null | undefined) => Math.max(0, Math.min(100, Math.round(value ?? 0)))

const toneColor = (tone: DeliveryTone) => {
  if (tone === 'ok') return '#2f7d54'
  if (tone === 'warn') return '#9a6a22'
  if (tone === 'danger') return '#b2432d'
  return '#706f68'
}

const toneBackground = (tone: DeliveryTone) => {
  if (tone === 'ok') return 'rgba(47, 125, 84, 0.10)'
  if (tone === 'warn') return 'rgba(154, 106, 34, 0.10)'
  if (tone === 'danger') return 'rgba(178, 67, 45, 0.10)'
  return 'rgba(112, 111, 104, 0.10)'
}

const resolveTone = (blockerCount: number, percent: number): DeliveryTone => {
  if (blockerCount > 0) return 'danger'
  if (percent < 80) return 'warn'
  return 'ok'
}

const firstActionRequiredRunner = (data: GiteaWorkflowRunnerHealthSnapshot | null) =>
  data?.runner_contracts.find(contract => contract.status === 'action_required')?.next_action ?? ''

const firstRuntimeAction = (data: RuntimeSurfaceInventorySnapshot | null) =>
  data?.runtime_surfaces.find(surface => surface.status !== 'manifest_mapped')?.next_action ?? ''

const firstBackupAction = (data: BackupDrReadinessMatrixSnapshot | null) =>
  data?.readiness_rows.find(row => row.overall_readiness === 'blocked' || row.overall_readiness === 'action_required')?.next_action ?? ''

function StatusPill({ tone, label }: { tone: DeliveryTone; label: string }) {
  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        minHeight: 26,
        borderRadius: 6,
        padding: '3px 8px',
        background: toneBackground(tone),
        color: toneColor(tone),
        fontSize: 12,
        fontWeight: 700,
        overflowWrap: 'anywhere',
      }}
    >
      {label}
    </span>
  )
}

function ProgressBar({ percent, tone }: { percent: number; tone: DeliveryTone }) {
  return (
    <div
      aria-hidden="true"
      style={{
        height: 8,
        borderRadius: 4,
        background: '#ebe8dd',
        overflow: 'hidden',
      }}
    >
      <div
        style={{
          width: `${percent}%`,
          height: '100%',
          background: toneColor(tone),
          transition: 'width 240ms ease',
        }}
      />
    </div>
  )
}

function MetricTile({
  label,
  value,
  detail,
  tone,
}: {
  label: string
  value: string | number
  detail: string
  tone: DeliveryTone
}) {
  return (
    <GlassCard variant="subtle" padding="sm" data-testid={`delivery-metric-${label}`}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, minHeight: 112 }}>
        <span style={{ fontSize: 12, color: '#706f68', fontWeight: 700 }}>{label}</span>
        <strong style={{ fontFamily: 'var(--font-heading), sans-serif', fontSize: 30, color: '#141413', lineHeight: 1 }}>
          {value}
        </strong>
        <span style={{ fontSize: 12, lineHeight: 1.45, color: toneColor(tone), overflowWrap: 'anywhere' }}>
          {detail}
        </span>
      </div>
    </GlassCard>
  )
}

function CurrentP0Panel({
  workbench,
  t,
}: {
  workbench: DeliveryClosureWorkbenchSnapshot | null
  t: DeliveryTranslator
}) {
  if (!workbench) return null

  const { readback, rollups, operation_boundaries: boundaries } = workbench
  const readiness = clampPercent(readback.current_p0_readiness_percent || rollups.current_p0_readiness_percent)
  const blockers = readback.current_p0_active_blockers.length > 0 ? readback.current_p0_active_blockers : workbench.active_blockers
  const drillPreflightReady = readback.current_p0_drill_preflight_ready || rollups.current_p0_drill_preflight_ready
  const drillBreakGlassRequired = readback.current_p0_drill_preflight_break_glass_required || rollups.current_p0_drill_preflight_break_glass_required
  const panelTone: DeliveryTone = blockers.length > 0 ? 'danger' : readiness >= 100 ? 'ok' : 'warn'
  const closedP0 = readback.closed_p0_workplan_ids.length > 0
    ? readback.closed_p0_workplan_ids.join(' / ')
    : t('currentP0.closedEmpty')
  const truthRows = [
    { key: 'eventGate', value: rollups.current_p0_blocked_by_fresh_reboot_window_only ? t('currentP0.values.yes') : t('currentP0.values.no') },
    { key: 'service', value: rollups.current_p0_service_green ? t('currentP0.values.green') : t('currentP0.values.blocked') },
    { key: 'productData', value: rollups.current_p0_product_data_green ? t('currentP0.values.green') : t('currentP0.values.blocked') },
    { key: 'backup', value: rollups.current_p0_backup_core_green ? t('currentP0.values.green') : t('currentP0.values.blocked') },
    { key: 'stock', value: `${rollups.current_p0_stockplatform_freshness_status} / ${rollups.current_p0_stockplatform_ingestion_status}` },
    { key: 'drillPreflight', value: drillPreflightReady ? t('currentP0.values.ready') : t('currentP0.values.blocked') },
    { key: 'breakGlass', value: drillBreakGlassRequired ? t('currentP0.values.yes') : t('currentP0.values.no') },
    { key: 'github', value: readback.github_lane_status },
  ]
  const flagRows = [
    { key: 'runtimeWrite', value: boundaries.runtime_write_allowed || readback.runtime_write_authorized || rollups.runtime_write_authorized },
    { key: 'workflowTrigger', value: boundaries.workflow_trigger_allowed || readback.workflow_trigger_authorized || rollups.workflow_trigger_authorized },
    { key: 'secretCollection', value: boundaries.secret_value_collection_allowed || readback.secret_value_collection_allowed || rollups.secret_values_collected },
    { key: 'remoteWrite', value: boundaries.remote_write_allowed },
    { key: 'repoCreation', value: boundaries.repo_creation_allowed },
    { key: 'activeScan', value: boundaries.active_scan_allowed },
  ]

  return (
    <section className="delivery-current-p0" data-testid="delivery-current-p0">
      <div className="delivery-section-heading">
        <div>
          <h2>{t('currentP0.title')}</h2>
          <p>{t('currentP0.detail')}</p>
        </div>
        <StatusPill tone={panelTone} label={readback.current_p0_status} />
      </div>
      <GlassCard variant="default" padding="md">
        <div className="delivery-current-p0-grid">
          <div className="delivery-current-p0-main">
            <div className="delivery-current-p0-icon">
              <ShieldCheck size={22} aria-hidden="true" />
            </div>
            <div>
              <h3>{readback.current_p0_workplan_id}</h3>
              <p>{readback.current_p0_safe_next_step || workbench.safe_next_step}</p>
            </div>
          </div>

          <div className="delivery-current-p0-stats">
            <div>
              <span>{t('currentP0.source')}</span>
              <strong>{readback.current_p0_source_id}</strong>
            </div>
            <div>
              <span>{t('currentP0.readiness')}</span>
              <strong>{readiness}%</strong>
            </div>
            <div>
              <span>{t('currentP0.closed')}</span>
              <strong>{closedP0}</strong>
            </div>
          </div>

          <div className="delivery-current-p0-blockers">
            <strong>{t('currentP0.blockers')}</strong>
            <div>
              {(blockers.length > 0 ? blockers : [t('currentP0.noBlockers')]).map(blocker => (
                <StatusPill key={blocker} tone={blockers.length > 0 ? 'danger' : 'ok'} label={blocker} />
              ))}
            </div>
          </div>

          <div className="delivery-current-p0-truth">
            {truthRows.map(row => (
              <div key={row.key}>
                <span>{t(`currentP0.truth.${row.key}`)}</span>
                <strong>{row.value}</strong>
              </div>
            ))}
          </div>

          <div className="delivery-current-p0-flags">
            {flagRows.map(row => (
              <StatusPill
                key={row.key}
                tone={row.value ? 'danger' : 'ok'}
                label={`${t(`currentP0.flags.${row.key}`)}: ${row.value ? t('currentP0.values.open') : t('currentP0.values.closed')}`}
              />
            ))}
          </div>
        </div>
      </GlassCard>
    </section>
  )
}

function DrillPreflightPanel({
  preflight,
  locale,
  t,
}: {
  preflight: RebootAutoRecoveryDrillPreflightSnapshot | null
  locale: string
  t: DeliveryTranslator
}) {
  if (!preflight) {
    return (
      <section className="delivery-drill-panel" data-testid="delivery-reboot-drill-preflight">
        <GlassCard variant="subtle" padding="md">
          <div className="delivery-drill-empty">
            <ShieldCheck size={18} aria-hidden="true" />
            <span>{t('drill.unavailable')}</span>
          </div>
        </GlassCard>
      </section>
    )
  }

  const readiness = clampPercent(preflight.current_readback.readiness_percent)
  const gateTone: DeliveryTone = preflight.execution_authorized_by_this_endpoint ? 'danger' : preflight.preflight_ready ? 'warn' : 'danger'
  const boundaryTone: DeliveryTone = preflight.execution_authorized_by_this_endpoint ? 'danger' : 'ok'
  const targetHosts = preflight.target_selector.required_host_aliases.join(' / ')
  const activeBlocker = preflight.current_readback.active_blockers[0] ?? preflight.status

  return (
    <section className="delivery-drill-panel" data-testid="delivery-reboot-drill-preflight">
      <div className="delivery-section-heading">
        <div>
          <h2>{t('sections.drill')}</h2>
          <p>{t('sections.drillDetail')}</p>
        </div>
        <StatusPill tone={gateTone} label={preflight.status} />
      </div>
      <GlassCard variant="default" padding="md">
        <div className="delivery-drill-grid">
          <div className="delivery-drill-primary">
            <div className="delivery-drill-icon">
              <ShieldCheck size={22} aria-hidden="true" />
            </div>
            <div style={{ minWidth: 0 }}>
              <h3>{t('drill.title')}</h3>
              <p>{t('drill.detail', { blocker: activeBlocker })}</p>
            </div>
          </div>

          <div className="delivery-drill-metrics">
            <div>
              <span>{t('drill.metrics.preflight')}</span>
              <strong>{preflight.preflight_ready ? t('drill.values.ready') : t('drill.values.blocked')}</strong>
            </div>
            <div>
              <span>{t('drill.metrics.target')}</span>
              <strong>{targetHosts}</strong>
            </div>
            <div>
              <span>{t('drill.metrics.readiness')}</span>
              <strong>{readiness}%</strong>
            </div>
            <div>
              <span>{t('drill.metrics.execution')}</span>
              <strong>{preflight.execution_authorized_by_this_endpoint ? t('drill.values.enabled') : t('drill.values.disabled')}</strong>
            </div>
          </div>

          <div className="delivery-drill-boundaries">
            <StatusPill tone={gateTone} label={t('drill.flags.breakGlass', { value: String(preflight.break_glass_authorization_required) })} />
            <StatusPill tone={boundaryTone} label={t('drill.flags.hostReboot', { value: String(preflight.operation_boundaries.host_reboot_performed) })} />
            <StatusPill tone={boundaryTone} label={t('drill.flags.runtimeWrite', { value: String(preflight.operation_boundaries.runtime_write_allowed) })} />
            <StatusPill tone={boundaryTone} label={t('drill.flags.secret', { value: String(preflight.operation_boundaries.secret_value_collection_allowed) })} />
          </div>

          <div className="delivery-drill-footer">
            <span>{preflight.safe_next_step}</span>
            <Link href={`/${locale}/operations`}>
              <ArrowRight size={15} aria-hidden="true" />
              <span>{t('drill.operations')}</span>
            </Link>
          </div>
        </div>
      </GlassCard>
    </section>
  )
}

function LaneCard({ lane, locale }: { lane: DeliveryLane; locale: string }) {
  return (
    <GlassCard variant="default" padding="md" data-testid={`delivery-lane-${lane.id}`}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, minHeight: 230 }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
          <div
            style={{
              width: 38,
              height: 38,
              borderRadius: 8,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              background: toneBackground(lane.tone),
              color: toneColor(lane.tone),
              flex: '0 0 auto',
            }}
          >
            <lane.Icon size={19} aria-hidden="true" />
          </div>
          <div style={{ minWidth: 0, flex: 1 }}>
            <h2 style={{ fontSize: 17, fontWeight: 800, color: '#141413', margin: 0, overflowWrap: 'anywhere' }}>
              {lane.title}
            </h2>
            <p style={{ fontSize: 13, lineHeight: 1.5, color: '#706f68', margin: '5px 0 0', overflowWrap: 'anywhere' }}>
              {lane.description}
            </p>
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
          <StatusPill tone={lane.tone} label={lane.status} />
          <span style={{ fontSize: 13, fontWeight: 800, color: '#141413' }}>{lane.percent}%</span>
        </div>
        <ProgressBar percent={lane.percent} tone={lane.tone} />

        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 10, alignItems: 'center', marginTop: 'auto' }}>
          <span style={{ fontSize: 13, color: '#45443f', lineHeight: 1.45, overflowWrap: 'anywhere' }}>{lane.metric}</span>
          <StatusPill tone={lane.blockerCount > 0 ? 'danger' : 'ok'} label={String(lane.blockerCount)} />
        </div>

        <Link
          href={`/${locale}${lane.href}`}
          style={{
            display: 'inline-flex',
            alignItems: 'center',
            gap: 6,
            color: '#141413',
            fontWeight: 800,
            fontSize: 13,
            textDecoration: 'none',
          }}
        >
          <ArrowRight size={15} aria-hidden="true" />
          <span>{lane.metric}</span>
        </Link>
      </div>
    </GlassCard>
  )
}

export default function DeliveryPage({ params }: { params: { locale: string } }) {
  const t = useTranslations('delivery')
  const [workbench, setWorkbench] = useState<DeliveryClosureWorkbenchSnapshot | null>(null)
  const [drillPreflight, setDrillPreflight] = useState<RebootAutoRecoveryDrillPreflightSnapshot | null>(null)
  const [data, setData] = useState<DeliveryData>(EMPTY_DATA)
  const [errors, setErrors] = useState<string[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    const load = async () => {
      setLoading(true)
      setErrors([])
      try {
        const [summaryResult, drillResult] = await Promise.allSettled([
          apiClient.getDeliveryClosureWorkbench(),
          apiClient.getRebootAutoRecoveryDrillPreflight(),
        ])
        if (summaryResult.status === 'fulfilled') {
          if (cancelled) return
          setWorkbench(summaryResult.value)
          setDrillPreflight(drillResult.status === 'fulfilled' ? drillResult.value : null)
          setData(EMPTY_DATA)
          setErrors(drillResult.status === 'fulfilled' ? [] : [t('sources.5.error')])
          setLoading(false)
          return
        }
      } catch {
        // Summary endpoint may not exist until the API release lands; keep the page useful with legacy reads.
      }

      const results = await Promise.allSettled([
        apiClient.getAwoooIStatusCleanupDashboard(),
        apiClient.getGiteaPrivateInventoryP0Scorecard(),
        apiClient.getGiteaWorkflowRunnerHealth(),
        apiClient.getRuntimeSurfaceInventory(),
        apiClient.getBackupDrReadinessMatrix(),
        apiClient.getRebootAutoRecoveryDrillPreflight(),
      ])
      if (cancelled) return

      const nextData: DeliveryData = {
        statusCleanup: results[0].status === 'fulfilled' ? results[0].value : null,
        privateInventory: results[1].status === 'fulfilled' ? results[1].value : null,
        gitea: results[2].status === 'fulfilled' ? results[2].value : null,
        runtime: results[3].status === 'fulfilled' ? results[3].value : null,
        backup: results[4].status === 'fulfilled' ? results[4].value : null,
      }
      const nextDrillPreflight = results[5].status === 'fulfilled' ? results[5].value : null
      const nextErrors = results
        .map((result, index) => ({ result, index }))
        .filter(({ result }) => result.status === 'rejected')
        .map(({ index }) => t(`sources.${index}.error`))

      setWorkbench(null)
      setDrillPreflight(nextDrillPreflight)
      setData(nextData)
      setErrors(nextErrors)
      setLoading(false)
    }

    load()
    return () => {
      cancelled = true
    }
  }, [t])

  const lanes = useMemo<DeliveryLane[]>(() => {
    if (workbench) {
      return workbench.lanes.map(lane => {
        const iconMap: Record<string, typeof Rocket> = {
          release: Rocket,
          production_deploy: Rocket,
          gitea_private_inventory: PackageCheck,
          cicd_baseline: PackageCheck,
          reboot_auto_recovery: RefreshCw,
          credential_escrow: ShieldCheck,
          gitea: PackageCheck,
          runtime: Server,
          backup: HardDrive,
        }
        const metric =
          lane.metric.kind === 'blocked_gate'
            ? t('lanes.release.metric', { blocked: lane.metric.blocked })
            : lane.metric.kind === 'private_inventory'
              ? t('lanes.gitea_private_inventory.metric', {
                  present: lane.metric.present_product_row_count,
                  expected: lane.metric.expected_product_count,
                  scope: lane.metric.gitea_visibility_scope,
                })
              : lane.metric.kind === 'deploy_readback'
                ? t('lanes.production_deploy.metric', {
                    run: lane.metric.latest_visible_cd_run_id,
                    status: lane.metric.latest_visible_cd_run_status,
                  })
              : lane.metric.kind === 'source_readiness'
                ? t('lanes.cicd_baseline.metric', {
                    present: lane.metric.present_required_source_count,
                    required: lane.metric.required_source_count,
                  })
              : lane.metric.kind === 'reboot_auto_recovery_slo'
                ? t('lanes.reboot_auto_recovery.metric', {
                    hosts: lane.metric.observed_host_count,
                    stale: lane.metric.stale_host_count,
                    freshness: lane.metric.stockplatform_freshness_status,
                  })
              : lane.metric.kind === 'credential_escrow_evidence'
                ? t('lanes.credential_escrow.metric', {
                    accepted: lane.metric.accepted_item_count,
                    required: lane.metric.required_item_count,
                  })
              : lane.metric.kind === 'workflow_count'
                ? t('lanes.gitea.metric', { count: lane.metric.count })
                : lane.metric.kind === 'surface_count'
                  ? t('lanes.runtime.metric', { total: lane.metric.total })
                  : t('lanes.backup.metric', { rows: lane.metric.rows })

        return {
          id: lane.id,
          title: t(`lanes.${lane.id}.title`),
          description: t(`lanes.${lane.id}.description`),
          percent: clampPercent(lane.completion_percent),
          status: lane.status || t('states.noData'),
          metric,
          blockerCount: lane.blocker_count,
          nextAction: lane.next_action,
          href: lane.href,
          tone: lane.tone,
          Icon: iconMap[lane.id] ?? Rocket,
        }
      })
    }

    const statusBlocked = Number(data.statusCleanup?.summary.blocked_gate_count ?? 0)
    const statusPercent = clampPercent(data.statusCleanup?.summary.overall_completion_percent)
    const privateInventoryPercent = clampPercent(data.privateInventory?.rollups.review_readiness_percent)
    const privateInventoryBlocked = data.privateInventory?.rollups.active_blocker_count ?? 0
    const giteaPercent = clampPercent(data.gitea?.program_status.overall_completion_percent)
    const giteaBlocked = data.gitea?.rollups.runner_contracts_requiring_action.length ?? 0
    const runtimePercent = clampPercent(data.runtime?.program_status.overall_completion_percent)
    const runtimeBlocked = (data.runtime?.rollups.action_required_surface_ids.length ?? 0) + (data.runtime?.rollups.secret_surface_ids.length ?? 0)
    const backupPercent = clampPercent(data.backup?.program_status.overall_completion_percent)
    const backupBlocked = data.backup?.rollups.blocked_row_ids.length ?? 0

    return [
      {
        id: 'release',
        title: t('lanes.release.title'),
        description: t('lanes.release.description'),
        percent: statusPercent,
        status: data.statusCleanup?.summary.dashboard_status ?? t('states.noData'),
        metric: t('lanes.release.metric', { blocked: statusBlocked }),
        blockerCount: statusBlocked,
        nextAction: data.statusCleanup?.next_actions[0] ?? '',
        href: '/governance?tab=automation-inventory',
        tone: resolveTone(statusBlocked, statusPercent),
        Icon: Rocket,
      },
      {
        id: 'gitea_private_inventory',
        title: t('lanes.gitea_private_inventory.title'),
        description: t('lanes.gitea_private_inventory.description'),
        percent: privateInventoryPercent,
        status: data.privateInventory?.status ?? t('states.noData'),
        metric: t('lanes.gitea_private_inventory.metric', {
          present: data.privateInventory?.rollups.present_product_row_count ?? 0,
          expected: data.privateInventory?.rollups.expected_product_count ?? 0,
          scope: data.privateInventory?.rollups.gitea_visibility_scope ?? 'unknown',
        }),
        blockerCount: privateInventoryBlocked,
        nextAction: data.privateInventory?.readback.safe_next_step ?? '',
        href: '/delivery',
        tone: resolveTone(privateInventoryBlocked, privateInventoryPercent),
        Icon: PackageCheck,
      },
      {
        id: 'gitea',
        title: t('lanes.gitea.title'),
        description: t('lanes.gitea.description'),
        percent: giteaPercent,
        status: data.gitea?.program_status.current_task_id ?? t('states.noData'),
        metric: t('lanes.gitea.metric', { count: data.gitea?.rollups.total_workflows ?? 0 }),
        blockerCount: giteaBlocked,
        nextAction: firstActionRequiredRunner(data.gitea),
        href: '/deployments',
        tone: resolveTone(giteaBlocked, giteaPercent),
        Icon: PackageCheck,
      },
      {
        id: 'runtime',
        title: t('lanes.runtime.title'),
        description: t('lanes.runtime.description'),
        percent: runtimePercent,
        status: data.runtime?.program_status.current_task_id ?? t('states.noData'),
        metric: t('lanes.runtime.metric', { total: data.runtime?.rollups.total_surfaces ?? 0 }),
        blockerCount: runtimeBlocked,
        nextAction: firstRuntimeAction(data.runtime),
        href: '/governance?tab=automation-inventory',
        tone: resolveTone(runtimeBlocked, runtimePercent),
        Icon: Server,
      },
      {
        id: 'backup',
        title: t('lanes.backup.title'),
        description: t('lanes.backup.description'),
        percent: backupPercent,
        status: data.backup?.program_status.current_task_id ?? t('states.noData'),
        metric: t('lanes.backup.metric', { rows: data.backup?.rollups.total_rows ?? 0 }),
        blockerCount: backupBlocked,
        nextAction: firstBackupAction(data.backup),
        href: '/operations',
        tone: resolveTone(backupBlocked, backupPercent),
        Icon: HardDrive,
      },
    ]
  }, [data, t, workbench])

  const sourceTotal = workbench?.summary.source_count ?? SOURCE_COUNT
  const loadedCount = workbench?.summary.loaded_source_count ?? Object.values(data).filter(Boolean).length + (drillPreflight ? 1 : 0)
  const highRiskBlockers = workbench?.summary.high_risk_blocker_count ?? lanes.reduce((sum, lane) => sum + lane.blockerCount, 0)
  const averageCompletion = workbench?.summary.average_completion_percent ?? clampPercent(lanes.reduce((sum, lane) => sum + lane.percent, 0) / Math.max(lanes.length, 1))
  const pageTone: DeliveryTone = highRiskBlockers > 0 ? 'danger' : loadedCount === sourceTotal ? 'ok' : 'warn'
  const activeExecutionCount = workbench
    ? [
        workbench.operation_boundaries.runtime_write_allowed,
        workbench.operation_boundaries.remote_write_allowed,
        workbench.operation_boundaries.workflow_trigger_allowed,
        workbench.operation_boundaries.secret_value_collection_allowed,
        workbench.operation_boundaries.active_scan_allowed,
      ].filter(Boolean).length
    : 0
  const focusRows = useMemo<DeliveryFocusRow[]>(() => {
    if (workbench?.next_focus?.length) {
      return workbench.next_focus.slice(0, 5).map(focus => {
        const lane = lanes.find(item => item.id === focus.lane_id)
        const percent = clampPercent(focus.completion_percent)
        return {
          id: focus.lane_id,
          title: lane?.title ?? focus.lane_id,
          action: focus.next_action,
          percent,
          blockerCount: focus.blocker_count,
          tone: focus.blocker_count > 0 ? 'danger' : resolveTone(0, percent),
          Icon: lane?.Icon ?? Rocket,
        }
      })
    }

    return lanes
      .filter(lane => lane.blockerCount > 0 || lane.percent < 80)
      .slice(0, 5)
      .map(lane => ({
        id: lane.id,
        title: lane.title,
        action: lane.nextAction || lane.metric,
        percent: lane.percent,
        blockerCount: lane.blockerCount,
        tone: lane.tone,
        Icon: lane.Icon,
      }))
  }, [lanes, workbench])
  const boundaryRows = workbench
    ? [
        { key: 'readOnlyApi', value: workbench.operation_boundaries.read_only_api_allowed, tone: 'ok' as DeliveryTone },
        { key: 'runtimeWrite', value: workbench.operation_boundaries.runtime_write_allowed, tone: workbench.operation_boundaries.runtime_write_allowed ? 'danger' as DeliveryTone : 'ok' as DeliveryTone },
        { key: 'remoteWrite', value: workbench.operation_boundaries.remote_write_allowed, tone: workbench.operation_boundaries.remote_write_allowed ? 'danger' as DeliveryTone : 'ok' as DeliveryTone },
        { key: 'workflowTrigger', value: workbench.operation_boundaries.workflow_trigger_allowed, tone: workbench.operation_boundaries.workflow_trigger_allowed ? 'warn' as DeliveryTone : 'ok' as DeliveryTone },
        { key: 'secretCollection', value: workbench.operation_boundaries.secret_value_collection_allowed, tone: workbench.operation_boundaries.secret_value_collection_allowed ? 'danger' as DeliveryTone : 'ok' as DeliveryTone },
        { key: 'activeScan', value: workbench.operation_boundaries.active_scan_allowed, tone: workbench.operation_boundaries.active_scan_allowed ? 'danger' as DeliveryTone : 'ok' as DeliveryTone },
      ]
    : []

  return (
    <AppLayout locale={params.locale}>
      <div data-testid="delivery-page" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <section className="delivery-hero">
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: '#d97757', fontSize: 12, fontWeight: 800 }}>
              <Rocket size={16} aria-hidden="true" />
              <span>{t('eyebrow')}</span>
            </div>
            <h1 style={{ fontSize: 34, lineHeight: 1.1, fontWeight: 900, color: '#141413', margin: '8px 0 8px' }}>
              {t('title')}
            </h1>
            <p style={{ maxWidth: 780, fontSize: 15, lineHeight: 1.65, color: '#595852', margin: 0 }}>
              {t('subtitle')}
            </p>
          </div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
            <StatusPill tone={pageTone} label={loading ? t('states.loading') : errors.length > 0 ? t('states.partial') : t('states.ready')} />
            <button
              type="button"
              onClick={() => window.location.reload()}
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: 6,
                minHeight: 34,
                borderRadius: 7,
                border: '0.5px solid #d8d3c5',
                background: '#fffaf0',
                color: '#141413',
                padding: '0 10px',
                fontSize: 13,
                fontWeight: 800,
                cursor: 'pointer',
              }}
            >
              <RefreshCw size={15} aria-hidden="true" />
              {t('actions.refresh')}
            </button>
          </div>
        </section>

        <section className="delivery-metrics">
          <MetricTile label={t('metrics.loaded')} value={`${loadedCount}/${sourceTotal}`} detail={t('metrics.loadedDetail')} tone={loadedCount === sourceTotal ? 'ok' : 'warn'} />
          <MetricTile label={t('metrics.completion')} value={`${averageCompletion}%`} detail={t('metrics.completionDetail')} tone={averageCompletion >= 80 ? 'ok' : 'warn'} />
          <MetricTile label={t('metrics.blockers')} value={highRiskBlockers} detail={t('metrics.blockersDetail')} tone={highRiskBlockers > 0 ? 'danger' : 'ok'} />
          <MetricTile label={t('metrics.execution')} value={activeExecutionCount} detail={t('metrics.executionDetail')} tone={activeExecutionCount > 0 ? 'danger' : 'ok'} />
        </section>

        <CurrentP0Panel workbench={workbench} t={t} />

        <DrillPreflightPanel preflight={drillPreflight} locale={params.locale} t={t} />

        {errors.length > 0 && (
          <section className="delivery-alert" data-testid="delivery-partial-errors">
            <AlertTriangle size={18} aria-hidden="true" />
            <div>
              <strong>{t('errors.title')}</strong>
              <p>{errors.join(' · ')}</p>
            </div>
          </section>
        )}

        <section>
          <div className="delivery-section-heading">
            <div>
              <h2>{t('sections.lanes')}</h2>
              <p>{t('sections.lanesDetail')}</p>
            </div>
          </div>
          <div className="delivery-lanes">
            {lanes.map(lane => <LaneCard key={lane.id} lane={lane} locale={params.locale} />)}
          </div>
        </section>

        <section className="delivery-grid-two">
          <div>
            <div className="delivery-section-heading">
              <div>
                <h2>{t('sections.next')}</h2>
                <p>{t('sections.nextDetail')}</p>
              </div>
            </div>
            <div className="delivery-next-list">
              {focusRows.length > 0 ? (
                focusRows.map(row => (
                  <div key={row.id} className="delivery-next-row">
                    <row.Icon size={17} aria-hidden="true" />
                    <div>
                      <strong>{row.title}</strong>
                      <span>{row.action}</span>
                    </div>
                    <StatusPill tone={row.tone} label={t('nextFocus.status', { percent: row.percent, blockers: row.blockerCount })} />
                  </div>
                ))
              ) : (
                <div className="delivery-next-empty">{t('nextFocus.empty')}</div>
              )}
            </div>
          </div>

          <div>
            <div className="delivery-section-heading">
              <div>
                <h2>{t('sections.boundary')}</h2>
                <p>{t('sections.boundaryDetail')}</p>
              </div>
            </div>
            <div className="delivery-boundary-list">
              {boundaryRows.length > 0
                ? boundaryRows.map(row => (
                    <div key={row.key} className="delivery-boundary-row">
                      <Lock size={16} aria-hidden="true" />
                      <span>{t(`boundaryFacts.${row.key}`)}</span>
                      <StatusPill tone={row.tone} label={row.value ? t('boundaryFacts.values.open') : t('boundaryFacts.values.closed')} />
                    </div>
                  ))
                : ['secret', 'production', 'repo', 'data', 'security'].map(key => (
                    <div key={key} className="delivery-boundary-row">
                      <Lock size={16} aria-hidden="true" />
                      <span>{t(`boundaries.${key}`)}</span>
                      <CheckCircle2 size={16} aria-hidden="true" />
                    </div>
                  ))}
            </div>
          </div>
        </section>
      </div>

      <style jsx>{`
        .delivery-hero {
          display: grid;
          grid-template-columns: minmax(0, 1fr) auto;
          gap: 18px;
          align-items: start;
          padding-bottom: 4px;
        }
        .delivery-metrics,
        .delivery-lanes {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
          gap: 12px;
        }
        :global(.delivery-current-p0-grid) {
          display: grid;
          grid-template-columns: minmax(0, 1.1fr) minmax(300px, 0.9fr);
          gap: 14px;
          align-items: start;
        }
        :global(.delivery-current-p0-main) {
          display: grid;
          grid-template-columns: 44px minmax(0, 1fr);
          gap: 12px;
          min-width: 0;
        }
        :global(.delivery-current-p0-icon) {
          width: 44px;
          height: 44px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #2f7d54;
          background: rgba(47, 125, 84, 0.1);
        }
        :global(.delivery-current-p0-main h3) {
          margin: 0;
          font-size: 19px;
          font-weight: 900;
          color: #141413;
          overflow-wrap: anywhere;
        }
        :global(.delivery-current-p0-main p) {
          margin: 6px 0 0;
          color: #595852;
          font-size: 13px;
          line-height: 1.55;
          overflow-wrap: anywhere;
        }
        :global(.delivery-current-p0-stats),
        :global(.delivery-current-p0-truth) {
          display: grid;
          grid-template-columns: repeat(3, minmax(0, 1fr));
          gap: 8px;
        }
        :global(.delivery-current-p0-truth) {
          grid-column: 1 / -1;
          grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
        }
        :global(.delivery-current-p0-stats div),
        :global(.delivery-current-p0-truth div) {
          min-height: 68px;
          border: 0.5px solid #e0ddd4;
          border-radius: 8px;
          padding: 9px;
          background: rgba(255, 255, 255, 0.56);
          min-width: 0;
        }
        :global(.delivery-current-p0-stats span),
        :global(.delivery-current-p0-truth span) {
          display: block;
          color: #706f68;
          font-size: 11px;
          font-weight: 800;
          margin-bottom: 6px;
        }
        :global(.delivery-current-p0-stats strong),
        :global(.delivery-current-p0-truth strong) {
          color: #141413;
          font-size: 15px;
          line-height: 1.3;
          overflow-wrap: anywhere;
        }
        :global(.delivery-current-p0-blockers) {
          grid-column: 1 / -1;
          display: grid;
          gap: 8px;
          min-width: 0;
        }
        :global(.delivery-current-p0-blockers > strong) {
          color: #141413;
          font-size: 13px;
          font-weight: 900;
        }
        :global(.delivery-current-p0-blockers > div),
        :global(.delivery-current-p0-flags) {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          min-width: 0;
        }
        :global(.delivery-current-p0-flags) {
          grid-column: 1 / -1;
        }
        :global(.delivery-drill-panel) {
          min-width: 0;
        }
        :global(.delivery-drill-grid) {
          display: grid;
          grid-template-columns: minmax(0, 1.05fr) minmax(280px, 1fr);
          gap: 14px;
          align-items: start;
        }
        :global(.delivery-drill-primary) {
          display: grid;
          grid-template-columns: 44px minmax(0, 1fr);
          gap: 12px;
          align-items: start;
          min-width: 0;
        }
        :global(.delivery-drill-icon) {
          width: 44px;
          height: 44px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #9a6a22;
          background: rgba(154, 106, 34, 0.1);
        }
        :global(.delivery-drill-primary h3) {
          margin: 0;
          font-size: 18px;
          font-weight: 900;
          color: #141413;
          overflow-wrap: anywhere;
        }
        :global(.delivery-drill-primary p) {
          margin: 6px 0 0;
          color: #595852;
          font-size: 13px;
          line-height: 1.55;
          overflow-wrap: anywhere;
        }
        :global(.delivery-drill-metrics) {
          display: grid;
          grid-template-columns: repeat(2, minmax(0, 1fr));
          gap: 8px;
        }
        :global(.delivery-drill-metrics div) {
          min-height: 68px;
          border: 0.5px solid #e0ddd4;
          border-radius: 8px;
          padding: 9px;
          background: rgba(255, 255, 255, 0.56);
          min-width: 0;
        }
        :global(.delivery-drill-metrics span) {
          display: block;
          color: #706f68;
          font-size: 11px;
          font-weight: 800;
          margin-bottom: 6px;
        }
        :global(.delivery-drill-metrics strong) {
          color: #141413;
          font-size: 16px;
          line-height: 1.25;
          overflow-wrap: anywhere;
        }
        :global(.delivery-drill-boundaries) {
          grid-column: 1 / -1;
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          min-width: 0;
        }
        :global(.delivery-drill-footer) {
          grid-column: 1 / -1;
          display: grid;
          grid-template-columns: minmax(0, 1fr) auto;
          gap: 12px;
          align-items: center;
          border-top: 0.5px solid #e0ddd4;
          padding-top: 12px;
          color: #45443f;
          font-size: 12px;
          line-height: 1.5;
          min-width: 0;
        }
        :global(.delivery-drill-footer > span) {
          display: block;
          min-width: 0;
          max-width: 100%;
          overflow-wrap: anywhere;
          word-break: break-word;
        }
        :global(.delivery-drill-footer a) {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          color: #141413;
          font-weight: 800;
          text-decoration: none;
          white-space: nowrap;
        }
        :global(.delivery-drill-empty) {
          min-height: 58px;
          display: flex;
          gap: 10px;
          align-items: center;
          color: #706f68;
          font-size: 13px;
          line-height: 1.45;
        }
        .delivery-section-heading {
          display: flex;
          align-items: flex-end;
          justify-content: space-between;
          gap: 12px;
          margin: 4px 0 10px;
        }
        .delivery-section-heading h2 {
          margin: 0;
          font-size: 19px;
          font-weight: 900;
          color: #141413;
        }
        .delivery-section-heading p {
          margin: 4px 0 0;
          color: #706f68;
          font-size: 13px;
          line-height: 1.5;
        }
        .delivery-alert {
          display: flex;
          align-items: flex-start;
          gap: 10px;
          border: 0.5px solid rgba(178, 67, 45, 0.22);
          background: rgba(178, 67, 45, 0.08);
          color: #7f2f21;
          border-radius: 8px;
          padding: 12px;
        }
        .delivery-alert p {
          margin: 3px 0 0;
          font-size: 13px;
          line-height: 1.5;
        }
        .delivery-grid-two {
          display: grid;
          grid-template-columns: minmax(0, 1.25fr) minmax(280px, 0.75fr);
          gap: 14px;
        }
        .delivery-next-list,
        .delivery-boundary-list {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }
        .delivery-next-empty {
          min-height: 54px;
          border: 0.5px solid #e0ddd4;
          background: rgba(255, 255, 255, 0.62);
          border-radius: 8px;
          padding: 12px;
          color: #706f68;
          font-size: 13px;
          line-height: 1.5;
        }
        .delivery-next-row,
        .delivery-boundary-row {
          display: grid;
          grid-template-columns: 20px minmax(0, 1fr) auto;
          align-items: center;
          gap: 10px;
          min-height: 54px;
          border: 0.5px solid #e0ddd4;
          background: rgba(255, 255, 255, 0.62);
          border-radius: 8px;
          padding: 10px;
          color: #45443f;
        }
        .delivery-next-row div {
          display: flex;
          flex-direction: column;
          gap: 3px;
          min-width: 0;
        }
        .delivery-next-row strong {
          color: #141413;
          font-size: 13px;
          overflow-wrap: anywhere;
        }
        .delivery-next-row span,
        .delivery-boundary-row span {
          font-size: 12px;
          line-height: 1.45;
          overflow-wrap: anywhere;
        }
        .delivery-boundary-row {
          grid-template-columns: 20px minmax(0, 1fr) auto;
        }
        @media (max-width: 900px) {
          .delivery-hero,
          :global(.delivery-current-p0-grid),
          :global(.delivery-drill-grid),
          .delivery-grid-two {
            grid-template-columns: 1fr;
          }
          :global(.delivery-drill-footer) {
            grid-template-columns: 1fr;
          }
        }
        @media (max-width: 560px) {
          :global(.delivery-current-p0-stats) {
            grid-template-columns: 1fr;
          }
          :global(.delivery-drill-metrics) {
            grid-template-columns: 1fr;
          }
        }
      `}</style>
    </AppLayout>
  )
}
