'use client'

/**
 * 可觀測性 (/observability)
 * ========================
 * 首屏整合只讀 AI Agent deployment layout、監控合約矩陣與服務健康缺口，
 * 下方保留既有監控 / APM / 錯誤 / 應用 / 服務目錄獨立入口作為鑽取細節。
 */

import { useEffect, useMemo, useState, type ReactNode } from 'react'
import Link from 'next/link'
import type { Route as NextRoute } from 'next'
import { useTranslations } from 'next-intl'
import {
  Activity,
  AlertTriangle,
  BellRing,
  Boxes,
  CheckCircle2,
  CircuitBoard,
  Database,
  GitBranch,
  Globe2,
  Layers3,
  Lock,
  Network,
  PackageCheck,
  Radar,
  Route,
  Server,
  ShieldCheck,
  Workflow,
  Wrench,
  XCircle,
  type LucideIcon,
} from 'lucide-react'
import { AppLayout } from '@/components/layout'
import {
  apiClient,
  type AiAgentAutomationInventorySnapshot,
  type AiAgentDeploymentLayoutSnapshot,
  type ObservabilityContractMatrixSnapshot,
  type ServiceHealthGapMatrixSnapshot,
} from '@/lib/api-client'
import { cn } from '@/lib/utils'

type CommandState = {
  deployment: AiAgentDeploymentLayoutSnapshot | null
  observability: ObservabilityContractMatrixSnapshot | null
  serviceHealth: ServiceHealthGapMatrixSnapshot | null
  inventory: AiAgentAutomationInventorySnapshot | null
  loading: boolean
  error: boolean
}

type Tone = 'ok' | 'warn' | 'danger' | 'neutral'

const DOMAIN_ICONS: Record<string, LucideIcon> = {
  hosts: Server,
  projects: GitBranch,
  websites: Globe2,
  services: Workflow,
  packages: PackageCheck,
  tools: Wrench,
  learning: CircuitBoard,
}

const DOMAIN_ORDER = ['hosts', 'projects', 'websites', 'services', 'packages', 'tools', 'learning']

function toneClass(tone: Tone) {
  if (tone === 'ok') return 'border-emerald-200 bg-emerald-50 text-emerald-700'
  if (tone === 'warn') return 'border-amber-200 bg-amber-50 text-amber-700'
  if (tone === 'danger') return 'border-rose-200 bg-rose-50 text-rose-700'
  return 'border-[#e0ddd4] bg-white text-[#141413]'
}

function riskTone(status?: string): Tone {
  if (!status) return 'neutral'
  if (status === 'verified' || status === 'active_governed' || status === 'read_only_layout') return 'ok'
  if (status === 'action_required' || status === 'planned' || status === 'candidate_only') return 'warn'
  if (status === 'blocked' || status === 'blocked_by_gate' || status === 'critical') return 'danger'
  return 'neutral'
}

function formatNumber(value?: number | null) {
  if (typeof value !== 'number' || Number.isNaN(value)) return '--'
  return new Intl.NumberFormat('zh-TW').format(value)
}

function formatDateTime(value?: string) {
  if (!value) return '--'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '--'
  return date.toLocaleString('zh-TW', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function countRuntimeAllowedBoundaries(boundaries?: Record<string, boolean>) {
  return Object.entries(boundaries ?? {}).filter(([key, allowed]) => {
    if (!allowed) return false
    return !key.startsWith('read_only')
  }).length
}

function MetricTile({
  label,
  value,
  detail,
  icon,
  tone = 'neutral',
}: {
  label: string
  value: ReactNode
  detail: string
  icon: ReactNode
  tone?: Tone
}) {
  return (
    <div className="min-w-0 border border-[#e0ddd4] bg-white p-4">
      <div className="flex min-w-0 items-start justify-between gap-3">
        <div className="min-w-0">
          <p className="text-xs font-medium text-[#87867f]">{label}</p>
          <p className="mt-2 truncate font-['Syne'] text-3xl font-bold leading-none text-[#141413]">
            {value}
          </p>
        </div>
        <div className={cn('flex h-9 w-9 shrink-0 items-center justify-center border', toneClass(tone))}>
          {icon}
        </div>
      </div>
      <p className="mt-3 min-w-0 text-sm leading-6 text-[#5f5d57]">{detail}</p>
    </div>
  )
}

function SectionHeader({
  eyebrow,
  title,
  detail,
}: {
  eyebrow: string
  title: string
  detail: string
}) {
  return (
    <div className="mb-4 flex min-w-0 flex-col gap-1">
      <p className="text-xs font-semibold text-[#d97757]">{eyebrow}</p>
      <h2 className="font-['Syne'] text-xl font-bold leading-tight text-[#141413]">{title}</h2>
      <p className="max-w-4xl text-sm leading-6 text-[#5f5d57]">{detail}</p>
    </div>
  )
}

function StatusChip({ children, tone = 'neutral' }: { children: ReactNode; tone?: Tone }) {
  return (
    <span className={cn('inline-flex min-h-[24px] max-w-full items-center border px-2 py-1 text-xs font-medium', toneClass(tone))}>
      <span className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap">{children}</span>
    </span>
  )
}

function MiniBar({ value, tone = 'ok' }: { value: number; tone?: Tone }) {
  const color = tone === 'danger' ? 'bg-rose-500' : tone === 'warn' ? 'bg-amber-500' : 'bg-emerald-600'
  return (
    <div className="h-2 overflow-hidden bg-[#ebe8df]">
      <div className={cn('h-full', color)} style={{ width: `${Math.max(0, Math.min(value, 100))}%` }} />
    </div>
  )
}

function AssetLedgerCard({
  label,
  value,
  detail,
  meta,
  Icon,
  tone,
  progress,
}: {
  label: string
  value: ReactNode
  detail: string
  meta: string
  Icon: LucideIcon
  tone: Tone
  progress: number
}) {
  return (
    <div className="min-w-0 border border-[#e0ddd4] bg-white p-4">
      <div className="flex min-w-0 items-start justify-between gap-3">
        <div className="min-w-0">
          <p className="truncate text-xs font-semibold uppercase text-[#87867f]">{label}</p>
          <p className="mt-2 font-['Syne'] text-3xl font-bold leading-none text-[#141413]">{value}</p>
        </div>
        <div className={cn('flex h-9 w-9 shrink-0 items-center justify-center border', toneClass(tone))}>
          <Icon className="h-5 w-5" />
        </div>
      </div>
      <p className="mt-3 min-h-[42px] text-sm leading-5 text-[#5f5d57]">{detail}</p>
      <div className="mt-4">
        <MiniBar value={progress} tone={tone} />
        <p className="mt-2 min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-xs text-[#87867f]">{meta}</p>
      </div>
    </div>
  )
}

export default function ObservabilityPage({ params }: { params: { locale: string } }) {
  const nav = useTranslations('nav')
  const t = useTranslations('observabilityCommand')
  const [state, setState] = useState<CommandState>({
    deployment: null,
    observability: null,
    serviceHealth: null,
    inventory: null,
    loading: true,
    error: false,
  })

  useEffect(() => {
    let alive = true

    async function load() {
      setState(prev => ({ ...prev, loading: true, error: false }))
      const [deployment, observability, serviceHealth, inventory] = await Promise.allSettled([
        apiClient.getAiAgentDeploymentLayout(),
        apiClient.getObservabilityContractMatrix(),
        apiClient.getServiceHealthGapMatrix(),
        apiClient.getAiAgentAutomationInventorySnapshot(),
      ])

      if (!alive) return

      setState({
        deployment: deployment.status === 'fulfilled' ? deployment.value : null,
        observability: observability.status === 'fulfilled' ? observability.value : null,
        serviceHealth: serviceHealth.status === 'fulfilled' ? serviceHealth.value : null,
        inventory: inventory.status === 'fulfilled' ? inventory.value : null,
        loading: false,
        error: [deployment, observability, serviceHealth, inventory].some(result => result.status === 'rejected'),
      })
    }

    load()
    return () => {
      alive = false
    }
  }, [])

  const statusLabels = useMemo(
    () => ({
      active_governed: t('values.activeGoverned'),
      read_only_layout: t('values.readOnlyLayout'),
      blocked_by_gate: t('values.blockedByGate'),
      planned: t('values.planned'),
      candidate_only: t('values.candidateOnly'),
      verified: t('values.verified'),
      action_required: t('values.actionRequired'),
      blocked: t('values.blocked'),
      failure_only: t('values.failureOnly'),
      action_required_policy: t('values.actionRequiredPolicy'),
      approval_required: t('values.approvalRequired'),
      daily_summary_only: t('values.dailySummaryOnly'),
      no_direct_notify: t('values.noDirectNotify'),
    }),
    [t]
  )

  const valueLabel = (value?: string) => {
    if (!value) return '--'
    return statusLabels[value as keyof typeof statusLabels] ?? value.replaceAll('_', ' ')
  }

  const deploymentTargets = state.deployment?.deployment_targets ?? []
  const serviceTargets = state.serviceHealth?.service_health_targets ?? []
  const observabilitySurfaces = state.observability?.observability_surfaces ?? []
  const totalDecisionTargets = deploymentTargets.length + serviceTargets.length + observabilitySurfaces.length
  const readableTargets =
    deploymentTargets.filter(target => target.deployment_state !== 'planned' && target.deployment_state !== 'candidate_only').length +
    serviceTargets.filter(target => target.status === 'verified').length +
    observabilitySurfaces.filter(surface => surface.status === 'verified').length
  const decisionCoverage = totalDecisionTargets === 0 ? 0 : Math.round((readableTargets / totalDecisionTargets) * 100)
  const actionRequired =
    (state.observability?.rollups.surface_ids_requiring_action.length ?? 0) +
    (state.serviceHealth?.rollups.target_ids_requiring_action.length ?? 0) +
    (state.deployment?.rollups.approval_required_target_ids.length ?? 0)
  const runtimeGateCount =
    countRuntimeAllowedBoundaries(state.observability?.operation_boundaries) +
    countRuntimeAllowedBoundaries(state.serviceHealth?.operation_boundaries) +
    Object.values(state.deployment?.approval_boundaries ?? {}).filter(Boolean).length +
    (state.serviceHealth?.rollups.service_restart_allowed_count ?? 0) +
    (state.serviceHealth?.rollups.endpoint_change_allowed_count ?? 0) +
    (state.serviceHealth?.rollups.active_probe_allowed_count ?? 0) +
    (state.serviceHealth?.rollups.notification_send_allowed_count ?? 0) +
    (state.serviceHealth?.rollups.runtime_execution_allowed_count ?? 0)

  const domainRows = DOMAIN_ORDER.map(domainId => {
    const domain = state.deployment?.domains.find(item => item.domain_id === domainId)
    const targets = deploymentTargets.filter(target => target.domain_id === domainId)
    const approvalRequired = targets.filter(target => state.deployment?.rollups.approval_required_target_ids.includes(target.target_id)).length
    const verified = targets.filter(target => target.deployment_state === 'active_governed' || target.deployment_state === 'read_only_layout').length
    return {
      domainId,
      label: domain?.display_name ?? domainId,
      description: domain?.description ?? '',
      count: targets.length,
      verified,
      approvalRequired,
      Icon: DOMAIN_ICONS[domainId] ?? Boxes,
    }
  })

  const topologyNodes = [
    {
      key: 'hosts',
      label: t('topology.hosts'),
      value: state.deployment?.rollups.by_domain.hosts ?? 0,
      detail: t('topology.hostsDetail'),
      Icon: Server,
      tone: 'ok' as Tone,
    },
    {
      key: 'products',
      label: t('topology.products'),
      value: (state.deployment?.rollups.by_domain.projects ?? 0) + (state.deployment?.rollups.by_domain.websites ?? 0),
      detail: t('topology.productsDetail'),
      Icon: Globe2,
      tone: 'ok' as Tone,
    },
    {
      key: 'services',
      label: t('topology.services'),
      value: state.serviceHealth?.rollups.total_targets ?? 0,
      detail: t('topology.servicesDetail'),
      Icon: Workflow,
      tone: 'warn' as Tone,
    },
    {
      key: 'signals',
      label: t('topology.signals'),
      value: state.observability?.rollups.total_surfaces ?? 0,
      detail: t('topology.signalsDetail'),
      Icon: Activity,
      tone: 'warn' as Tone,
    },
    {
      key: 'sre',
      label: t('topology.sre'),
      value: state.deployment?.telegram_contract.primary_gateway ? 1 : 0,
      detail: t('topology.sreDetail'),
      Icon: BellRing,
      tone: 'neutral' as Tone,
    },
    {
      key: 'ai',
      label: t('topology.ai'),
      value: state.inventory?.program_status.overall_completion_percent ?? '--',
      detail: t('topology.aiDetail'),
      Icon: CircuitBoard,
      tone: 'danger' as Tone,
    },
  ]

  const flowSteps = [
    {
      label: t('flow.collect'),
      value: formatNumber(state.deployment?.rollups.total_targets),
      detail: t('flow.collectDetail'),
    },
    {
      label: t('flow.correlate'),
      value: formatNumber(state.serviceHealth?.rollups.total_targets),
      detail: t('flow.correlateDetail'),
    },
    {
      label: t('flow.classify'),
      value: formatNumber(state.observability?.rollups.classification_gap_ids.length),
      detail: t('flow.classifyDetail'),
    },
    {
      label: t('flow.route'),
      value: formatNumber(state.deployment?.rollups.by_telegram_policy.action_required),
      detail: t('flow.routeDetail'),
    },
    {
      label: t('flow.gate'),
      value: formatNumber(runtimeGateCount),
      detail: t('flow.gateDetail'),
    },
  ]

  const assetLedgerRows = [
    {
      key: 'scope',
      label: t('assetLedger.scopeLabel'),
      value: formatNumber(state.deployment?.rollups.total_targets),
      detail: t('assetLedger.scopeDetail', {
        hosts: state.deployment?.rollups.by_domain.hosts ?? 0,
        projects: state.deployment?.rollups.by_domain.projects ?? 0,
        websites: state.deployment?.rollups.by_domain.websites ?? 0,
      }),
      meta: t('assetLedger.scopeMeta', {
        domains: state.deployment?.domains.length ?? 0,
        approval: state.deployment?.rollups.approval_required_target_ids.length ?? 0,
      }),
      Icon: Network,
      tone: 'ok' as Tone,
      progress: decisionCoverage,
    },
    {
      key: 'signals',
      label: t('assetLedger.signalLabel'),
      value: formatNumber(state.observability?.rollups.total_surfaces),
      detail: t('assetLedger.signalDetail', {
        gaps: state.observability?.rollups.classification_gap_ids.length ?? 0,
        noise: state.observability?.rollups.noise_reduction_opportunities_total ?? 0,
      }),
      meta: t('assetLedger.signalMeta', {
        required: state.observability?.rollups.surface_ids_requiring_action.length ?? 0,
        approval: state.observability?.rollups.approval_required_opportunity_ids.length ?? 0,
      }),
      Icon: Activity,
      tone: (state.observability?.rollups.surface_ids_requiring_action.length ?? 0) > 0 ? 'warn' as Tone : 'ok' as Tone,
      progress: state.observability?.program_status.overall_completion_percent ?? 0,
    },
    {
      key: 'health',
      label: t('assetLedger.healthLabel'),
      value: formatNumber(state.serviceHealth?.rollups.total_targets),
      detail: t('assetLedger.healthDetail', {
        health: state.serviceHealth?.rollups.health_gap_ids.length ?? 0,
        stale: state.serviceHealth?.rollups.stale_endpoint_ids.length ?? 0,
      }),
      meta: t('assetLedger.healthMeta', {
        restart: state.serviceHealth?.rollups.service_restart_allowed_count ?? 0,
        notify: state.serviceHealth?.rollups.notification_send_allowed_count ?? 0,
      }),
      Icon: Workflow,
      tone: (state.serviceHealth?.rollups.target_ids_requiring_action.length ?? 0) > 0 ? 'warn' as Tone : 'ok' as Tone,
      progress: state.serviceHealth?.program_status.overall_completion_percent ?? 0,
    },
    {
      key: 'learning',
      label: t('assetLedger.learningLabel'),
      value: `${state.inventory?.program_status.overall_completion_percent ?? 0}%`,
      detail: t('assetLedger.learningDetail', {
        assets: state.inventory?.assets.length ?? 0,
        tasks: state.inventory?.tasks.length ?? 0,
      }),
      meta: t('assetLedger.learningMeta', {
        approval: state.inventory?.task_approval_boundary_rollup.tasks_requiring_explicit_approval.length ?? 0,
        blocked: state.inventory?.task_approval_boundary_rollup.tasks_with_blocked_operations.length ?? 0,
      }),
      Icon: CircuitBoard,
      tone: 'warn' as Tone,
      progress: state.inventory?.program_status.overall_completion_percent ?? 0,
    },
    {
      key: 'sre',
      label: t('assetLedger.sreLabel'),
      value: state.deployment?.telegram_contract.primary_gateway ? '1' : '0',
      detail: t('assetLedger.sreDetail', {
        action: state.deployment?.rollups.by_telegram_policy.action_required ?? 0,
        approval: state.deployment?.rollups.by_telegram_policy.approval_required ?? 0,
      }),
      meta: t('assetLedger.sreMeta'),
      Icon: BellRing,
      tone: state.deployment?.telegram_contract.primary_gateway ? 'ok' as Tone : 'warn' as Tone,
      progress: state.deployment?.telegram_contract.primary_gateway ? 100 : 0,
    },
    {
      key: 'runtime',
      label: t('assetLedger.runtimeLabel'),
      value: formatNumber(runtimeGateCount),
      detail: t('assetLedger.runtimeDetail'),
      meta: t('assetLedger.runtimeMeta'),
      Icon: Lock,
      tone: 'danger' as Tone,
      progress: 0,
    },
  ]

  const drilldownLinks = [
    {
      id: 'monitoring',
      label: nav('monitoring'),
      href: `/${params.locale}/monitoring`,
      Icon: Activity,
    },
    {
      id: 'apm',
      label: nav('apm'),
      href: `/${params.locale}/apm`,
      Icon: Radar,
    },
    {
      id: 'errors',
      label: nav('errors'),
      href: `/${params.locale}/errors`,
      Icon: AlertTriangle,
    },
    {
      id: 'apps',
      label: nav('apps'),
      href: `/${params.locale}/apps`,
      Icon: Boxes,
    },
    {
      id: 'services',
      label: nav('services'),
      href: `/${params.locale}/services`,
      Icon: Server,
    },
  ]

  const sourceLabel = t('source', {
    generated: formatDateTime(state.observability?.generated_at ?? state.deployment?.generated_at ?? state.serviceHealth?.generated_at),
    current: state.observability?.program_status.current_task_id ?? state.serviceHealth?.program_status.current_task_id ?? '--',
    next: state.observability?.program_status.next_task_id ?? state.serviceHealth?.program_status.next_task_id ?? '--',
  })

  return (
    <AppLayout locale={params.locale}>
      <main className="min-h-screen max-w-full overflow-x-hidden bg-[#f5f4ed]">
        <section className="border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-6 md:px-8">
          <div className="mx-auto flex max-w-[1600px] flex-col gap-6">
            <div className="flex min-w-0 flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
              <div className="min-w-0">
                <p className="text-sm font-semibold text-[#d97757]">{t('eyebrow')}</p>
                <h1 className="mt-2 font-['Syne'] text-3xl font-bold leading-tight text-[#141413] md:text-4xl">
                  {t('title')}
                </h1>
                <p className="mt-3 max-w-5xl text-sm leading-6 text-[#5f5d57] md:text-base">{t('subtitle')}</p>
              </div>
              <div className="grid min-w-0 grid-cols-2 gap-2 md:grid-cols-4 lg:w-[520px]">
                <StatusChip tone={state.loading ? 'neutral' : 'ok'}>{state.loading ? t('loading') : t('liveRead')}</StatusChip>
                <StatusChip tone={state.error ? 'warn' : 'ok'}>{state.error ? t('partialData') : t('apiReady')}</StatusChip>
                <StatusChip tone="danger">{t('runtimeGate', { count: runtimeGateCount })}</StatusChip>
                <StatusChip tone="neutral">{sourceLabel}</StatusChip>
              </div>
            </div>

            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
              <MetricTile
                label={t('metrics.decisionCoverage')}
                value={`${decisionCoverage}%`}
                detail={t('metrics.decisionCoverageDetail', { readable: readableTargets, total: totalDecisionTargets })}
                icon={<GaugeIcon />}
                tone={decisionCoverage >= 80 ? 'ok' : decisionCoverage >= 60 ? 'warn' : 'danger'}
              />
              <MetricTile
                label={t('metrics.totalScope')}
                value={formatNumber(state.deployment?.rollups.total_targets)}
                detail={t('metrics.totalScopeDetail', {
                  hosts: state.deployment?.rollups.by_domain.hosts ?? 0,
                  projects: state.deployment?.rollups.by_domain.projects ?? 0,
                  websites: state.deployment?.rollups.by_domain.websites ?? 0,
                })}
                icon={<Network className="h-5 w-5" />}
                tone="ok"
              />
              <MetricTile
                label={t('metrics.actionRequired')}
                value={formatNumber(actionRequired)}
                detail={t('metrics.actionRequiredDetail', {
                  health: state.serviceHealth?.rollups.health_gap_ids.length ?? 0,
                  stale: state.serviceHealth?.rollups.stale_endpoint_ids.length ?? 0,
                })}
                icon={<AlertTriangle className="h-5 w-5" />}
                tone={actionRequired > 0 ? 'warn' : 'ok'}
              />
              <MetricTile
                label={t('metrics.runtimeGate')}
                value={formatNumber(runtimeGateCount)}
                detail={t('metrics.runtimeGateDetail')}
                icon={<Lock className="h-5 w-5" />}
                tone="danger"
              />
            </div>
          </div>
        </section>

        <div className="mx-auto flex max-w-[1600px] flex-col gap-6 px-4 py-6 md:px-8">
          <section className="border-y border-[#e0ddd4] bg-transparent py-2">
            <SectionHeader
              eyebrow={t('sections.assetLedgerEyebrow')}
              title={t('sections.assetLedgerTitle')}
              detail={t('sections.assetLedgerDetail')}
            />
            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
              {assetLedgerRows.map(({ key, ...row }) => (
                <AssetLedgerCard key={key} {...row} />
              ))}
            </div>
          </section>

          <section className="border-y border-[#e0ddd4] bg-transparent py-2">
            <SectionHeader
              eyebrow={t('sections.scopeEyebrow')}
              title={t('sections.scopeTitle')}
              detail={t('sections.scopeDetail')}
            />
            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
              {domainRows.map(row => {
                const coverage = row.count === 0 ? 0 : Math.round((row.verified / row.count) * 100)
                const tone: Tone = row.approvalRequired > 0 ? 'warn' : 'ok'
                return (
                  <div key={row.domainId} className="min-w-0 border border-[#e0ddd4] bg-white p-4">
                    <div className="flex min-w-0 items-start justify-between gap-3">
                      <div className="flex min-w-0 items-center gap-3">
                        <div className={cn('flex h-9 w-9 shrink-0 items-center justify-center border', toneClass(tone))}>
                          <row.Icon className="h-5 w-5" />
                        </div>
                        <div className="min-w-0">
                          <h3 className="truncate text-base font-semibold text-[#141413]">{row.label}</h3>
                          <p className="mt-1 text-xs text-[#87867f]">{t('scope.targets', { count: row.count })}</p>
                        </div>
                      </div>
                      <StatusChip tone={tone}>{t('scope.approval', { count: row.approvalRequired })}</StatusChip>
                    </div>
                    <p className="mt-3 line-clamp-2 min-h-[40px] text-sm leading-5 text-[#5f5d57]">{row.description}</p>
                    <div className="mt-4">
                      <div className="mb-2 flex items-center justify-between text-xs text-[#5f5d57]">
                        <span>{t('scope.readable')}</span>
                        <span>{coverage}%</span>
                      </div>
                      <MiniBar value={coverage} tone={tone} />
                    </div>
                  </div>
                )
              })}
            </div>
          </section>

          <section className="grid gap-6 xl:grid-cols-[1.35fr_0.65fr]">
            <div className="min-w-0 border border-[#e0ddd4] bg-white p-5">
              <SectionHeader
                eyebrow={t('sections.topologyEyebrow')}
                title={t('sections.topologyTitle')}
                detail={t('sections.topologyDetail')}
              />
              <div className="grid gap-3 md:grid-cols-3">
                {topologyNodes.map((node, index) => (
                  <div key={node.key} className="relative min-w-0 border border-[#e0ddd4] bg-[#faf9f3] p-4">
                    {index < topologyNodes.length - 1 && (
                      <div className="pointer-events-none absolute left-full top-1/2 hidden h-px w-3 bg-[#d6d1c3] md:block" />
                    )}
                    <div className="flex min-w-0 items-start justify-between gap-3">
                      <div className="min-w-0">
                        <p className="text-xs font-medium text-[#87867f]">{node.label}</p>
                        <p className="mt-2 font-['Syne'] text-3xl font-bold leading-none text-[#141413]">
                          {formatNumber(typeof node.value === 'number' ? node.value : Number.NaN)}
                        </p>
                      </div>
                      <div className={cn('flex h-9 w-9 shrink-0 items-center justify-center border', toneClass(node.tone))}>
                        <node.Icon className="h-5 w-5" />
                      </div>
                    </div>
                    <p className="mt-3 text-sm leading-5 text-[#5f5d57]">{node.detail}</p>
                  </div>
                ))}
              </div>
            </div>

            <div className="min-w-0 border border-[#e0ddd4] bg-white p-5">
              <SectionHeader
                eyebrow={t('sections.flowEyebrow')}
                title={t('sections.flowTitle')}
                detail={t('sections.flowDetail')}
              />
              <div className="flex flex-col">
                {flowSteps.map((step, index) => (
                  <div key={step.label} className="grid min-w-0 grid-cols-[32px_1fr] gap-3">
                    <div className="flex flex-col items-center">
                      <div className="flex h-7 w-7 items-center justify-center border border-[#d97757] bg-[#fff7ed] text-xs font-bold text-[#d97757]">
                        {index + 1}
                      </div>
                      {index < flowSteps.length - 1 && <div className="h-full min-h-8 w-px bg-[#e0ddd4]" />}
                    </div>
                    <div className="min-w-0 pb-4">
                      <div className="flex min-w-0 items-center justify-between gap-3">
                        <h3 className="truncate text-sm font-semibold text-[#141413]">{step.label}</h3>
                        <span className="font-['DM_Mono'] text-sm font-semibold text-[#141413]">{step.value}</span>
                      </div>
                      <p className="mt-1 text-sm leading-5 text-[#5f5d57]">{step.detail}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </section>

          <section className="grid gap-6 xl:grid-cols-3">
            <div className="min-w-0 border border-[#e0ddd4] bg-white p-5 xl:col-span-2">
              <SectionHeader
                eyebrow={t('sections.signalEyebrow')}
                title={t('sections.signalTitle')}
                detail={t('sections.signalDetail')}
              />
              <div className="grid gap-3 md:grid-cols-2">
                {observabilitySurfaces.map(surface => (
                  <div key={surface.surface_id} className="min-w-0 border border-[#e0ddd4] bg-[#faf9f3] p-4">
                    <div className="flex min-w-0 items-start justify-between gap-3">
                      <div className="min-w-0">
                        <h3 className="truncate text-sm font-semibold text-[#141413]">{surface.display_name}</h3>
                        <p className="mt-1 text-xs text-[#87867f]">{valueLabel(surface.kind)}</p>
                      </div>
                      <StatusChip tone={riskTone(surface.status)}>{valueLabel(surface.status)}</StatusChip>
                    </div>
                    <p className="mt-3 line-clamp-3 text-sm leading-5 text-[#5f5d57]">{surface.next_action}</p>
                    <div className="mt-3 flex flex-wrap gap-2">
                      <StatusChip tone={riskTone(surface.noise_policy_status)}>{valueLabel(surface.noise_policy_status)}</StatusChip>
                      <StatusChip tone="neutral">{valueLabel(surface.evidence_status)}</StatusChip>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div className="min-w-0 border border-[#e0ddd4] bg-white p-5">
              <SectionHeader
                eyebrow={t('sections.gapEyebrow')}
                title={t('sections.gapTitle')}
                detail={t('sections.gapDetail')}
              />
              <div className="flex flex-col gap-3">
                {state.serviceHealth?.health_gaps.slice(0, 4).map(gap => (
                  <div key={gap.gap_id} className="min-w-0 border border-[#e0ddd4] bg-[#faf9f3] p-3">
                    <div className="flex min-w-0 items-start justify-between gap-3">
                      <h3 className="min-w-0 text-sm font-semibold leading-5 text-[#141413]">{gap.display_name}</h3>
                      <StatusChip tone={riskTone(gap.severity)}>{valueLabel(gap.severity)}</StatusChip>
                    </div>
                    <p className="mt-2 text-sm leading-5 text-[#5f5d57]">{gap.summary}</p>
                  </div>
                ))}
              </div>
            </div>
          </section>

          <section className="border border-[#e0ddd4] bg-white p-5">
            <SectionHeader
              eyebrow={t('sections.boundaryEyebrow')}
              title={t('sections.boundaryTitle')}
              detail={t('sections.boundaryDetail')}
            />
            <div className="grid gap-3 md:grid-cols-3">
              <div className="border border-[#e0ddd4] bg-[#faf9f3] p-4">
                <div className="flex items-center gap-2 text-sm font-semibold text-[#141413]">
                  <ShieldCheck className="h-4 w-4 text-emerald-600" />
                  {t('boundary.readOnly')}
                </div>
                <p className="mt-2 text-sm leading-5 text-[#5f5d57]">{t('boundary.readOnlyDetail')}</p>
              </div>
              <div className="border border-[#e0ddd4] bg-[#faf9f3] p-4">
                <div className="flex items-center gap-2 text-sm font-semibold text-[#141413]">
                  <XCircle className="h-4 w-4 text-rose-600" />
                  {t('boundary.noRuntime')}
                </div>
                <p className="mt-2 text-sm leading-5 text-[#5f5d57]">{t('boundary.noRuntimeDetail')}</p>
              </div>
              <div className="border border-[#e0ddd4] bg-[#faf9f3] p-4">
                <div className="flex items-center gap-2 text-sm font-semibold text-[#141413]">
                  <CheckCircle2 className="h-4 w-4 text-emerald-600" />
                  {t('boundary.sreRoom')}
                </div>
                <p className="mt-2 text-sm leading-5 text-[#5f5d57]">{t('boundary.sreRoomDetail')}</p>
              </div>
            </div>
          </section>

          <section className="min-w-0 border-t border-[#e0ddd4] pt-5">
            <SectionHeader
              eyebrow={t('sections.drilldownEyebrow')}
              title={t('sections.drilldownTitle')}
              detail={t('sections.drilldownDetail')}
            />
            <div className="grid min-w-0 gap-3 sm:grid-cols-2 xl:grid-cols-5">
              {drilldownLinks.map(({ id, label, href, Icon }) => (
                <Link
                  key={id}
                  href={href as NextRoute}
                  className="group min-w-0 border border-[#e0ddd4] bg-white p-4 text-[#141413] no-underline transition hover:border-[#d97757] hover:bg-[#fffaf7]"
                >
                  <div className="flex items-center justify-between gap-3">
                    <span className="flex h-9 w-9 shrink-0 items-center justify-center border border-[#d8d3c7] bg-[#faf9f3] text-[#5f5d57] group-hover:text-[#d97757]">
                      <Icon className="h-4 w-4" aria-hidden="true" />
                    </span>
                    <span className="min-w-0 text-right text-[11px] font-semibold text-[#87867f]">
                      {href.replace(`/${params.locale}`, '')}
                    </span>
                  </div>
                  <div className="mt-4 min-w-0 text-sm font-semibold leading-5">
                    {label}
                  </div>
                </Link>
              ))}
            </div>
          </section>
        </div>
      </main>
    </AppLayout>
  )
}

function GaugeIcon() {
  return <Radar className="h-5 w-5" />
}
