'use client'

/**
 * AWOOOI AI Center 主頁
 * ====================================
 * 2欄佈局（Sidebar 由 AppLayout 提供）: Feed + RightPanel
 *
 * 專案鐵律: 使用真實數據 Hook，禁止假數據！
 *
 * @updated 2026-04-02 Claude Code — Metrics Strip 7指標視覺強化
 * @updated 2026-04-03 Claude Code — 監控工具區塊 (Grafana/Prometheus/SigNoz/Gitea)
 *   串接: incidents(count/P0/MTTR/autoRemediation) + dashboard(serviceHealth/pendingApprovals/podHealth)
 * @updated 2026-04-03 Claude Code — 完整對齊 figma-v2 設計
 *   figma-v2 重點: 7指標(含今日事件) + 監控工具左彩色條 + 可點擊連結 + meta行
 */

import React from 'react'
import { useTranslations } from 'next-intl'
import { useState, useEffect } from 'react'
import { useIncidents } from '@/hooks/useIncidents'
import { useIncidentStatusChains } from '@/hooks/useIncidentStatusChains'
import { useHosts, useDashboardStore, type Host } from '@/stores/dashboard.store'
import { IncidentCard } from '@/components/incident'
import { OpenClawPanel } from '@/components/ai/openclaw-panel'
import { AppLayout } from '@/components/layout'
import { PageTabs, type TabConfig } from '@/components/layout/page-tabs'
import { PulseSkeleton, CardSkeleton } from '@/components/shared/pulse-skeleton'
import { DispositionMini } from '@/components/shared/disposition-mini'
import { RecentActivity } from '@/components/shared/recent-activity'
import { PendingApprovalsCard } from '@/components/shared/pending-approvals-card'
import { AIModelStatus } from '@/components/shared/ai-model-status'
import { FlywheelKPICard } from '@/components/dashboard/flywheel-kpi-card'
import { AutomationEvidenceCard } from '@/components/dashboard/automation-evidence-card'

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? ''
const HOMEPAGE_STATUS_CHAIN_PREFETCH_LIMIT = 8
const HOMEPAGE_STATUS_CHAIN_CONCURRENCY = 2
const HOMEPAGE_STATUS_CHAIN_TIMEOUT_MS = 6000
const HOMEPAGE_INCIDENT_LIMIT = HOMEPAGE_STATUS_CHAIN_PREFETCH_LIMIT
const HOMEPAGE_QUALITY_SUMMARY_LIMIT = 8
const HOMEPAGE_QUALITY_SUMMARY_TIMEOUT_MS = 8000
const HOMEPAGE_BLUEPRINT_STAGE_KEYS = ['signal', 'intake', 'ai', 'mcp', 'playbook', 'ansible', 'approval', 'verify'] as const
type HomepageBlueprintStageKey = typeof HOMEPAGE_BLUEPRINT_STAGE_KEYS[number]

interface HomepageAutomationQualitySummary {
  average_score?: number
  evaluated_total?: number
  verified_auto_repair_total?: number
  gate_failures?: HomepageAutomationGateFailure[]
  execution_backend_summary?: HomepageExecutionBackendSummary | null
  ansible_runtime?: HomepageAnsibleRuntime | null
  production_claim?: {
    can_claim_full_auto_repair?: boolean
    reason?: string | null
  }
}

interface HomepageAutomationGateFailure {
  gate?: string | null
  total?: number | null
  statuses?: Record<string, number>
}

interface HomepageExecutionBackendSummary {
  operation_records_total?: number
  effective_execution_records_total?: number
  audit_only_operation_records_total?: number
  auto_repair_execution_records_total?: number
  ansible_candidate_total?: number
  ansible_check_mode_total?: number
  ansible_apply_total?: number
  ansible_pending_check_mode_total?: number
}

interface HomepageAnsibleRuntime {
  can_run_check_mode?: boolean
  blockers?: string[]
}

interface HomepageCallbackReplyAuditSummary {
  outbound_reply_markup_missing_trace_ref_total?: number
  outbound_reply_markup_missing_trace_ref_recent_1h_total?: number
  outbound_reply_markup_missing_trace_ref_recent_24h_total?: number
  outbound_reply_markup_trace_ref_after_gap_total?: number
  outbound_reply_markup_trace_ref_gap_status?: string | null
  outbound_reply_markup_trace_ref_gap_next_action?: string | null
  outbound_reply_markup_trace_ref_gap_recovery_status?: string | null
}

interface HomepageCallbackRepliesResponse {
  total?: number
  summary?: HomepageCallbackReplyAuditSummary | null
}

interface HomepageAiRouteStatusResponse {
  lane_mode?: string | null
  selected_provider?: string | null
  skipped_lanes?: Array<{ provider_name?: string | null }>
  operator_action?: {
    human_required?: boolean | null
    action?: string | null
    reason?: string | null
  } | null
}

interface HomepageKmStaleCandidatesResponse {
  total_stale?: number
  threshold_days?: number
}

interface HomepageDossierCoverageResponse {
  summary?: {
    source_count?: number
    source_ref_total?: number
    missing_source_refs_total?: number
    duplicate_total?: number
    alert_ref_total?: number
    sentry_ref_total?: number
    signoz_ref_total?: number
    latest_received_at?: string | null
  }
}

interface HomepageEventRecurrenceResponse {
  summary?: {
    source_event_total?: number
    linked_run_total?: number
    unlinked_event_total?: number
    auto_repair_linked_total?: number
    verified_repair_group_total?: number
    open_work_item_group_total?: number
    automation_gap_group_total?: number
    recurrent_group_total?: number
    recurrence_group_total?: number
    duplicate_event_total?: number
    latest_received_at?: string | null
  }
}

interface HomepageRunSummary {
  run_id?: string
  state?: string
  created_at?: string | null
  remediation_summary?: {
    status?: string | null
    evidence_total?: number | null
    mcp_observation_total?: number | null
    mcp_observation_success?: number | null
    mcp_observation_failed?: number | null
    latest_mcp_server?: string | null
    latest_route?: string | null
    has_mcp_investigation?: boolean | null
    has_dry_run?: boolean | null
    human_gate_open?: boolean | null
  } | null
}

interface HomepageRunsListResponse {
  runs?: HomepageRunSummary[]
  total?: number
}

interface HomepageCicdEventsResponse {
  total?: number
  items?: Array<{
    stage?: string | null
    status?: string | null
    summary?: string | null
    commit_sha?: string | null
    needs_attention?: boolean | null
    created_at?: string | null
  }>
}

interface HomepageKmOwnerReviewBurndownResponse {
  burn_down_status?: string | null
  current_snapshot?: {
    stale_count?: number
    total_count?: number
    stale_ratio?: number
    threshold?: number
    stale_days?: number
  } | null
  entries_to_threshold?: number | null
  pending_owner_reviews?: number | null
  completed_owner_reviews?: number | null
  completion_audit_total?: number | null
  stale_ratio_recheck_total?: number | null
  manual_review_required?: boolean | null
  generated_at?: string | null
}

interface HomepageAutomationBriefSnapshot {
  callbackReplies?: HomepageCallbackRepliesResponse | null
  aiRouteStatus?: HomepageAiRouteStatusResponse | null
  kmStaleCandidates?: HomepageKmStaleCandidatesResponse | null
  dossierCoverage?: HomepageDossierCoverageResponse | null
  dossierCoverageSentry?: HomepageDossierCoverageResponse | null
  dossierCoverageSignoz?: HomepageDossierCoverageResponse | null
  eventRecurrence?: HomepageEventRecurrenceResponse | null
  runsList?: HomepageRunsListResponse | null
  cicdEvents?: HomepageCicdEventsResponse | null
  kmOwnerReviewBurndown?: HomepageKmOwnerReviewBurndownResponse | null
}

type HomepageWorkTone = 'live' | 'progress' | 'blocked' | 'watching'

interface HomepageWorkItemSummary {
  key: string
  title: string
  status: string
  detail: string
  href: string
  tone: HomepageWorkTone
}

interface HomepageBlueprintStage extends HomepageWorkItemSummary {
  owner: string
  evidence: string
  nextAction: string
  liveEvidence: {
    metric: string
    detail: string
    source: string
    updated: string
  }
}

async function fetchHomepageJson<T>(url: string, signal?: AbortSignal): Promise<T | null> {
  try {
    const response = await fetch(url, { signal, cache: 'no-store' })
    if (!response.ok) return null
    return await response.json() as T
  } catch {
    return null
  }
}

// =============================================================================
// Tab 2: 告警 & 授權 (串接真實 API)
// =============================================================================

function AlertsAndApprovalsTab() {
  const t = useTranslations('dashboard')
  const [alerts, setAlerts] = useState<any[]>([])
  const [approvals, setApprovals] = useState<any[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    Promise.all([
      fetch(`${API_BASE}/api/v1/incidents`).then(r => r.ok ? r.json() : { incidents: [] }).catch(() => ({ incidents: [] })),
      fetch(`${API_BASE}/api/v1/approvals/pending`).then(r => r.ok ? r.json() : []).catch(() => []),
    ]).then(([incData, apprData]) => {
      setAlerts(incData.incidents ?? incData ?? [])
      setApprovals(Array.isArray(apprData) ? apprData : apprData.approvals ?? [])
    }).finally(() => setLoading(false))
  }, [])

  if (loading) return <CardSkeleton lines={4} />

  return (
    <div style={{ display: 'flex', gap: 20, padding: '16px 20px', flex: 1, overflow: 'hidden' }}>
      {/* 左: 告警列表 */}
      <div style={{ flex: 1, overflowY: 'auto' }}>
        <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 12, color: '#141413' }}>{t('alertEvents')} ({alerts.length})</div>
        {alerts.length === 0 ? (
          <div style={{ padding: 24, textAlign: 'center', color: '#87867f' }}>{t('noActiveAlerts')}</div>
        ) : alerts.map((a: any, i: number) => (
          <div key={a.incident_id || i} style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 10, padding: '10px 14px', marginBottom: 8 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 6px', borderRadius: 3, background: 'rgba(204,34,0,0.1)', color: '#cc2200' }}>{a.severity || 'P2'}</span>
              <span style={{ fontSize: 13, fontWeight: 600 }}>{a.title || a.incident_id}</span>
            </div>
            <div style={{ fontSize: 11, color: '#555550', marginTop: 4 }}>{a.affected_services?.join(', ') || '--'} · {a.status || '--'}</div>
          </div>
        ))}
      </div>
      {/* 右: 授權待批准 */}
      <div style={{ width: 400, flexShrink: 0, overflowY: 'auto' }}>
        <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 12, color: '#141413' }}>{t('pendingApprovalsTitle')} ({approvals.length})</div>
        {approvals.length === 0 ? (
          <div style={{ padding: 24, textAlign: 'center', color: '#87867f' }}>{t('noPendingApprovals')}</div>
        ) : approvals.map((ap: any, i: number) => (
          <div key={ap.id || i} style={{ background: '#faf9f3', border: '0.5px solid #e0ddd4', borderRadius: 8, padding: '10px 12px', marginBottom: 8 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: '#cc2200' }}>{ap.action || ap.title || '--'}</div>
            <div style={{ fontSize: 10, color: '#555550', marginTop: 2, fontFamily: "'JetBrains Mono', monospace" }}>{ap.resource || '--'}</div>
            <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
              <button
                onClick={() => {
                  fetch(`${API_BASE}/api/v1/approvals/${ap.id}/sign`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ signer: 'web-ui' }) })
                    .then(() => setApprovals(prev => prev.filter(x => x.id !== ap.id)))
                    .catch(() => {})
                }}
                style={{ flex: 1, padding: '5px 0', border: 'none', borderRadius: 5, fontSize: 11, fontWeight: 600, cursor: 'pointer', background: '#22C55E', color: '#fff' }}
              >{t('approve')}</button>
              <button
                onClick={() => {
                  fetch(`${API_BASE}/api/v1/approvals/${ap.id}/reject`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ reason: 'rejected-from-web' }) })
                    .then(() => setApprovals(prev => prev.filter(x => x.id !== ap.id)))
                    .catch(() => {})
                }}
                style={{ flex: 1, padding: '5px 0', border: '0.5px solid #e0ddd4', borderRadius: 5, fontSize: 11, cursor: 'pointer', background: '#fff', color: '#87867f' }}
              >{t('reject')}</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

// =============================================================================
// Tab 3: 活動串流 (串接真實 SSE)
// =============================================================================

function ActivityStreamTab() {
  const t = useTranslations('dashboard')
  const [events, setEvents] = useState<any[]>([])
  const [connected, setConnected] = useState(false)
  const [selectedIdx, setSelectedIdx] = useState<number | null>(null)

  useEffect(() => {
    const es = new EventSource(`${API_BASE}/api/v1/dashboard/stream`)
    es.onopen = () => setConnected(true)
    es.onmessage = (e) => {
      try {
        const data = JSON.parse(e.data)
        setEvents(prev => [{ ...data, _time: new Date().toLocaleTimeString('zh-TW', { hour: '2-digit', minute: '2-digit', second: '2-digit' }) }, ...prev].slice(0, 50))
      } catch {
        return
      }
    }
    es.onerror = () => setConnected(false)
    return () => es.close()
  }, [])

  const selected = selectedIdx !== null ? events[selectedIdx] : null
  const cot = selected?.data?.incident?.decision?.proposal_data ?? selected?.data?.proposal_data ?? null

  return (
    <div style={{ padding: '16px 20px', flex: 1, overflowY: 'auto' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <div style={{ width: 6, height: 6, borderRadius: '50%', background: connected ? '#22C55E' : '#cc2200' }} />
        <span style={{ fontSize: 14, fontWeight: 700 }}>{t('activityStream')}</span>
        <span style={{ fontSize: 11, color: '#87867f' }}>{connected ? t('sseConnected') : t('sseDisconnected')} · {events.length}</span>
      </div>
      {events.length === 0 ? (
        <div style={{ padding: 32, textAlign: 'center', color: '#87867f' }}>{t('waitingEvents')}</div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: cot ? '1fr 1fr' : '1fr', gap: 12 }}>
          {/* Event list */}
          <div>
            {events.map((ev, i) => (
              <div
                key={i}
                onClick={() => setSelectedIdx(i === selectedIdx ? null : i)}
                style={{
                  display: 'flex', gap: 8, padding: '7px 8px', borderBottom: '0.5px solid #f0ede5',
                  fontSize: 12, cursor: 'pointer', borderRadius: 5,
                  background: i === selectedIdx ? 'rgba(74,144,217,0.06)' : 'transparent',
                }}
              >
                <span style={{ fontSize: 10, color: '#87867f', fontFamily: "'JetBrains Mono', monospace", width: 60, flexShrink: 0 }}>{ev._time}</span>
                <span style={{ width: 5, height: 5, borderRadius: '50%', background: ev.type === 'HOST_UPDATE' ? '#22C55E' : '#4A90D9', marginTop: 5, flexShrink: 0 }} />
                <span style={{ flex: 1, minWidth: 0, lineHeight: 1.4, overflowWrap: 'anywhere', wordBreak: 'break-word' }}>
                  <b>{ev.type || 'EVENT'}</b>
                  {ev.data?.overall_status && ` · ${t('statusLabel')}: ${ev.data.overall_status}`}
                  {ev.data?.hosts && ` · ${ev.data.hosts.length} ${t('hostsLabel')}`}
                  {(ev.data?.incident?.decision?.proposal_data || ev.data?.proposal_data) && (
                    <span style={{ marginLeft: 4, fontSize: 9, background: 'rgba(74,144,217,0.12)', color: '#4A90D9', borderRadius: 3, padding: '1px 5px', fontWeight: 600 }}>COT</span>
                  )}
                </span>
              </div>
            ))}
            {selectedIdx === null && events.length > 0 && (
              <div style={{ marginTop: 8, fontSize: 10, color: '#87867f', textAlign: 'center' }}>{t('cotClickHint')}</div>
            )}
          </div>

          {/* Chain of Thought panel */}
          {cot && (
            <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 10, padding: '14px 16px', fontSize: 12 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: '#141413', marginBottom: 10 }}>{t('cotTitle')}</div>
              {/* Provider + confidence row */}
              <div style={{ display: 'flex', gap: 8, marginBottom: 10, flexWrap: 'wrap' }}>
                {cot.provider && (
                  <span style={{ fontSize: 10, background: 'rgba(74,144,217,0.1)', color: '#4A90D9', borderRadius: 4, padding: '2px 8px', fontWeight: 600 }}>
                    {t('cotProvider')}: {cot.provider}
                  </span>
                )}
                {cot.confidence !== undefined && (
                  <span style={{ fontSize: 10, background: cot.confidence >= 0.8 ? 'rgba(34,197,94,0.1)' : 'rgba(245,158,11,0.1)', color: cot.confidence >= 0.8 ? '#22C55E' : '#F59E0B', borderRadius: 4, padding: '2px 8px', fontWeight: 600 }}>
                    {t('cotConfidence')}: {Math.round(cot.confidence * 100)}%
                  </span>
                )}
                {cot.nemotron_latency_ms !== undefined && (
                  <span style={{ fontSize: 10, background: 'rgba(168,85,247,0.08)', color: '#A855F7', borderRadius: 4, padding: '2px 8px', fontWeight: 600 }}>
                    {t('cotLatency')}: {cot.nemotron_latency_ms}ms
                  </span>
                )}
              </div>
              {/* Tools used */}
              {Array.isArray(cot.nemotron_tools) && cot.nemotron_tools.length > 0 && (
                <div style={{ marginBottom: 10 }}>
                  <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', color: '#87867f', marginBottom: 4 }}>{t('cotTools')}</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                    {cot.nemotron_tools.map((tool: string, i: number) => (
                      <span key={i} style={{ fontSize: 10, background: '#f5f4ed', border: '0.5px solid #e0ddd4', borderRadius: 3, padding: '2px 6px', fontFamily: "'JetBrains Mono', monospace" }}>{tool}</span>
                    ))}
                  </div>
                </div>
              )}
              {/* Reasoning */}
              {cot.reasoning && (
                <div>
                  <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', color: '#87867f', marginBottom: 4 }}>{t('cotReasoning')}</div>
                  <div style={{ fontSize: 11, color: '#555550', lineHeight: 1.5, background: '#faf9f3', border: '0.5px solid #e0ddd4', borderRadius: 6, padding: '8px 10px', maxHeight: 180, overflowY: 'auto', fontFamily: "'JetBrains Mono', monospace", whiteSpace: 'pre-wrap' }}>
                    {cot.reasoning}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  )
}

// =============================================================================
// Tab 4: 處置統計 (串接真實 /stats/disposition)
// =============================================================================

function DispositionTab() {
  const t = useTranslations('dashboard')
  const [data, setData] = useState<any>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch(`${API_BASE}/api/v1/stats/disposition`)
      .then(r => r.json())
      .then(d => setData(d))
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [])

  if (loading) return <CardSkeleton lines={4} />

  const s = data?.summary
  if (!s || s.total === 0) return (
    <div style={{ padding: 48, textAlign: 'center', color: '#87867f' }}>
      <div style={{ fontSize: 32, marginBottom: 8, opacity: 0.3 }}>--</div>
      <div>{t('noDispositionData')}</div>
    </div>
  )

  const autoRate = Math.round(s.auto_rate * 100)

  return (
    <div style={{ padding: '16px 20px', flex: 1, overflowY: 'auto' }}>
      {/* KPI 3 卡 */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 16 }}>
        <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 10, padding: '14px 16px' }}>
          <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.5, color: '#87867f', fontWeight: 500 }}>{t('totalDispositions')}</div>
          <div style={{ fontSize: 28, fontWeight: 700, color: '#4A90D9', marginTop: 4 }}>{s.total}</div>
        </div>
        <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 10, padding: '14px 16px' }}>
          <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.5, color: '#87867f', fontWeight: 500 }}>{t('autoRate')}</div>
          <div style={{ fontSize: 28, fontWeight: 700, color: '#22C55E', marginTop: 4 }}>{autoRate}%</div>
        </div>
        <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 10, padding: '14px 16px' }}>
          <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.5, color: '#87867f', fontWeight: 500 }}>{t('humanRate')}</div>
          <div style={{ fontSize: 28, fontWeight: 700, color: '#F59E0B', marginTop: 4 }}>{Math.round(s.human_rate * 100)}%</div>
        </div>
      </div>
      {/* 四大計數 */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 16 }}>
        {[
          { label: t('autoRepairLabel'), count: s.auto_repair, color: '#22C55E', bg: 'rgba(34,197,94,0.06)', border: 'rgba(34,197,94,0.25)' },
          { label: t('humanApprovedLabel'), count: s.human_approved, color: '#F59E0B', bg: 'rgba(249,115,22,0.06)', border: 'rgba(249,115,22,0.25)' },
          { label: t('manualResolvedLabel'), count: s.manual_resolved, color: '#A855F7', bg: 'rgba(168,85,247,0.06)', border: 'rgba(168,85,247,0.25)' },
          { label: t('coldStartLabel'), count: s.cold_start_trust, color: '#4A90D9', bg: 'rgba(59,130,246,0.06)', border: 'rgba(59,130,246,0.25)' },
        ].map(item => (
          <div key={item.label} style={{ background: item.bg, border: `0.5px solid ${item.border}`, borderRadius: 10, padding: 14, textAlign: 'center' }}>
            <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, color: item.color, marginBottom: 6 }}>{item.label}</div>
            <div style={{ fontSize: 28, fontWeight: 700, color: item.color }}>{item.count}</div>
          </div>
        ))}
      </div>
      {/* 堆疊分佈條 */}
      <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 10, padding: '14px 16px', marginBottom: 16 }}>
        <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, color: '#87867f', marginBottom: 8 }}>{t('dispositionBreakdown')}</div>
        <div style={{ display: 'flex', height: 12, borderRadius: 6, overflow: 'hidden' }}>
          {s.total > 0 && <>
            <div style={{ width: `${(s.auto_repair/s.total)*100}%`, background: '#22C55E' }} />
            <div style={{ width: `${(s.cold_start_trust/s.total)*100}%`, background: '#4A90D9' }} />
            <div style={{ width: `${(s.human_approved/s.total)*100}%`, background: '#F59E0B' }} />
            <div style={{ width: `${(s.manual_resolved/s.total)*100}%`, background: '#A855F7' }} />
          </>}
        </div>
      </div>

      {/* By Anomaly Top 5 */}
      {Array.isArray(data?.by_anomaly) && data.by_anomaly.length > 0 && (() => {
        const top5 = [...data.by_anomaly]
          .sort((a: any, b: any) => (b.disposition?.total ?? 0) - (a.disposition?.total ?? 0))
          .slice(0, 5)
        const maxCount = top5[0]?.disposition?.total || 1
        return (
          <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 10, padding: '14px 16px', marginBottom: 16 }}>
            <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, color: '#87867f', marginBottom: 10 }}>{t('byAnomalyTitle')}</div>
            {top5.map((item: any, i: number) => {
              const disp = item.disposition ?? {}
              const count = disp.total ?? 0
              const autoRate = Math.round((disp.auto_rate ?? 0) * 100)
              const label = item.alert_name || item.anomaly_key || '--'
              return (
                <div key={i} style={{ marginBottom: 8 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 3 }}>
                    <span style={{ color: '#141413', fontWeight: 500, maxWidth: '70%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
                    <span style={{ color: '#87867f', fontFamily: "'JetBrains Mono', monospace", fontSize: 10 }}>
                      {count} · {t('byAnomalyAutoRate', { pct: autoRate })}
                    </span>
                  </div>
                  <div style={{ height: 6, background: '#f0ede5', borderRadius: 3, overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: `${(count / maxCount) * 100}%`, background: autoRate >= 80 ? '#22C55E' : autoRate >= 50 ? '#F59E0B' : '#cc2200', borderRadius: 3, transition: 'width 0.4s ease' }} />
                  </div>
                </div>
              )
            })}
          </div>
        )
      })()}

      {/* MTTR */}
      {(() => {
        const mttr = data?.mttr
        if (!mttr) return (
          <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 10, padding: '14px 16px' }}>
            <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, color: '#87867f', marginBottom: 6 }}>{t('mttrTitle')}</div>
            <div style={{ fontSize: 11, color: '#87867f' }}>{t('mttrNoData')}</div>
          </div>
        )
        const mttrVal = typeof mttr === 'number' ? mttr : mttr.avg_seconds ?? mttr.value ?? null
        const mttrMin = mttrVal !== null ? (mttrVal / 60).toFixed(1) : '--'
        return (
          <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 10, padding: '14px 16px' }}>
            <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, color: '#87867f', marginBottom: 6 }}>{t('mttrTitle')}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
              <span style={{ fontSize: 32, fontWeight: 700, color: '#4A90D9' }}>{mttrMin}</span>
              <span style={{ fontSize: 11, color: '#87867f' }}>{t('mttrUnit')}</span>
            </div>
          </div>
        )
      })()}
    </div>
  )
}

// =============================================================================
// Monitoring Tools Component — figma-v2 style
// Left 3px accent bar + clickable links + meta row
// =============================================================================

interface MonitoringTool {
  name: string
  status: string
  version: string | null
  stats: string | null
  description: string
  firing_count?: number
  checked_at: string
  url?: string
}

// figma-v2 左側彩色條顏色
const TOOL_ACCENT_COLOR: Record<string, string> = {
  Grafana:    '#F59E0B',
  Prometheus: '#E85530',
  Sentry:     '#7B52BF',
  Langfuse:   '#0077CC',
  SigNoz:     '#4A90D9',
  Gitea:      '#22C55E',
}

function MonitoringTools() {
  const tDash = useTranslations('dashboard')
  const tCommon = useTranslations('common')
  const [tools, setTools] = useState<MonitoringTool[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const load = () => {
      fetch(`${API_BASE}/api/v1/monitoring/status`)
        .then(r => r.json())
        .then(d => { setTools(d.tools ?? []); setLoading(false) })
        .catch(() => setLoading(false))
    }
    load()
    const t = setInterval(load, 60000)
    return () => clearInterval(t)
  }, [])

  if (loading) return (
    <div style={{ padding: '12px 14px', fontSize: 12, color: '#87867f' }}>{tCommon('loading')}</div>
  )
  if (tools.length === 0) return (
    <div style={{ padding: '12px 14px', fontSize: 12, color: '#cc2200' }}>{tDash('connectionError')}</div>
  )

  // S10: 監控工具元資訊 (設計稿 3×2 精簡版)
  const TOOL_META: Record<string, string> = {
    SigNoz: 'Traces · Logs', Grafana: '3 Dashboards', Prometheus: '-- targets',
    Langfuse: 'LLMOps', Sentry: '2 Projects', Gitea: 'CI/CD',
  }

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6, padding: '10px 14px' }}>
      {tools.map((tool) => {
        const accentColor = TOOL_ACCENT_COLOR[tool.name] ?? '#b0ad9f'
        const link = tool.url ?? '#'
        const meta = TOOL_META[tool.name] ?? tool.description ?? ''

        return (
          <a key={tool.name} href={link} target="_blank" rel="noopener noreferrer"
            style={{
              display: 'flex', overflow: 'hidden',
              border: '0.5px solid #e0ddd4', borderRadius: 6,
              background: '#faf9f3', cursor: 'pointer',
              textDecoration: 'none', color: 'inherit',
              transition: 'border-color 0.1s',
            }}
          >
            <div style={{ width: 3, flexShrink: 0, background: accentColor }} />
            <div style={{ padding: '5px 7px', flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', color: '#141413' }}>{tool.name}</div>
              <div style={{ fontSize: 10, color: '#87867f', marginTop: 2 }}>{meta}</div>
            </div>
          </a>
        )
      })}
    </div>
  )
}

// =============================================================================
// Main Page
// =============================================================================

function isHealthyService(status: string | null | undefined) {
  return status === 'up' || status === 'healthy'
}

function metricColor(value: number | null | undefined) {
  if (value == null) return '#e0ddd4'
  if (value >= 90) return '#cc2200'
  if (value >= 70) return '#F59E0B'
  return '#22C55E'
}

function metricText(value: number | null | undefined) {
  return value == null ? '--' : `${Math.round(value)}%`
}

function roleLabelKey(role: string | null | undefined) {
  if (role === 'security') return 'groupSecurity'
  if (role === 'k3s') return 'groupK3s'
  if (role === 'ai_web') return 'groupAiData'
  return 'groupInfra'
}

function roleAccent(role: string | null | undefined) {
  if (role === 'security') return { border: 'rgba(204,34,0,0.25)', bg: 'rgba(204,34,0,0.02)', accent: '#cc2200' }
  if (role === 'k3s') return { border: 'rgba(168,85,247,0.25)', bg: 'rgba(168,85,247,0.02)', accent: '#A855F7' }
  if (role === 'ai_web') return { border: 'rgba(249,115,22,0.25)', bg: 'rgba(249,115,22,0.02)', accent: '#F97316' }
  return { border: 'rgba(59,130,246,0.2)', bg: 'rgba(59,130,246,0.01)', accent: '#3B82F6' }
}

function incidentMatchesHost(incident: { affected_services?: string[] }, host: Host) {
  const terms = [
    host.ip,
    host.ip.split('.').pop() ?? '',
    host.name,
    ...host.services.map(service => service.name),
  ]
    .filter(Boolean)
    .map(term => term.toLowerCase())

  return incident.affected_services?.some(serviceName => {
    const normalized = serviceName.toLowerCase()
    return terms.some(term => normalized.includes(term) || term.includes(normalized))
  }) ?? false
}

export default function Home({ params }: { params: { locale: string } }) {
  const tDashboard = useTranslations('dashboard')
  const tTopo = useTranslations('topology')
  const locale = params.locale
  const hosts = useHosts()

  // dashboard store — pending approvals + overall pod health
  const pendingApprovals = useDashboardStore(s => s.pendingApprovals)
  const dashboardHosts = useDashboardStore(s => s.hosts)

  // Real incidents
  const {
    incidents,
    isLoading: isIncidentsLoading,
    error: incidentsError,
    lastUpdated: incidentsLastUpdated,
  } = useIncidents({
    pollInterval: 15000,
    enablePolling: true,
  })
  const {
    statusChains,
    requestedIncidentIds,
    isLoading: isStatusChainsLoading,
  } = useIncidentStatusChains({
    incidentIds: incidents?.map(incident => incident.incident_id) ?? [],
    limit: HOMEPAGE_STATUS_CHAIN_PREFETCH_LIMIT,
    concurrency: HOMEPAGE_STATUS_CHAIN_CONCURRENCY,
    timeoutMs: HOMEPAGE_STATUS_CHAIN_TIMEOUT_MS,
    refreshKey: incidentsLastUpdated?.toISOString() ?? null,
  })

  // ── Metrics 計算 ────────────────────────────────────────────────────────────

  // 服務健康: dashboard hosts healthy services count
  const { healthyServices, totalServices } = (() => {
    let healthy = 0, total = 0
    for (const h of dashboardHosts) {
      for (const s of h.services) {
        total++
        if (s.status === 'up' || s.status === 'healthy') healthy++
      }
    }
    return { healthyServices: healthy, totalServices: total }
  })()

  // 2026-04-07 Claude Code: Sprint 4 E2 — 從 disposition API 取得真實自動化率
  const [dispositionRate, setDispositionRate] = useState<{ auto_rate: number; total: number } | null>(null)
  const [automationQuality, setAutomationQuality] = useState<HomepageAutomationQualitySummary | null>(null)
  const [automationQualityLoaded, setAutomationQualityLoaded] = useState(false)
  const [automationBrief, setAutomationBrief] = useState<HomepageAutomationBriefSnapshot>({})
  const [automationBriefLoaded, setAutomationBriefLoaded] = useState(false)
  useEffect(() => {
    fetch(`${API_BASE}/api/v1/stats/disposition`)
      .then(r => r.json())
      .then(d => {
        if (d?.summary) setDispositionRate({ auto_rate: d.summary.auto_rate, total: d.summary.total })
      })
      .catch(() => {})
  }, [])
  useEffect(() => {
    const controller = new AbortController()
    let isCancelled = false
    const timeoutId = window.setTimeout(() => controller.abort(), HOMEPAGE_QUALITY_SUMMARY_TIMEOUT_MS)
    fetch(`${API_BASE}/api/v1/platform/truth-chain/quality/summary?project_id=awoooi&hours=24&limit=${HOMEPAGE_QUALITY_SUMMARY_LIMIT}`, {
      signal: controller.signal,
    })
      .then(r => r.ok ? r.json() : null)
      .then(d => {
        if (!d || isCancelled) return
        setAutomationQuality({
          average_score: typeof d.average_score === 'number' ? d.average_score : undefined,
          evaluated_total: typeof d.evaluated_total === 'number' ? d.evaluated_total : undefined,
          verified_auto_repair_total: typeof d.verified_auto_repair_total === 'number' ? d.verified_auto_repair_total : undefined,
          gate_failures: Array.isArray(d.gate_failures) ? d.gate_failures : [],
          execution_backend_summary: d.execution_backend_summary ?? null,
          ansible_runtime: d.ansible_runtime ?? null,
          production_claim: d.production_claim,
        })
      })
      .catch(() => {})
      .finally(() => {
        window.clearTimeout(timeoutId)
        if (!isCancelled) {
          setAutomationQualityLoaded(true)
        }
      })
    return () => {
      isCancelled = true
      window.clearTimeout(timeoutId)
      controller.abort()
    }
  }, [])
  useEffect(() => {
    const controller = new AbortController()
    const encodedProjectId = encodeURIComponent('awoooi')
    let isCancelled = false
    let pendingRequests = 10
    const finishRequest = () => {
      pendingRequests -= 1
      if (pendingRequests <= 0 && !isCancelled) {
        setAutomationBriefLoaded(true)
      }
    }
    const loadBriefPart = <K extends keyof HomepageAutomationBriefSnapshot>(
      key: K,
      request: Promise<HomepageAutomationBriefSnapshot[K]>
    ) => {
      request
        .then(value => {
          if (!isCancelled) {
            setAutomationBrief(previous => ({ ...previous, [key]: value }))
          }
        })
        .catch(() => {
          if (!isCancelled) {
            setAutomationBrief(previous => ({ ...previous, [key]: null }))
          }
        })
        .finally(finishRequest)
    }

    setAutomationBrief({})
    setAutomationBriefLoaded(false)
    loadBriefPart(
      'callbackReplies',
      fetchHomepageJson<HomepageCallbackRepliesResponse>(
        `${API_BASE}/api/v1/platform/runs/callback-replies?project_id=${encodedProjectId}&per_page=20`,
        controller.signal
      )
    )
    loadBriefPart(
      'aiRouteStatus',
      fetchHomepageJson<HomepageAiRouteStatusResponse>(
        `${API_BASE}/api/v1/platform/ai-route-status?workload_type=deep_rca`,
        controller.signal
      )
    )
    loadBriefPart(
      'kmStaleCandidates',
      fetchHomepageJson<HomepageKmStaleCandidatesResponse>(
        `${API_BASE}/api/v1/ai/governance/km-stale-candidates?project_id=${encodedProjectId}&limit=5`,
        controller.signal
      )
    )
    loadBriefPart(
      'dossierCoverage',
      fetchHomepageJson<HomepageDossierCoverageResponse>(
        `${API_BASE}/api/v1/platform/events/dossier/coverage?project_id=${encodedProjectId}&limit=100`,
        controller.signal
      )
    )
    loadBriefPart(
      'dossierCoverageSentry',
      fetchHomepageJson<HomepageDossierCoverageResponse>(
        `${API_BASE}/api/v1/platform/events/dossier/coverage?project_id=${encodedProjectId}&provider=sentry&limit=100`,
        controller.signal
      )
    )
    loadBriefPart(
      'dossierCoverageSignoz',
      fetchHomepageJson<HomepageDossierCoverageResponse>(
        `${API_BASE}/api/v1/platform/events/dossier/coverage?project_id=${encodedProjectId}&provider=signoz&limit=100`,
        controller.signal
      )
    )
    loadBriefPart(
      'eventRecurrence',
      fetchHomepageJson<HomepageEventRecurrenceResponse>(
        `${API_BASE}/api/v1/platform/events/dossier/recurrence?project_id=${encodedProjectId}&limit=100`,
        controller.signal
      )
    )
    loadBriefPart(
      'runsList',
      fetchHomepageJson<HomepageRunsListResponse>(
        `${API_BASE}/api/v1/platform/runs/list?project_id=${encodedProjectId}&per_page=25`,
        controller.signal
      )
    )
    loadBriefPart(
      'cicdEvents',
      fetchHomepageJson<HomepageCicdEventsResponse>(
        `${API_BASE}/api/v1/platform/cicd/events?project_id=${encodedProjectId}&limit=12`,
        controller.signal
      )
    )
    loadBriefPart(
      'kmOwnerReviewBurndown',
      fetchHomepageJson<HomepageKmOwnerReviewBurndownResponse>(
        `${API_BASE}/api/v1/ai/governance/km-stale-owner-review-burndown?project_id=${encodedProjectId}&limit=5`,
        controller.signal
      )
    )
    return () => {
      isCancelled = true
      controller.abort()
    }
  }, [])

  // 自動處置率 — 首頁 KPI 使用 24h truth-chain 驗證率，避免把歷史 disposition 總表誤讀成今日閉環。
  const automationQualityAvailable = automationQuality !== null
  const unavailableValue = tDashboard('automationDelivery.unavailableValue')
  const loadingStatus = tDashboard('automationDelivery.status.loading')
  const unavailableStatus = tDashboard('automationDelivery.status.unavailable')
  const hasAutomationBriefPart = (key: keyof HomepageAutomationBriefSnapshot) => (
    Object.prototype.hasOwnProperty.call(automationBrief, key)
  )
  const callbackRepliesLoaded = hasAutomationBriefPart('callbackReplies')
  const aiRouteStatusLoaded = hasAutomationBriefPart('aiRouteStatus')
  const kmStaleCandidatesLoaded = hasAutomationBriefPart('kmStaleCandidates')
  const dossierCoverageLoaded = hasAutomationBriefPart('dossierCoverage')
  const dossierCoverageSentryLoaded = hasAutomationBriefPart('dossierCoverageSentry')
  const dossierCoverageSignozLoaded = hasAutomationBriefPart('dossierCoverageSignoz')
  const eventRecurrenceLoaded = hasAutomationBriefPart('eventRecurrence')
  const runsListLoaded = hasAutomationBriefPart('runsList')
  const cicdEventsLoaded = hasAutomationBriefPart('cicdEvents')
  const kmOwnerReviewBurndownLoaded = hasAutomationBriefPart('kmOwnerReviewBurndown')
  const formatLiveEvidenceTime = (value: string | null | undefined, loaded = automationBriefLoaded) => {
    if (!value) return loaded ? unavailableValue : loadingStatus
    const date = new Date(value)
    if (Number.isNaN(date.getTime())) return unavailableValue
    return date.toLocaleString(locale === 'en' ? 'en-US' : 'zh-TW', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    })
  }
  const evaluatedAutomationTotal = automationQuality?.evaluated_total
  const verifiedAutomationTotal = automationQuality?.verified_auto_repair_total
  const formatAutomationNumber = (value: number | null | undefined, loaded: boolean) => {
    if (typeof value === 'number') return value.toLocaleString()
    return loaded ? unavailableValue : '--'
  }
  const autoRemediationRate = (() => {
    if (typeof evaluatedAutomationTotal === 'number' && evaluatedAutomationTotal > 0 && typeof verifiedAutomationTotal === 'number') {
      return `${Math.round((verifiedAutomationTotal / evaluatedAutomationTotal) * 100)}%`
    }
    return '--'
  })()

  // 自動處置率數值 (for progress bar)
  const autoRemediationPct = (() => {
    if (typeof evaluatedAutomationTotal === 'number' && evaluatedAutomationTotal > 0 && typeof verifiedAutomationTotal === 'number') {
      return Math.round((verifiedAutomationTotal / evaluatedAutomationTotal) * 100)
    }
    return 0
  })()
  const autoRemediationTone = automationQuality?.production_claim?.can_claim_full_auto_repair
    ? '#22C55E'
    : typeof evaluatedAutomationTotal === 'number' && evaluatedAutomationTotal > 0
      ? '#F59E0B'
      : '#141413'
  const autoRemediationDetail = typeof evaluatedAutomationTotal === 'number' && evaluatedAutomationTotal > 0 && typeof verifiedAutomationTotal === 'number'
    ? tDashboard('autoRepairVerifiedCount', {
      verified: verifiedAutomationTotal,
      evaluated: evaluatedAutomationTotal,
    })
    : dispositionRate && dispositionRate.total > 0
      ? tDashboard('autoRepairAllTime', {
        pct: Math.round(dispositionRate.auto_rate * 100),
        total: dispositionRate.total.toLocaleString(),
      })
      : null
  const topAutomationGate = automationQuality?.gate_failures?.[0] ?? null
  const executionBackend = automationQuality?.execution_backend_summary ?? null
  const ansibleRuntime = automationQuality?.ansible_runtime ?? null
  const ansibleRuntimeBlockerLabel = !automationQualityLoaded
    ? loadingStatus
    : ansibleRuntime?.can_run_check_mode
      ? tDashboard('automationEvidence.ansibleRuntimeReady')
      : ansibleRuntime?.blockers?.join(' / ') || unavailableValue
  const callbackTraceSummary = automationBrief.callbackReplies?.summary ?? null
  const missingTraceRecent24h = callbackTraceSummary?.outbound_reply_markup_missing_trace_ref_recent_24h_total ?? 0
  const traceRecoveryStatus = callbackTraceSummary?.outbound_reply_markup_trace_ref_gap_recovery_status
    ?? (callbackRepliesLoaded ? unavailableValue : loadingStatus)
  const traceRecoveryCount = callbackTraceSummary?.outbound_reply_markup_trace_ref_after_gap_total
  const aiRouteSelectedProvider = automationBrief.aiRouteStatus?.selected_provider ?? '--'
  const aiRouteLaneMode = automationBrief.aiRouteStatus?.lane_mode ?? '--'
  const kmStaleTotal = automationBrief.kmStaleCandidates?.total_stale
  const kmStaleThreshold = automationBrief.kmStaleCandidates?.threshold_days
  const hasCallbackEvidence = automationBrief.callbackReplies !== undefined && automationBrief.callbackReplies !== null
  const hasAiRouteStatus = automationBrief.aiRouteStatus !== undefined && automationBrief.aiRouteStatus !== null
  const hasKmStaleCandidates = automationBrief.kmStaleCandidates !== undefined && automationBrief.kmStaleCandidates !== null
  const canClaimFullAutoRepair = automationQualityAvailable && Boolean(automationQuality?.production_claim?.can_claim_full_auto_repair)
  const dossierCoverageSummary = automationBrief.dossierCoverage?.summary ?? null
  const dossierCoverageSentrySummary = automationBrief.dossierCoverageSentry?.summary ?? null
  const dossierCoverageSignozSummary = automationBrief.dossierCoverageSignoz?.summary ?? null
  const dossierSentryRefs = dossierCoverageSentrySummary?.sentry_ref_total ?? dossierCoverageSummary?.sentry_ref_total
  const dossierSignozRefs = dossierCoverageSignozSummary?.signoz_ref_total ?? dossierCoverageSummary?.signoz_ref_total
  const dossierProviderRefsLoaded = dossierCoverageSentryLoaded && dossierCoverageSignozLoaded
  const dossierProviderRefsLive = (dossierSentryRefs ?? 0) > 0 || (dossierSignozRefs ?? 0) > 0
  const recurrenceSummary = automationBrief.eventRecurrence?.summary ?? null
  const recentRuns = automationBrief.runsList?.runs ?? []
  const latestRun = recentRuns[0]
  const runEvidenceSummary = recentRuns.reduce(
    (acc, run) => {
      const summary = run.remediation_summary
      acc.mcpTotal += summary?.mcp_observation_total ?? 0
      acc.mcpSuccess += summary?.mcp_observation_success ?? 0
      acc.mcpFailed += summary?.mcp_observation_failed ?? 0
      acc.evidenceTotal += summary?.evidence_total ?? 0
      if (summary?.has_mcp_investigation) acc.mcpInvestigatedRuns += 1
      if (summary?.human_gate_open) acc.humanGateRuns += 1
      if (!acc.latestMcpServer && summary?.latest_mcp_server) acc.latestMcpServer = summary.latest_mcp_server
      if (!acc.latestRoute && summary?.latest_route) acc.latestRoute = summary.latest_route
      return acc
    },
    {
      mcpTotal: 0,
      mcpSuccess: 0,
      mcpFailed: 0,
      evidenceTotal: 0,
      mcpInvestigatedRuns: 0,
      humanGateRuns: 0,
      latestMcpServer: null as string | null,
      latestRoute: null as string | null,
    }
  )
  const statusChainValues = Object.values(statusChains).filter((chain): chain is NonNullable<typeof chain> => Boolean(chain && !chain.fetch_error))
  const statusChainEvidenceSummary = statusChainValues.reduce(
    (acc, chain) => {
      acc.mcpGateway += chain.mcp?.gateway?.total ?? chain.evidence?.mcp_gateway_total ?? 0
      acc.mcpGatewaySuccess += chain.mcp?.gateway?.success ?? 0
      acc.mcpGatewayFailed += chain.mcp?.gateway?.failed ?? 0
      acc.operationRecords += chain.evidence?.operation_records ?? chain.execution?.operation_total ?? 0
      acc.autoRepairRecords += chain.evidence?.auto_repair_records ?? 0
      acc.knowledgeEntries += chain.evidence?.knowledge_entries ?? 0
      acc.inboundRefs += chain.source_refs?.inbound_total ?? 0
      acc.outboundRefs += chain.source_refs?.outbound_total ?? 0
      return acc
    },
    {
      mcpGateway: 0,
      mcpGatewaySuccess: 0,
      mcpGatewayFailed: 0,
      operationRecords: 0,
      autoRepairRecords: 0,
      knowledgeEntries: 0,
      inboundRefs: 0,
      outboundRefs: 0,
    }
  )
  const cicdItems = automationBrief.cicdEvents?.items ?? []
  const latestCicdEvent = cicdItems[0]
  const cicdNeedsAttention = cicdItems.filter(item => item.needs_attention).length
  const kmOwnerReviewBurndown = automationBrief.kmOwnerReviewBurndown ?? null
  const kmBurndownSnapshot = kmOwnerReviewBurndown?.current_snapshot ?? null
  const kmStaleDisplayCount = kmBurndownSnapshot?.stale_count ?? kmStaleTotal
  const kmTotalDisplayCount = kmBurndownSnapshot?.total_count
  const kmEntriesToThreshold = kmOwnerReviewBurndown?.entries_to_threshold
  const kmGovernanceLoaded = kmOwnerReviewBurndownLoaded || kmStaleCandidatesLoaded
  const staleRatioLabel = typeof kmBurndownSnapshot?.stale_ratio === 'number'
    ? `${(kmBurndownSnapshot.stale_ratio * 100).toFixed(1)}%`
    : kmOwnerReviewBurndownLoaded ? unavailableValue : loadingStatus
  const automationWorkToneStyle: Record<HomepageWorkTone, { bg: string; border: string; color: string }> = {
    live: { bg: '#f0faf2', border: '#9bc7a4', color: '#17602a' },
    progress: { bg: '#fff7e8', border: '#d9b36f', color: '#8a5a08' },
    blocked: { bg: '#fff0ef', border: '#e2a29b', color: '#9f2f25' },
    watching: { bg: '#eef5ff', border: '#9bb6d9', color: '#1f5b9b' },
  }
  const automationDeliveryHeadline = !automationQualityLoaded
    ? tDashboard('automationDelivery.claimLoading')
    : canClaimFullAutoRepair
      ? tDashboard('automationDelivery.claimReady')
      : automationQualityAvailable
        ? tDashboard('automationDelivery.claimBlocked')
        : tDashboard('automationDelivery.claimUnavailable')
  const automationDeliveryClaimTone = canClaimFullAutoRepair
    ? automationWorkToneStyle.live
    : automationQualityLoaded && automationQualityAvailable
      ? automationWorkToneStyle.progress
      : automationWorkToneStyle.watching
  const automationDeliveryClaimDetail = !automationQualityLoaded
    ? tDashboard('automationDelivery.claimSyncingDetail')
    : automationQualityAvailable
      ? tDashboard('automationDelivery.claimDetail', {
        verified: formatAutomationNumber(verifiedAutomationTotal, automationQualityLoaded),
        evaluated: formatAutomationNumber(evaluatedAutomationTotal, automationQualityLoaded),
        score: automationQuality?.average_score != null
          ? automationQuality.average_score.toFixed(1)
          : unavailableValue,
      })
      : tDashboard('automationDelivery.claimUnavailableDetail')
  const automationDeliveryItems: HomepageWorkItemSummary[] = [
    {
      key: 'cicdTimeline',
      title: tDashboard('automationDelivery.delivered.cicdTimeline.title'),
      status: tDashboard('automationDelivery.status.live'),
      detail: tDashboard('automationDelivery.delivered.cicdTimeline.detail'),
      href: `/${locale}/awooop/runs`,
      tone: 'live',
    },
    {
      key: 'sourceDossier',
      title: tDashboard('automationDelivery.delivered.sourceDossier.title'),
      status: !dossierProviderRefsLoaded
        ? loadingStatus
        : dossierProviderRefsLive
          ? tDashboard('automationDelivery.status.live')
          : tDashboard('automationDelivery.status.watching'),
      detail: tDashboard('automationDelivery.delivered.sourceDossier.detail', {
        sources: formatAutomationNumber(dossierCoverageSummary?.source_count, dossierCoverageLoaded),
        sentry: formatAutomationNumber(dossierSentryRefs, dossierCoverageSentryLoaded || dossierCoverageLoaded),
        signoz: formatAutomationNumber(dossierSignozRefs, dossierCoverageSignozLoaded || dossierCoverageLoaded),
      }),
      href: `/${locale}/alerts`,
      tone: dossierProviderRefsLive ? 'live' : dossierProviderRefsLoaded ? 'watching' : 'progress',
    },
    {
      key: 'callbackEvidence',
      title: tDashboard('automationDelivery.delivered.callbackEvidence.title'),
      status: hasCallbackEvidence
        ? tDashboard('automationDelivery.status.live')
        : callbackRepliesLoaded
          ? unavailableStatus
          : loadingStatus,
      detail: tDashboard('automationDelivery.delivered.callbackEvidence.detail', {
        total: formatAutomationNumber(automationBrief.callbackReplies?.total, callbackRepliesLoaded),
      }),
      href: `/${locale}/awooop/runs?project_id=awoooi#tg-callback-evidence`,
      tone: hasCallbackEvidence ? 'live' : 'watching',
    },
    {
      key: 'callbackTrace',
      title: tDashboard('automationDelivery.delivered.callbackTrace.title'),
      status: callbackTraceSummary && traceRecoveryStatus === 'recovered_after_gap'
        ? tDashboard('automationDelivery.status.progress')
        : !callbackRepliesLoaded
          ? loadingStatus
          : callbackTraceSummary
            ? tDashboard('automationDelivery.status.watching')
            : unavailableStatus,
      detail: tDashboard('automationDelivery.delivered.callbackTrace.detail', {
        status: traceRecoveryStatus,
        recovered: formatAutomationNumber(traceRecoveryCount, callbackRepliesLoaded),
        recent24h: formatAutomationNumber(callbackTraceSummary?.outbound_reply_markup_missing_trace_ref_recent_24h_total, callbackRepliesLoaded),
      }),
      href: `/${locale}/awooop/work-items?project_id=awoooi`,
      tone: traceRecoveryStatus === 'recovered_after_gap' ? 'progress' : 'watching',
    },
    {
      key: 'aiRoute',
      title: tDashboard('automationDelivery.delivered.aiRoute.title'),
      status: hasAiRouteStatus
        ? tDashboard('automationDelivery.status.live')
        : automationBriefLoaded
          ? unavailableStatus
          : loadingStatus,
      detail: tDashboard('automationDelivery.delivered.aiRoute.detail', {
        provider: aiRouteSelectedProvider,
        lane: aiRouteLaneMode,
      }),
      href: `/${locale}/awooop/work-items?project_id=awoooi`,
      tone: hasAiRouteStatus ? 'live' : 'watching',
    },
  ]
  const automationRemainingItems: HomepageWorkItemSummary[] = [
    {
      key: 'fullAutoRepairClaim',
      title: tDashboard('automationDelivery.remaining.fullAutoRepairClaim.title'),
      status: !automationQualityLoaded
        ? loadingStatus
        : canClaimFullAutoRepair
          ? tDashboard('automationDelivery.status.live')
          : automationQualityAvailable
            ? tDashboard('automationDelivery.status.blocked')
            : unavailableStatus,
      detail: tDashboard('automationDelivery.remaining.fullAutoRepairClaim.detail', {
        verified: formatAutomationNumber(verifiedAutomationTotal, automationQualityLoaded),
        evaluated: formatAutomationNumber(evaluatedAutomationTotal, automationQualityLoaded),
      }),
      href: `/${locale}/awooop/work-items?project_id=awoooi`,
      tone: canClaimFullAutoRepair ? 'live' : automationQualityAvailable ? 'blocked' : 'watching',
    },
    {
      key: 'qualityGateBacklog',
      title: tDashboard('automationDelivery.remaining.qualityGateBacklog.title'),
      status: !automationQualityLoaded
        ? loadingStatus
        : topAutomationGate
          ? tDashboard('automationDelivery.status.blocked')
          : automationQualityAvailable
            ? tDashboard('automationDelivery.status.live')
            : unavailableStatus,
      detail: tDashboard('automationDelivery.remaining.qualityGateBacklog.detail', {
        gate: topAutomationGate?.gate ?? (automationQualityLoaded ? unavailableValue : loadingStatus),
        count: formatAutomationNumber(topAutomationGate?.total, automationQualityLoaded),
      }),
      href: `/${locale}/awooop/runs?project_id=awoooi`,
      tone: topAutomationGate ? 'blocked' : automationQualityAvailable ? 'live' : 'watching',
    },
    {
      key: 'ansibleRuntime',
      title: tDashboard('automationDelivery.remaining.ansibleRuntime.title'),
      status: !automationQualityLoaded
        ? loadingStatus
        : ansibleRuntime?.can_run_check_mode
          ? tDashboard('automationDelivery.status.live')
          : automationQualityAvailable
            ? tDashboard('automationDelivery.status.blocked')
            : unavailableStatus,
      detail: tDashboard('automationDelivery.remaining.ansibleRuntime.detail', {
        checkMode: formatAutomationNumber(executionBackend?.ansible_check_mode_total, automationQualityLoaded),
        pending: formatAutomationNumber(executionBackend?.ansible_pending_check_mode_total, automationQualityLoaded),
        blocker: ansibleRuntimeBlockerLabel,
      }),
      href: `/${locale}/awooop/work-items?project_id=awoooi`,
      tone: ansibleRuntime?.can_run_check_mode ? 'live' : automationQualityAvailable ? 'blocked' : 'watching',
    },
    {
      key: 'kmGovernance',
      title: tDashboard('automationDelivery.remaining.kmGovernance.title'),
      status: !kmGovernanceLoaded
        ? loadingStatus
        : typeof kmStaleDisplayCount === 'number' && kmStaleDisplayCount > 0
          ? tDashboard('automationDelivery.status.progress')
          : hasKmStaleCandidates
            ? tDashboard('automationDelivery.status.live')
            : unavailableStatus,
      detail: tDashboard('automationDelivery.remaining.kmGovernance.detail', {
        stale: formatAutomationNumber(kmStaleDisplayCount, kmGovernanceLoaded),
        total: formatAutomationNumber(kmTotalDisplayCount, kmOwnerReviewBurndownLoaded),
        ratio: staleRatioLabel,
        pending: formatAutomationNumber(kmOwnerReviewBurndown?.pending_owner_reviews, kmOwnerReviewBurndownLoaded),
        remaining: formatAutomationNumber(kmEntriesToThreshold, kmOwnerReviewBurndownLoaded),
        days: formatAutomationNumber(kmStaleThreshold ?? kmBurndownSnapshot?.stale_days, kmGovernanceLoaded),
      }),
      href: `/${locale}/awooop/work-items?project_id=awoooi`,
      tone: typeof kmStaleDisplayCount === 'number' && kmStaleDisplayCount > 0 ? 'progress' : hasKmStaleCandidates ? 'live' : 'watching',
    },
    {
      key: 'callbackBacklogDecay',
      title: tDashboard('automationDelivery.remaining.callbackBacklogDecay.title'),
      status: !callbackRepliesLoaded
        ? loadingStatus
        : callbackTraceSummary && missingTraceRecent24h > 0
          ? tDashboard('automationDelivery.status.progress')
          : callbackTraceSummary
            ? tDashboard('automationDelivery.status.live')
            : unavailableStatus,
      detail: tDashboard('automationDelivery.remaining.callbackBacklogDecay.detail', {
        recent1h: formatAutomationNumber(callbackTraceSummary?.outbound_reply_markup_missing_trace_ref_recent_1h_total, callbackRepliesLoaded),
        recent24h: formatAutomationNumber(callbackTraceSummary?.outbound_reply_markup_missing_trace_ref_recent_24h_total, callbackRepliesLoaded),
        missing: formatAutomationNumber(callbackTraceSummary?.outbound_reply_markup_missing_trace_ref_total, callbackRepliesLoaded),
      }),
      href: `/${locale}/awooop/runs?project_id=awoooi#tg-callback-evidence`,
      tone: callbackTraceSummary && missingTraceRecent24h > 0 ? 'progress' : callbackTraceSummary ? 'live' : 'watching',
    },
  ]
  const automationDeliveryMatrixRows = [
    ...automationDeliveryItems.map(item => ({
      ...item,
      group: tDashboard('automationDelivery.deliveredTitle'),
    })),
    ...automationRemainingItems.map(item => ({
      ...item,
      group: tDashboard('automationDelivery.remainingTitle'),
    })),
  ]
  const productDiagramCards = [
    {
      key: 'c4Runtime',
      title: tDashboard('automationDiagrams.cards.c4Runtime.title'),
      standard: tDashboard('automationDiagrams.cards.c4Runtime.standard'),
      detail: tDashboard('automationDiagrams.cards.c4Runtime.detail'),
      href: `/${locale}/topology`,
      nodes: [
        tDashboard('automationDiagrams.cards.c4Runtime.nodes.user'),
        tDashboard('automationDiagrams.cards.c4Runtime.nodes.web'),
        tDashboard('automationDiagrams.cards.c4Runtime.nodes.api'),
        tDashboard('automationDiagrams.cards.c4Runtime.nodes.k8s'),
      ],
    },
    {
      key: 'incidentFlow',
      title: tDashboard('automationDiagrams.cards.incidentFlow.title'),
      standard: tDashboard('automationDiagrams.cards.incidentFlow.standard'),
      detail: tDashboard('automationDiagrams.cards.incidentFlow.detail'),
      href: `/${locale}/awooop/runs?project_id=awoooi`,
      nodes: [
        tDashboard('automationDiagrams.cards.incidentFlow.nodes.alert'),
        tDashboard('automationDiagrams.cards.incidentFlow.nodes.ai'),
        tDashboard('automationDiagrams.cards.incidentFlow.nodes.playbook'),
        tDashboard('automationDiagrams.cards.incidentFlow.nodes.verify'),
      ],
    },
    {
      key: 'decisionRules',
      title: tDashboard('automationDiagrams.cards.decisionRules.title'),
      standard: tDashboard('automationDiagrams.cards.decisionRules.standard'),
      detail: tDashboard('automationDiagrams.cards.decisionRules.detail'),
      href: `/${locale}/awooop/approvals`,
      nodes: [
        tDashboard('automationDiagrams.cards.decisionRules.nodes.risk'),
        tDashboard('automationDiagrams.cards.decisionRules.nodes.confidence'),
        tDashboard('automationDiagrams.cards.decisionRules.nodes.policy'),
        tDashboard('automationDiagrams.cards.decisionRules.nodes.approval'),
      ],
    },
    {
      key: 'evidenceLineage',
      title: tDashboard('automationDiagrams.cards.evidenceLineage.title'),
      standard: tDashboard('automationDiagrams.cards.evidenceLineage.standard'),
      detail: tDashboard('automationDiagrams.cards.evidenceLineage.detail'),
      href: `/${locale}/awooop/runs?project_id=awoooi#tg-callback-evidence`,
      nodes: [
        tDashboard('automationDiagrams.cards.evidenceLineage.nodes.telegram'),
        tDashboard('automationDiagrams.cards.evidenceLineage.nodes.db'),
        tDashboard('automationDiagrams.cards.evidenceLineage.nodes.trace'),
        tDashboard('automationDiagrams.cards.evidenceLineage.nodes.km'),
      ],
    },
  ]
  const automationFlowStages: HomepageBlueprintStage[] = [
    {
      key: 'signal',
      title: tDashboard('automationDiagrams.workspace.flow.stages.signal'),
      status: tDashboard('automationDelivery.status.live'),
      detail: tDashboard('automationDiagrams.workspace.liveEvidence.signal.metric', {
        sources: formatAutomationNumber(dossierCoverageSummary?.source_count, dossierCoverageLoaded),
        refs: formatAutomationNumber(dossierCoverageSummary?.source_ref_total, dossierCoverageLoaded),
      }),
      href: `/${locale}/awooop/runs?project_id=awoooi#tg-callback-evidence`,
      tone: 'live',
      owner: tDashboard('automationDiagrams.workspace.inspector.stages.signal.owner'),
      evidence: tDashboard('automationDiagrams.workspace.inspector.stages.signal.evidence'),
      nextAction: tDashboard('automationDiagrams.workspace.inspector.stages.signal.nextAction'),
      liveEvidence: {
        metric: tDashboard('automationDiagrams.workspace.liveEvidence.signal.metric', {
          sources: formatAutomationNumber(dossierCoverageSummary?.source_count, dossierCoverageLoaded),
          refs: formatAutomationNumber(dossierCoverageSummary?.source_ref_total, dossierCoverageLoaded),
        }),
        detail: tDashboard('automationDiagrams.workspace.liveEvidence.signal.detail', {
          missing: formatAutomationNumber(dossierCoverageSummary?.missing_source_refs_total, dossierCoverageLoaded),
          duplicates: formatAutomationNumber(dossierCoverageSummary?.duplicate_total, dossierCoverageLoaded),
          alert: formatAutomationNumber(dossierCoverageSummary?.alert_ref_total, dossierCoverageLoaded),
          sentry: formatAutomationNumber(dossierSentryRefs, dossierCoverageSentryLoaded || dossierCoverageLoaded),
          signoz: formatAutomationNumber(dossierSignozRefs, dossierCoverageSignozLoaded || dossierCoverageLoaded),
        }),
        source: tDashboard('automationDiagrams.workspace.liveEvidence.sources.dossierCoverageWithProviders'),
        updated: formatLiveEvidenceTime(
          dossierCoverageSummary?.latest_received_at
            ?? dossierCoverageSentrySummary?.latest_received_at
            ?? dossierCoverageSignozSummary?.latest_received_at,
          dossierCoverageLoaded || dossierProviderRefsLoaded
        ),
      },
    },
    {
      key: 'intake',
      title: tDashboard('automationDiagrams.workspace.flow.stages.intake'),
      status: tDashboard('automationDelivery.status.live'),
      detail: tDashboard('automationDelivery.delivered.cicdTimeline.detail'),
      href: `/${locale}/awooop/runs`,
      tone: 'live',
      owner: tDashboard('automationDiagrams.workspace.inspector.stages.intake.owner'),
      evidence: tDashboard('automationDiagrams.workspace.inspector.stages.intake.evidence'),
      nextAction: tDashboard('automationDiagrams.workspace.inspector.stages.intake.nextAction'),
      liveEvidence: {
        metric: tDashboard('automationDiagrams.workspace.liveEvidence.intake.metric', {
          runs: formatAutomationNumber(automationBrief.runsList?.total, runsListLoaded),
          linked: formatAutomationNumber(recurrenceSummary?.linked_run_total, eventRecurrenceLoaded),
        }),
        detail: tDashboard('automationDiagrams.workspace.liveEvidence.intake.detail', {
          stage: latestCicdEvent?.stage ?? (cicdEventsLoaded ? unavailableValue : loadingStatus),
          status: latestCicdEvent?.status ?? (cicdEventsLoaded ? unavailableValue : loadingStatus),
          commit: latestCicdEvent?.commit_sha?.slice(0, 7) ?? (cicdEventsLoaded ? unavailableValue : loadingStatus),
          attention: formatAutomationNumber(cicdNeedsAttention, cicdEventsLoaded),
        }),
        source: tDashboard('automationDiagrams.workspace.liveEvidence.sources.runsAndCicd'),
        updated: formatLiveEvidenceTime(latestCicdEvent?.created_at ?? latestRun?.created_at, cicdEventsLoaded || runsListLoaded),
      },
    },
    {
      key: 'ai',
      title: tDashboard('automationDiagrams.workspace.flow.stages.ai'),
      status: hasAiRouteStatus ? tDashboard('automationDelivery.status.live') : unavailableStatus,
      detail: tDashboard('automationDiagrams.workspace.values.aiRoute', {
        lane: aiRouteLaneMode,
        provider: aiRouteSelectedProvider,
      }),
      href: `/${locale}/awooop/work-items?project_id=awoooi`,
      tone: hasAiRouteStatus ? 'live' : 'watching',
      owner: tDashboard('automationDiagrams.workspace.inspector.stages.ai.owner'),
      evidence: tDashboard('automationDiagrams.workspace.inspector.stages.ai.evidence'),
      nextAction: tDashboard('automationDiagrams.workspace.inspector.stages.ai.nextAction'),
      liveEvidence: {
        metric: tDashboard('automationDiagrams.workspace.liveEvidence.ai.metric', {
          lane: aiRouteLaneMode,
          provider: aiRouteSelectedProvider,
        }),
        detail: tDashboard('automationDiagrams.workspace.liveEvidence.ai.detail', {
          skipped: formatAutomationNumber(automationBrief.aiRouteStatus?.skipped_lanes?.length, aiRouteStatusLoaded),
          action: automationBrief.aiRouteStatus?.operator_action?.action ?? (aiRouteStatusLoaded ? unavailableValue : loadingStatus),
          reason: automationBrief.aiRouteStatus?.operator_action?.reason ?? (aiRouteStatusLoaded ? unavailableValue : loadingStatus),
        }),
        source: tDashboard('automationDiagrams.workspace.liveEvidence.sources.aiRouteStatus'),
        updated: aiRouteStatusLoaded ? tDashboard('automationDiagrams.workspace.liveEvidence.realtime') : loadingStatus,
      },
    },
    {
      key: 'mcp',
      title: tDashboard('automationDiagrams.workspace.flow.stages.mcp'),
      status: runEvidenceSummary.mcpTotal > 0 || statusChainEvidenceSummary.mcpGateway > 0
        ? tDashboard('automationDelivery.status.live')
        : tDashboard('automationDelivery.status.watching'),
      detail: tDashboard('automationDiagrams.workspace.liveEvidence.mcp.metric', {
        observations: formatAutomationNumber(runEvidenceSummary.mcpTotal, runsListLoaded),
        gateway: formatAutomationNumber(statusChainEvidenceSummary.mcpGateway, true),
      }),
      href: `/${locale}/awooop/runs?project_id=awoooi`,
      tone: runEvidenceSummary.mcpFailed > 0 ? 'progress' : (runEvidenceSummary.mcpTotal > 0 || statusChainEvidenceSummary.mcpGateway > 0) ? 'live' : 'watching',
      owner: tDashboard('automationDiagrams.workspace.inspector.stages.mcp.owner'),
      evidence: tDashboard('automationDiagrams.workspace.inspector.stages.mcp.evidence'),
      nextAction: tDashboard('automationDiagrams.workspace.inspector.stages.mcp.nextAction'),
      liveEvidence: {
        metric: tDashboard('automationDiagrams.workspace.liveEvidence.mcp.metric', {
          observations: formatAutomationNumber(runEvidenceSummary.mcpTotal, runsListLoaded),
          gateway: formatAutomationNumber(statusChainEvidenceSummary.mcpGateway, true),
        }),
        detail: tDashboard('automationDiagrams.workspace.liveEvidence.mcp.detail', {
          success: formatAutomationNumber(runEvidenceSummary.mcpSuccess + statusChainEvidenceSummary.mcpGatewaySuccess, runsListLoaded),
          failed: formatAutomationNumber(runEvidenceSummary.mcpFailed + statusChainEvidenceSummary.mcpGatewayFailed, runsListLoaded),
          server: runEvidenceSummary.latestMcpServer ?? (runsListLoaded ? unavailableValue : loadingStatus),
          route: runEvidenceSummary.latestRoute ?? (runsListLoaded ? unavailableValue : loadingStatus),
        }),
        source: tDashboard('automationDiagrams.workspace.liveEvidence.sources.runsAndStatusChain'),
        updated: formatLiveEvidenceTime(latestRun?.created_at, runsListLoaded),
      },
    },
    {
      key: 'playbook',
      title: tDashboard('automationDiagrams.workspace.flow.stages.playbook'),
      status: topAutomationGate ? tDashboard('automationDelivery.status.blocked') : tDashboard('automationDelivery.status.live'),
      detail: tDashboard('automationDiagrams.workspace.values.topGate', {
        gate: topAutomationGate?.gate ?? (automationQualityLoaded ? unavailableValue : loadingStatus),
        count: formatAutomationNumber(topAutomationGate?.total, automationQualityLoaded),
      }),
      href: `/${locale}/awooop/work-items?project_id=awoooi`,
      tone: topAutomationGate ? 'blocked' : automationQualityAvailable ? 'live' : 'watching',
      owner: tDashboard('automationDiagrams.workspace.inspector.stages.playbook.owner'),
      evidence: tDashboard('automationDiagrams.workspace.inspector.stages.playbook.evidence'),
      nextAction: tDashboard('automationDiagrams.workspace.inspector.stages.playbook.nextAction'),
      liveEvidence: {
        metric: tDashboard('automationDiagrams.workspace.liveEvidence.playbook.metric', {
          gate: topAutomationGate?.gate ?? (automationQualityLoaded ? unavailableValue : loadingStatus),
          gaps: formatAutomationNumber(recurrenceSummary?.automation_gap_group_total, automationBriefLoaded),
        }),
        detail: tDashboard('automationDiagrams.workspace.liveEvidence.playbook.detail', {
          workItems: formatAutomationNumber(recurrenceSummary?.open_work_item_group_total, automationBriefLoaded),
          verifiedGroups: formatAutomationNumber(recurrenceSummary?.verified_repair_group_total, automationBriefLoaded),
          linkedAutoRepair: formatAutomationNumber(recurrenceSummary?.auto_repair_linked_total, automationBriefLoaded),
        }),
        source: tDashboard('automationDiagrams.workspace.liveEvidence.sources.qualityAndRecurrence'),
        updated: formatLiveEvidenceTime(recurrenceSummary?.latest_received_at),
      },
    },
    {
      key: 'ansible',
      title: tDashboard('automationDiagrams.workspace.flow.stages.ansible'),
      status: ansibleRuntime?.can_run_check_mode ? tDashboard('automationDelivery.status.live') : tDashboard('automationDelivery.status.blocked'),
      detail: tDashboard('automationDiagrams.workspace.values.ansible', {
        checkMode: formatAutomationNumber(executionBackend?.ansible_check_mode_total, automationQualityLoaded),
        pending: formatAutomationNumber(executionBackend?.ansible_pending_check_mode_total, automationQualityLoaded),
        blocker: ansibleRuntimeBlockerLabel,
      }),
      href: `/${locale}/awooop/work-items?project_id=awoooi`,
      tone: ansibleRuntime?.can_run_check_mode ? 'live' : automationQualityAvailable ? 'blocked' : 'watching',
      owner: tDashboard('automationDiagrams.workspace.inspector.stages.ansible.owner'),
      evidence: tDashboard('automationDiagrams.workspace.inspector.stages.ansible.evidence'),
      nextAction: ansibleRuntime?.can_run_check_mode
        ? tDashboard('automationDiagrams.workspace.inspector.stages.ansible.nextActionReady')
        : tDashboard('automationDiagrams.workspace.inspector.stages.ansible.nextAction'),
      liveEvidence: {
        metric: tDashboard('automationDiagrams.workspace.liveEvidence.ansible.metric', {
          checkMode: formatAutomationNumber(executionBackend?.ansible_check_mode_total, automationQualityLoaded),
          pending: formatAutomationNumber(executionBackend?.ansible_pending_check_mode_total, automationQualityLoaded),
        }),
        detail: tDashboard('automationDiagrams.workspace.liveEvidence.ansible.detail', {
          blocker: ansibleRuntimeBlockerLabel,
          candidates: formatAutomationNumber(executionBackend?.ansible_candidate_total, automationQualityLoaded),
          operations: formatAutomationNumber(executionBackend?.operation_records_total, automationQualityLoaded),
        }),
        source: tDashboard('automationDiagrams.workspace.liveEvidence.sources.truthChainQuality'),
        updated: automationQualityLoaded ? tDashboard('automationDiagrams.workspace.liveEvidence.realtime') : loadingStatus,
      },
    },
    {
      key: 'approval',
      title: tDashboard('automationDiagrams.workspace.flow.stages.approval'),
      status: canClaimFullAutoRepair ? tDashboard('automationDelivery.status.live') : tDashboard('automationDelivery.status.blocked'),
      detail: tDashboard('automationDiagrams.workspace.values.verified', {
        verified: formatAutomationNumber(verifiedAutomationTotal, automationQualityLoaded),
        evaluated: formatAutomationNumber(evaluatedAutomationTotal, automationQualityLoaded),
      }),
      href: `/${locale}/awooop/approvals`,
      tone: canClaimFullAutoRepair ? 'live' : automationQualityAvailable ? 'blocked' : 'watching',
      owner: tDashboard('automationDiagrams.workspace.inspector.stages.approval.owner'),
      evidence: tDashboard('automationDiagrams.workspace.inspector.stages.approval.evidence'),
      nextAction: tDashboard('automationDiagrams.workspace.inspector.stages.approval.nextAction'),
      liveEvidence: {
        metric: tDashboard('automationDiagrams.workspace.liveEvidence.approval.metric', {
          pending: formatAutomationNumber(pendingApprovals, true),
          verified: formatAutomationNumber(verifiedAutomationTotal, automationQualityLoaded),
          evaluated: formatAutomationNumber(evaluatedAutomationTotal, automationQualityLoaded),
        }),
        detail: tDashboard('automationDiagrams.workspace.liveEvidence.approval.detail', {
          humanGates: formatAutomationNumber(runEvidenceSummary.humanGateRuns, automationBriefLoaded),
          autoRepairRecords: formatAutomationNumber(statusChainEvidenceSummary.autoRepairRecords, true),
          operations: formatAutomationNumber(statusChainEvidenceSummary.operationRecords, true),
        }),
        source: tDashboard('automationDiagrams.workspace.liveEvidence.sources.approvalsAndQuality'),
        updated: automationQualityLoaded ? tDashboard('automationDiagrams.workspace.liveEvidence.realtime') : loadingStatus,
      },
    },
    {
      key: 'verify',
      title: tDashboard('automationDiagrams.workspace.flow.stages.verify'),
      status: typeof kmStaleTotal === 'number' && kmStaleTotal > 0 ? tDashboard('automationDelivery.status.progress') : tDashboard('automationDelivery.status.live'),
      detail: tDashboard('automationDiagrams.workspace.values.km', {
        stale: formatAutomationNumber(kmStaleTotal, kmStaleCandidatesLoaded),
        days: formatAutomationNumber(kmStaleThreshold, kmStaleCandidatesLoaded),
      }),
      href: `/${locale}/knowledge-base`,
      tone: typeof kmStaleTotal === 'number' && kmStaleTotal > 0 ? 'progress' : hasKmStaleCandidates ? 'live' : 'watching',
      owner: tDashboard('automationDiagrams.workspace.inspector.stages.verify.owner'),
      evidence: tDashboard('automationDiagrams.workspace.inspector.stages.verify.evidence'),
      nextAction: tDashboard('automationDiagrams.workspace.inspector.stages.verify.nextAction'),
      liveEvidence: {
        metric: tDashboard('automationDiagrams.workspace.liveEvidence.verify.metric', {
          stale: formatAutomationNumber(kmStaleDisplayCount, kmGovernanceLoaded),
          ratio: staleRatioLabel,
        }),
        detail: tDashboard('automationDiagrams.workspace.liveEvidence.verify.detail', {
          pending: formatAutomationNumber(kmOwnerReviewBurndown?.pending_owner_reviews, kmOwnerReviewBurndownLoaded),
          completed: formatAutomationNumber(kmOwnerReviewBurndown?.completed_owner_reviews, kmOwnerReviewBurndownLoaded),
          remaining: formatAutomationNumber(kmEntriesToThreshold, kmOwnerReviewBurndownLoaded),
        }),
        source: tDashboard('automationDiagrams.workspace.liveEvidence.sources.kmBurndown'),
        updated: formatLiveEvidenceTime(kmOwnerReviewBurndown?.generated_at, kmOwnerReviewBurndownLoaded),
      },
    },
  ]
  const runtimeTopologyLayers = [
    {
      key: 'channels',
      title: tDashboard('automationDiagrams.workspace.topology.layers.channels'),
      items: [
        tDashboard('automationDiagrams.cards.incidentFlow.nodes.alert'),
        tDashboard('automationDiagrams.cards.evidenceLineage.nodes.telegram'),
      ],
    },
    {
      key: 'product',
      title: tDashboard('automationDiagrams.workspace.topology.layers.product'),
      items: [
        tDashboard('automationDiagrams.cards.c4Runtime.nodes.web'),
        tDashboard('automationDiagrams.cards.c4Runtime.nodes.api'),
        tDashboard('automationDiagrams.cards.evidenceLineage.nodes.trace'),
      ],
    },
    {
      key: 'data',
      title: tDashboard('automationDiagrams.workspace.topology.layers.data'),
      items: [
        tDashboard('automationDiagrams.cards.evidenceLineage.nodes.db'),
        tDashboard('automationDiagrams.cards.evidenceLineage.nodes.km'),
      ],
    },
    {
      key: 'execution',
      title: tDashboard('automationDiagrams.workspace.topology.layers.execution'),
      items: [
        tDashboard('automationDiagrams.cards.incidentFlow.nodes.playbook'),
        tDashboard('automationDiagrams.workspace.flow.stages.ansible'),
        tDashboard('automationDiagrams.cards.c4Runtime.nodes.k8s'),
      ],
    },
    {
      key: 'providers',
      title: tDashboard('automationDiagrams.workspace.topology.layers.providers'),
      items: [
        aiRouteSelectedProvider,
        tDashboard('automationDelivery.delivered.aiRoute.detail', {
          lane: aiRouteLaneMode,
          provider: aiRouteSelectedProvider,
        }),
      ],
    },
  ]
  const decisionRows: Array<{
    key: string
    signal: string
    value: string
    outcome: string
    tone: HomepageWorkTone
  }> = [
    {
      key: 'claim',
      signal: tDashboard('automationDiagrams.workspace.decision.rows.claim'),
      value: tDashboard('automationDiagrams.workspace.values.verified', {
        verified: formatAutomationNumber(verifiedAutomationTotal, automationQualityLoaded),
        evaluated: formatAutomationNumber(evaluatedAutomationTotal, automationQualityLoaded),
      }),
      outcome: canClaimFullAutoRepair
        ? tDashboard('automationDiagrams.workspace.decision.outcomes.claimReady')
        : tDashboard('automationDiagrams.workspace.decision.outcomes.claimBlocked'),
      tone: canClaimFullAutoRepair ? 'live' : automationQualityAvailable ? 'blocked' : 'watching',
    },
    {
      key: 'qualityGate',
      signal: tDashboard('automationDiagrams.workspace.decision.rows.qualityGate'),
      value: tDashboard('automationDiagrams.workspace.values.topGate', {
        gate: topAutomationGate?.gate ?? (automationQualityLoaded ? unavailableValue : loadingStatus),
        count: formatAutomationNumber(topAutomationGate?.total, automationQualityLoaded),
      }),
      outcome: tDashboard('automationDiagrams.workspace.decision.outcomes.fillEvidence'),
      tone: topAutomationGate ? 'blocked' : automationQualityAvailable ? 'live' : 'watching',
    },
    {
      key: 'ansible',
      signal: tDashboard('automationDiagrams.workspace.decision.rows.ansible'),
      value: tDashboard('automationDiagrams.workspace.values.ansible', {
        checkMode: formatAutomationNumber(executionBackend?.ansible_check_mode_total, automationQualityLoaded),
        pending: formatAutomationNumber(executionBackend?.ansible_pending_check_mode_total, automationQualityLoaded),
        blocker: ansibleRuntimeBlockerLabel,
      }),
      outcome: ansibleRuntime?.can_run_check_mode
        ? tDashboard('automationDiagrams.workspace.decision.outcomes.ansibleReady')
        : tDashboard('automationDiagrams.workspace.decision.outcomes.ansibleBlocked'),
      tone: ansibleRuntime?.can_run_check_mode ? 'live' : automationQualityAvailable ? 'blocked' : 'watching',
    },
    {
      key: 'aiRoute',
      signal: tDashboard('automationDiagrams.workspace.decision.rows.aiRoute'),
      value: tDashboard('automationDiagrams.workspace.values.aiRoute', {
        lane: aiRouteLaneMode,
        provider: aiRouteSelectedProvider,
      }),
      outcome: tDashboard('automationDiagrams.workspace.decision.outcomes.monitor'),
      tone: hasAiRouteStatus ? 'live' : 'watching',
    },
    {
      key: 'km',
      signal: tDashboard('automationDiagrams.workspace.decision.rows.km'),
      value: tDashboard('automationDiagrams.workspace.values.km', {
        stale: formatAutomationNumber(kmStaleTotal, automationBriefLoaded),
        days: formatAutomationNumber(kmStaleThreshold, automationBriefLoaded),
      }),
      outcome: tDashboard('automationDiagrams.workspace.decision.outcomes.ownerReview'),
      tone: typeof kmStaleTotal === 'number' && kmStaleTotal > 0 ? 'progress' : hasKmStaleCandidates ? 'live' : 'watching',
    },
    {
      key: 'callback',
      signal: tDashboard('automationDiagrams.workspace.decision.rows.callback'),
      value: tDashboard('automationDiagrams.workspace.values.callback', {
        missing: formatAutomationNumber(callbackTraceSummary?.outbound_reply_markup_missing_trace_ref_total, automationBriefLoaded),
        recent1h: formatAutomationNumber(callbackTraceSummary?.outbound_reply_markup_missing_trace_ref_recent_1h_total, automationBriefLoaded),
        recent24h: formatAutomationNumber(callbackTraceSummary?.outbound_reply_markup_missing_trace_ref_recent_24h_total, automationBriefLoaded),
      }),
      outcome: tDashboard('automationDiagrams.workspace.decision.outcomes.watchDecay'),
      tone: callbackTraceSummary && missingTraceRecent24h > 0 ? 'progress' : callbackTraceSummary ? 'live' : 'watching',
    },
  ]
  const lineageNodes = [
    tDashboard('automationDiagrams.workspace.lineage.nodes.telegram'),
    tDashboard('automationDiagrams.workspace.lineage.nodes.callback'),
    tDashboard('automationDiagrams.workspace.lineage.nodes.db'),
    tDashboard('automationDiagrams.workspace.lineage.nodes.run'),
    tDashboard('automationDiagrams.workspace.lineage.nodes.km'),
  ]

  // ── 5 KPI Cards (Sprint 5R 設計稿批准版) ────────────────────────────────────

  const hasPendingApprovals = pendingApprovals !== null && pendingApprovals !== undefined && pendingApprovals > 0
  const incidentCount = incidents?.length ?? 0
  const p1Count = incidents?.filter(i => i.severity === 'P1').length ?? 0
  const p2Count = incidents?.filter(i => i.severity === 'P2').length ?? 0
  const visibleIncidents = incidents?.slice(0, HOMEPAGE_INCIDENT_LIMIT) ?? []
  const hiddenIncidentCount = Math.max(incidentCount - visibleIncidents.length, 0)
  const truthChainCoveredCount = requestedIncidentIds.filter((incidentId) => {
    const chain = statusChains[incidentId]
    return Boolean(chain && !chain.fetch_error && chain.source_id)
  }).length
  const truthChainCoverageLabel = isStatusChainsLoading
    ? tDashboard('truthChainLoading')
    : tDashboard('truthChainCoverage', {
      loaded: truthChainCoveredCount,
      shown: requestedIncidentIds.length,
    })
  const liveTopologyGroups = Object.values(
    hosts.reduce<Record<string, {
      role: string
      hosts: Host[]
      serviceCount: number
      healthyServices: number
      serviceNames: string[]
    }>>((acc, host) => {
      const role = host.role || 'devops'
      const current = acc[role] ?? { role, hosts: [], serviceCount: 0, healthyServices: 0, serviceNames: [] }
      current.hosts.push(host)
      current.serviceCount += host.services.length
      current.healthyServices += host.services.filter(service => isHealthyService(service.status)).length
      current.serviceNames.push(...host.services.map(service => service.name))
      acc[role] = current
      return acc
    }, {})
  )
    .map(group => ({
      ...group,
      serviceNames: Array.from(new Set(group.serviceNames)).slice(0, 5),
    }))
    .sort((a, b) => {
      const order = ['devops', 'security', 'k3s', 'ai_web']
      return order.indexOf(a.role) - order.indexOf(b.role)
    })

  // 近 24h 操作數。首頁 KPI 必須顯示窗口值，避免把 total_executions 誤讀成今日事件。
  const [auditStats, setAuditStats] = useState<{ last_24h_count?: number; total_executions?: number } | null>(null)
  useEffect(() => {
    fetch(`${API_BASE}/api/v1/audit-logs/stats`)
      .then(r => r.ok ? r.json() : null)
      .then(d => {
        if (d) {
          setAuditStats({
            last_24h_count: typeof d.last_24h_count === 'number' ? d.last_24h_count : undefined,
            total_executions: typeof d.total_executions === 'number' ? d.total_executions : undefined,
          })
        }
      })
      .catch(() => {})
  }, [])

  // 系統健康百分比
  const systemHealthPct = totalServices > 0 ? Math.round((healthyServices / totalServices) * 100) : 0

  // Sprint 5: 4 Tab 配置 (人工批准 2026-04-08)
  const alertsCount = incidents?.length ?? 0
  const tabs: TabConfig[] = [
    { id: 'overview', label: tDashboard('tabs.overview'), content: null },
    { id: 'alerts', label: tDashboard('tabs.alerts'), badge: alertsCount > 0 ? alertsCount : undefined, content: <AlertsAndApprovalsTab /> },
    { id: 'stream', label: tDashboard('tabs.stream'), content: <ActivityStreamTab /> },
    { id: 'disposition', label: tDashboard('tabs.disposition'), content: <DispositionTab /> },
  ]

  // Sprint 5: 從 URL 讀取當前 Tab
  const [activeTabId, setActiveTabId] = useState('overview')
  const [infraView, setInfraView] = useState<'host' | 'topo'>('topo')
  const [selectedHost, setSelectedHost] = useState<Host | null>(null)
  const [compactViewport, setCompactViewport] = useState(false)
  const [selectedBlueprintStageKey, setSelectedBlueprintStageKey] = useState<HomepageBlueprintStageKey>('ansible')

  // I1 修正: popstate 取代 100ms 輪詢
  useEffect(() => {
    const syncTab = () => {
      const tab = new URLSearchParams(window.location.search).get('tab') || 'overview'
      setActiveTabId(prev => prev !== tab ? tab : prev)
    }
    syncTab()
    window.addEventListener('popstate', syncTab)
    // PageTabs router.push 後 URL 改變，用 hashchange + 定期低頻同步(1s)作為備援
    const fallback = setInterval(syncTab, 1000)
    return () => { window.removeEventListener('popstate', syncTab); clearInterval(fallback) }
  }, [])

  useEffect(() => {
    const media = window.matchMedia('(max-width: 720px)')
    const syncViewport = () => setCompactViewport(media.matches)

    syncViewport()
    media.addEventListener('change', syncViewport)

    return () => {
      media.removeEventListener('change', syncViewport)
    }
  }, [])

  useEffect(() => {
    const syncBlueprintStage = () => {
      const requestedStage = new URLSearchParams(window.location.search).get('blueprint_stage')
      if (requestedStage && HOMEPAGE_BLUEPRINT_STAGE_KEYS.includes(requestedStage as HomepageBlueprintStageKey)) {
        setSelectedBlueprintStageKey(requestedStage as HomepageBlueprintStageKey)
      }
    }

    syncBlueprintStage()
    window.addEventListener('popstate', syncBlueprintStage)
    window.addEventListener('hashchange', syncBlueprintStage)

    return () => {
      window.removeEventListener('popstate', syncBlueprintStage)
      window.removeEventListener('hashchange', syncBlueprintStage)
    }
  }, [])

  const primarySectionMargin = compactViewport ? '10px 8px 0' : '14px 20px 0'
  const secondarySectionMargin = compactViewport ? '10px 8px 0' : '12px 20px 0'
  const sectionPadding = compactViewport ? 10 : 14
  const dashboardGridTemplate = compactViewport ? '1fr' : 'repeat(auto-fit, minmax(320px, 1fr))'
  const diagramCardGridTemplate = compactViewport ? '1fr' : 'repeat(auto-fit, minmax(240px, 1fr))'
  const diagramWorkspaceGridTemplate = compactViewport ? '1fr' : 'repeat(auto-fit, minmax(min(360px, 100%), 1fr))'
  const flowStageGridTemplate = compactViewport ? '1fr' : 'repeat(auto-fit, minmax(138px, 1fr))'
  const topologyGridTemplate = compactViewport ? '1fr' : 'repeat(auto-fit, minmax(150px, 1fr))'
  const decisionGridTemplate = compactViewport ? '1fr' : '0.8fr 1.15fr 1.05fr'
  const workItemGridTemplate = compactViewport ? '1fr' : '1fr auto'
  const selectedBlueprintStage = automationFlowStages.find(stage => stage.key === selectedBlueprintStageKey) ?? automationFlowStages[0]
  const selectedBlueprintStageIndex = Math.max(automationFlowStages.findIndex(stage => stage.key === selectedBlueprintStage.key), 0)
  const selectedBlueprintTone = automationWorkToneStyle[selectedBlueprintStage.tone]
  const commandMapMetrics: Array<{
    key: string
    label: string
    value: string
    detail: string
    tone: HomepageWorkTone
    href: string
  }> = [
    {
      key: 'claim',
      label: tDashboard('homeCommandMap.metrics.claim'),
      value: autoRemediationRate,
      detail: tDashboard('automationDiagrams.workspace.values.verified', {
        verified: formatAutomationNumber(verifiedAutomationTotal, automationQualityLoaded),
        evaluated: formatAutomationNumber(evaluatedAutomationTotal, automationQualityLoaded),
      }),
      tone: canClaimFullAutoRepair ? 'live' : automationQualityAvailable ? 'blocked' : 'watching',
      href: `/${locale}/awooop/runs?project_id=awoooi`,
    },
    {
      key: 'quality',
      label: tDashboard('homeCommandMap.metrics.quality'),
      value: topAutomationGate?.gate ?? (automationQualityLoaded ? unavailableValue : loadingStatus),
      detail: tDashboard('automationDiagrams.workspace.values.topGate', {
        gate: topAutomationGate?.gate ?? (automationQualityLoaded ? unavailableValue : loadingStatus),
        count: formatAutomationNumber(topAutomationGate?.total, automationQualityLoaded),
      }),
      tone: topAutomationGate ? 'blocked' : automationQualityAvailable ? 'live' : 'watching',
      href: `/${locale}/awooop/work-items?project_id=awoooi`,
    },
    {
      key: 'provider',
      label: tDashboard('homeCommandMap.metrics.provider'),
      value: aiRouteSelectedProvider,
      detail: tDashboard('automationDiagrams.workspace.values.aiRoute', {
        lane: aiRouteLaneMode,
        provider: aiRouteSelectedProvider,
      }),
      tone: hasAiRouteStatus ? 'live' : 'watching',
      href: `/${locale}/awooop/work-items?project_id=awoooi`,
    },
    {
      key: 'km',
      label: tDashboard('homeCommandMap.metrics.km'),
      value: staleRatioLabel,
      detail: tDashboard('automationDiagrams.workspace.values.km', {
        stale: formatAutomationNumber(kmStaleDisplayCount, kmGovernanceLoaded),
        days: formatAutomationNumber(kmStaleThreshold ?? kmBurndownSnapshot?.stale_days, kmGovernanceLoaded),
      }),
      tone: typeof kmStaleDisplayCount === 'number' && kmStaleDisplayCount > 0 ? 'progress' : hasKmStaleCandidates ? 'live' : 'watching',
      href: `/${locale}/knowledge-base`,
    },
  ]
  const commandMapEvidenceSources = [
    {
      key: 'channels',
      label: tDashboard('automationDiagrams.workspace.topology.layers.channels'),
      value: tDashboard('automationDiagrams.workspace.liveEvidence.signal.metric', {
        sources: formatAutomationNumber(dossierCoverageSummary?.source_count, dossierCoverageLoaded),
        refs: formatAutomationNumber(dossierCoverageSummary?.source_ref_total, dossierCoverageLoaded),
      }),
    },
    {
      key: 'runs',
      label: tDashboard('automationDiagrams.workspace.topology.layers.product'),
      value: tDashboard('automationDiagrams.workspace.liveEvidence.intake.metric', {
        runs: formatAutomationNumber(automationBrief.runsList?.total, runsListLoaded),
        linked: formatAutomationNumber(recurrenceSummary?.linked_run_total, eventRecurrenceLoaded),
      }),
    },
    {
      key: 'mcp',
      label: tDashboard('automationDiagrams.workspace.flow.stages.mcp'),
      value: tDashboard('automationDiagrams.workspace.liveEvidence.mcp.metric', {
        observations: formatAutomationNumber(runEvidenceSummary.mcpTotal, runsListLoaded),
        gateway: formatAutomationNumber(statusChainEvidenceSummary.mcpGateway, true),
      }),
    },
    {
      key: 'verification',
      label: tDashboard('automationDiagrams.workspace.flow.stages.verify'),
      value: tDashboard('automationDiagrams.workspace.liveEvidence.verify.metric', {
        stale: formatAutomationNumber(kmStaleDisplayCount, kmGovernanceLoaded),
        ratio: staleRatioLabel,
      }),
    },
  ]
  const commandMapSwimlanes: Array<{
    key: string
    label: string
    summary: string
    tone: HomepageWorkTone
    stages: HomepageBlueprintStage[]
  }> = [
    {
      key: 'signals',
      label: tDashboard('homeCommandMap.swimlanes.signals'),
      summary: tDashboard('automationDiagrams.workspace.liveEvidence.signal.metric', {
        sources: formatAutomationNumber(dossierCoverageSummary?.source_count, dossierCoverageLoaded),
        refs: formatAutomationNumber(dossierCoverageSummary?.source_ref_total, dossierCoverageLoaded),
      }),
      tone: dossierCoverageLoaded ? 'live' : 'watching',
      stages: automationFlowStages.filter(stage => stage.key === 'signal' || stage.key === 'intake'),
    },
    {
      key: 'reasoning',
      label: tDashboard('homeCommandMap.swimlanes.reasoning'),
      summary: tDashboard('automationDiagrams.workspace.values.aiRoute', {
        lane: aiRouteLaneMode,
        provider: aiRouteSelectedProvider,
      }),
      tone: hasAiRouteStatus ? 'live' : 'watching',
      stages: automationFlowStages.filter(stage => stage.key === 'ai' || stage.key === 'mcp'),
    },
    {
      key: 'execution',
      label: tDashboard('homeCommandMap.swimlanes.execution'),
      summary: tDashboard('automationDiagrams.workspace.values.ansible', {
        checkMode: formatAutomationNumber(executionBackend?.ansible_check_mode_total, automationQualityLoaded),
        pending: formatAutomationNumber(executionBackend?.ansible_pending_check_mode_total, automationQualityLoaded),
        blocker: ansibleRuntimeBlockerLabel,
      }),
      tone: ansibleRuntime?.can_run_check_mode ? 'live' : automationQualityAvailable ? 'blocked' : 'watching',
      stages: automationFlowStages.filter(stage => stage.key === 'playbook' || stage.key === 'ansible'),
    },
    {
      key: 'governance',
      label: tDashboard('homeCommandMap.swimlanes.governance'),
      summary: tDashboard('automationDiagrams.workspace.liveEvidence.verify.metric', {
        stale: formatAutomationNumber(kmStaleDisplayCount, kmGovernanceLoaded),
        ratio: staleRatioLabel,
      }),
      tone: typeof kmStaleDisplayCount === 'number' && kmStaleDisplayCount > 0 ? 'progress' : hasKmStaleCandidates ? 'live' : 'watching',
      stages: automationFlowStages.filter(stage => stage.key === 'approval' || stage.key === 'verify'),
    },
  ]
  const productModuleRows: Array<{
    key: string
    module: string
    owns: string
    evidence: string
    href: string
    tone: HomepageWorkTone
  }> = [
    {
      key: 'awooop',
      module: tDashboard('homeProductMap.modules.awooop.module'),
      owns: tDashboard('homeProductMap.modules.awooop.owns'),
      evidence: tDashboard('automationDiagrams.workspace.liveEvidence.intake.metric', {
        runs: formatAutomationNumber(automationBrief.runsList?.total, runsListLoaded),
        linked: formatAutomationNumber(recurrenceSummary?.linked_run_total, eventRecurrenceLoaded),
      }),
      href: `/${locale}/awooop/runs?project_id=awoooi`,
      tone: 'live',
    },
    {
      key: 'routing',
      module: tDashboard('homeProductMap.modules.routing.module'),
      owns: tDashboard('homeProductMap.modules.routing.owns'),
      evidence: tDashboard('automationDiagrams.workspace.values.aiRoute', {
        lane: aiRouteLaneMode,
        provider: aiRouteSelectedProvider,
      }),
      href: `/${locale}/awooop/work-items?project_id=awoooi`,
      tone: hasAiRouteStatus ? 'live' : 'watching',
    },
    {
      key: 'execution',
      module: tDashboard('homeProductMap.modules.execution.module'),
      owns: tDashboard('homeProductMap.modules.execution.owns'),
      evidence: tDashboard('automationDiagrams.workspace.values.ansible', {
        checkMode: formatAutomationNumber(executionBackend?.ansible_check_mode_total, automationQualityLoaded),
        pending: formatAutomationNumber(executionBackend?.ansible_pending_check_mode_total, automationQualityLoaded),
        blocker: ansibleRuntimeBlockerLabel,
      }),
      href: `/${locale}/automation`,
      tone: ansibleRuntime?.can_run_check_mode ? 'live' : automationQualityAvailable ? 'blocked' : 'watching',
    },
    {
      key: 'learning',
      module: tDashboard('homeProductMap.modules.learning.module'),
      owns: tDashboard('homeProductMap.modules.learning.owns'),
      evidence: tDashboard('automationDiagrams.workspace.liveEvidence.verify.metric', {
        stale: formatAutomationNumber(kmStaleDisplayCount, kmGovernanceLoaded),
        ratio: staleRatioLabel,
      }),
      href: `/${locale}/knowledge-base`,
      tone: typeof kmStaleDisplayCount === 'number' && kmStaleDisplayCount > 0 ? 'progress' : hasKmStaleCandidates ? 'live' : 'watching',
    },
  ]

  return (
    <AppLayout locale={locale} showBackground={false} fullBleed>
      {/* Sprint 5: Tab Bar */}
      <PageTabs
        tabs={tabs.map(t => ({ ...t, content: t.id === 'overview' ? <></> : t.content }))}
        defaultTab="overview"
        syncWithUrl={true}
      />

      {/* Tab 1 戰情總覽: 顯示現有首頁完整內容 */}
      {activeTabId === 'overview' && (
      <div style={{
        display: 'flex',
        flexDirection: 'column',
        minHeight: 'calc(100vh - 68px)',
        background: '#f5f4ed',
        fontFamily: 'var(--font-body), monospace',
        overflowX: 'hidden',
        overflowY: 'visible',
      }}>

        <section
          data-testid="homepage-product-map"
          style={{
            margin: primarySectionMargin,
            background: '#fff',
            borderTop: '0.5px solid #d8d3c7',
            borderBottom: '0.5px solid #d8d3c7',
            flexShrink: 0,
          }}
        >
          <div style={{
            display: 'grid',
            gridTemplateColumns: compactViewport ? '1fr' : 'minmax(0, 1.4fr) minmax(260px, 0.6fr)',
            gap: compactViewport ? 10 : 18,
            padding: compactViewport ? '14px 12px' : '18px 20px',
            borderBottom: '0.5px solid #e0ddd4',
            background: '#fffdf8',
          }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 11, fontWeight: 850, color: '#1f5b9b', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                {tDashboard('homeProductMap.eyebrow')}
              </div>
              <h1 style={{ margin: '5px 0 0', fontSize: compactViewport ? 22 : 28, lineHeight: 1.1, fontWeight: 900, color: '#141413' }}>
                {tDashboard('homeProductMap.title')}
              </h1>
              <p style={{ margin: '8px 0 0', maxWidth: 820, fontSize: 13, lineHeight: 1.65, color: '#4e4a43' }}>
                {tDashboard('homeProductMap.subtitle')}
              </p>
            </div>
            <div style={{
              alignSelf: 'stretch',
              display: 'grid',
              gap: 8,
              border: `0.5px solid ${automationDeliveryClaimTone.border}`,
              background: automationDeliveryClaimTone.bg,
              padding: '11px 12px',
            }}>
              <div style={{ fontSize: 10, fontWeight: 850, color: automationDeliveryClaimTone.color, textTransform: 'uppercase', letterSpacing: 0.5 }}>
                {tDashboard('homeProductMap.currentGate')}
              </div>
              <div style={{ fontSize: 16, fontWeight: 900, color: '#141413', lineHeight: 1.2 }}>
                {automationDeliveryHeadline}
              </div>
              <div style={{ fontSize: 11, lineHeight: 1.5, color: '#5f5b52' }}>
                {automationDeliveryClaimDetail}
              </div>
            </div>
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: compactViewport ? '1fr' : 'minmax(0, 1.35fr) minmax(320px, 0.85fr)',
            gap: compactViewport ? 10 : 14,
            padding: compactViewport ? 12 : 16,
          }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 10, marginBottom: 10 }}>
                <h2 style={{ margin: 0, fontSize: 15, fontWeight: 900, color: '#141413' }}>
                  {tDashboard('homeProductMap.flowTitle')}
                </h2>
                <a href={`/${locale}/awooop/runs?project_id=awoooi`} style={{ fontSize: 11, fontWeight: 800, color: '#1f5b9b', textDecoration: 'none' }}>
                  {tDashboard('automationDelivery.openRuns')}
                </a>
              </div>
              <div style={{
                display: 'grid',
                gridTemplateColumns: compactViewport ? '1fr' : 'repeat(4, minmax(0, 1fr))',
                gap: 8,
              }}>
                {automationFlowStages.map((stage, index) => {
                  const tone = automationWorkToneStyle[stage.tone]
                  return (
                    <a
                      key={`product-map-${stage.key}`}
                      href={`/${locale}?blueprint_stage=${stage.key}#homepage-ai-command-map`}
                      onClick={() => setSelectedBlueprintStageKey(stage.key as HomepageBlueprintStageKey)}
                      style={{
                        minWidth: 0,
                        border: `0.5px solid ${tone.border}`,
                        background: tone.bg,
                        padding: '9px 10px',
                        color: 'inherit',
                        textDecoration: 'none',
                      }}
                    >
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                        <span style={{ fontSize: 10, fontWeight: 900, color: tone.color, fontFamily: "'JetBrains Mono', monospace" }}>
                          {String(index + 1).padStart(2, '0')}
                        </span>
                        <span style={{ fontSize: 9, fontWeight: 850, color: tone.color, textTransform: 'uppercase', whiteSpace: 'nowrap' }}>
                          {stage.status}
                        </span>
                      </div>
                      <div style={{ marginTop: 8, fontSize: 12, fontWeight: 900, color: '#141413', lineHeight: 1.25 }}>
                        {stage.title}
                      </div>
                      <div style={{ marginTop: 6, fontSize: 10, lineHeight: 1.45, color: '#5f5b52', minHeight: 30, overflow: 'hidden' }}>
                        {stage.liveEvidence.metric}
                      </div>
                    </a>
                  )
                })}
              </div>
            </div>

            <div style={{ minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 10, marginBottom: 10 }}>
                <h2 style={{ margin: 0, fontSize: 15, fontWeight: 900, color: '#141413' }}>
                  {tDashboard('homeProductMap.moduleTitle')}
                </h2>
                <a href={`/${locale}/topology`} style={{ fontSize: 11, fontWeight: 800, color: '#1f5b9b', textDecoration: 'none' }}>
                  {tDashboard('automationDiagrams.openTopology')}
                </a>
              </div>
              <div style={{ display: 'grid', gap: 1, border: '0.5px solid #e0ddd4', background: '#e0ddd4' }}>
                {productModuleRows.map((row) => {
                  const tone = automationWorkToneStyle[row.tone]
                  return (
                    <a
                      key={row.key}
                      href={row.href}
                      style={{
                        display: 'grid',
                        gridTemplateColumns: compactViewport ? '1fr' : '0.72fr 1fr',
                        gap: 8,
                        padding: '9px 10px',
                        background: '#fff',
                        color: 'inherit',
                        textDecoration: 'none',
                      }}
                    >
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 12, fontWeight: 900, color: '#141413' }}>{row.module}</div>
                        <div style={{ marginTop: 3, fontSize: 10, lineHeight: 1.4, color: '#5f5b52' }}>{row.owns}</div>
                      </div>
                      <div style={{ minWidth: 0 }}>
                        <div style={{
                          display: 'inline-flex',
                          maxWidth: '100%',
                          border: `0.5px solid ${tone.border}`,
                          background: tone.bg,
                          color: tone.color,
                          padding: '2px 7px',
                          fontSize: 10,
                          fontWeight: 850,
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          whiteSpace: 'nowrap',
                        }}>
                          {row.evidence}
                        </div>
                      </div>
                    </a>
                  )
                })}
              </div>
            </div>
          </div>
        </section>

        <section style={{
          margin: primarySectionMargin,
          background: '#fff',
          border: '0.5px solid #d8d3c7',
          borderRadius: 10,
          boxShadow: '0 1px 4px rgba(0,0,0,0.05)',
          overflow: 'hidden',
          flexShrink: 0,
        }}>
          <div style={{
            display: 'flex',
            flexDirection: compactViewport ? 'column' : 'row',
            alignItems: 'flex-start',
            justifyContent: 'space-between',
            gap: 16,
            padding: compactViewport ? '12px 10px' : '14px 16px',
            borderBottom: '0.5px solid #e0ddd4',
            background: '#faf9f3',
          }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: 0.5, color: '#77736a', fontWeight: 700 }}>
                {tDashboard('automationDelivery.eyebrow')}
              </div>
              <h1 style={{ margin: '4px 0 0', fontSize: compactViewport ? 20 : 22, lineHeight: 1.15, fontWeight: 800, color: '#141413' }}>
                {tDashboard('automationDelivery.title')}
              </h1>
              <p style={{ margin: '6px 0 0', maxWidth: 840, fontSize: 13, lineHeight: 1.6, color: '#5f5b52' }}>
                {tDashboard('automationDelivery.subtitle')}
              </p>
            </div>
            <div style={{
              minWidth: compactViewport ? 0 : 220,
              width: compactViewport ? '100%' : undefined,
              border: `0.5px solid ${automationDeliveryClaimTone.border}`,
              background: automationDeliveryClaimTone.bg,
              borderRadius: 8,
              padding: '10px 12px',
            }}>
              <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.5, color: '#77736a', fontWeight: 700 }}>
                {tDashboard('automationDelivery.claimLabel')}
              </div>
              <div style={{ marginTop: 4, fontSize: 15, fontWeight: 800, color: automationDeliveryClaimTone.color }}>
                {automationDeliveryHeadline}
              </div>
              <div style={{ marginTop: 4, fontSize: 11, color: '#5f5b52', lineHeight: 1.5 }}>
                {automationDeliveryClaimDetail}
              </div>
            </div>
          </div>

          <div
            id="homepage-ai-command-map"
            data-testid="homepage-ai-command-map"
            style={{
              display: 'grid',
              gridTemplateColumns: compactViewport ? '1fr' : 'minmax(0, 1.65fr) minmax(300px, 0.75fr)',
              gap: compactViewport ? 10 : 14,
              padding: sectionPadding,
              borderBottom: '0.5px solid #e0ddd4',
              background: '#f7f8f4',
            }}
          >
            <div style={{
              border: '0.5px solid #cfd8d0',
              borderRadius: 8,
              background: '#fff',
              padding: compactViewport ? 10 : 12,
              minWidth: 0,
            }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, marginBottom: 10 }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 10, fontWeight: 800, color: '#1f5b9b', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                    {tDashboard('homeCommandMap.eyebrow')}
                  </div>
                  <h2 style={{ margin: '3px 0 0', fontSize: compactViewport ? 17 : 19, lineHeight: 1.15, fontWeight: 850, color: '#141413' }}>
                    {tDashboard('homeCommandMap.title')}
                  </h2>
                  <p style={{ margin: '5px 0 0', maxWidth: 720, fontSize: 11, lineHeight: 1.55, color: '#5f5b52' }}>
                    {tDashboard('homeCommandMap.subtitle')}
                  </p>
                </div>
                <a href={`/${locale}/awooop/runs?project_id=awoooi`} style={{
                  flexShrink: 0,
                  border: '0.5px solid #9bb6d9',
                  background: '#eef5ff',
                  color: '#1f5b9b',
                  borderRadius: 999,
                  padding: '5px 9px',
                  fontSize: 10,
                  fontWeight: 800,
                  textDecoration: 'none',
                  whiteSpace: 'nowrap',
                }}>
                  {tDashboard('homeCommandMap.openRuns')}
                </a>
              </div>

              <div style={{
                display: 'grid',
                gridTemplateColumns: compactViewport ? '1fr' : 'repeat(4, minmax(0, 1fr))',
                gap: 8,
                marginBottom: 10,
              }}>
                {commandMapMetrics.map(metric => {
                  const tone = automationWorkToneStyle[metric.tone]
                  return (
                    <a
                      key={metric.key}
                      href={metric.href}
                      style={{
                        border: `0.5px solid ${tone.border}`,
                        borderRadius: 8,
                        background: tone.bg,
                        padding: '9px 10px',
                        color: 'inherit',
                        textDecoration: 'none',
                        minWidth: 0,
                      }}
                    >
                      <div style={{ fontSize: 10, fontWeight: 800, color: tone.color, textTransform: 'uppercase', letterSpacing: 0.4 }}>
                        {metric.label}
                      </div>
                      <div style={{
                        marginTop: 5,
                        fontSize: compactViewport ? 15 : 17,
                        fontWeight: 850,
                        color: '#141413',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                      }}>
                        {metric.value}
                      </div>
                      <div style={{
                        marginTop: 4,
                        fontSize: 10,
                        color: '#5f5b52',
                        lineHeight: 1.45,
                        minHeight: 28,
                        overflow: 'hidden',
                      }}>
                        {metric.detail}
                      </div>
                    </a>
                  )
                })}
              </div>

              <div style={{
                display: 'grid',
                gridTemplateColumns: compactViewport ? '1fr' : 'repeat(4, minmax(0, 1fr))',
                gap: 8,
                marginBottom: 10,
              }}>
                {commandMapSwimlanes.map((lane) => {
                  const laneTone = automationWorkToneStyle[lane.tone]
                  return (
                    <div
                      key={lane.key}
                      style={{
                        minWidth: 0,
                        border: `0.5px solid ${laneTone.border}`,
                        borderRadius: 9,
                        background: '#fffdf8',
                        overflow: 'hidden',
                      }}
                    >
                      <div style={{
                        borderBottom: `0.5px solid ${laneTone.border}`,
                        background: laneTone.bg,
                        padding: '7px 8px',
                      }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
                          <span style={{
                            width: 8,
                            height: 8,
                            borderRadius: 999,
                            background: laneTone.color,
                            flexShrink: 0,
                          }} />
                          <div style={{
                            minWidth: 0,
                            fontSize: 10,
                            fontWeight: 900,
                            color: laneTone.color,
                            textTransform: 'uppercase',
                            letterSpacing: 0.35,
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                          }}>
                            {lane.label}
                          </div>
                        </div>
                        <div style={{
                          marginTop: 5,
                          minHeight: 30,
                          fontSize: 10,
                          lineHeight: 1.45,
                          color: '#4e4a43',
                          overflowWrap: 'anywhere',
                        }}>
                          {lane.summary}
                        </div>
                      </div>
                      <div style={{
                        display: 'grid',
                        gridTemplateColumns: '1fr',
                        gap: 6,
                        padding: 8,
                      }}>
                        {lane.stages.map((stage, index) => {
                          const stageTone = automationWorkToneStyle[stage.tone]
                          const isSelectedStage = stage.key === selectedBlueprintStage.key
                          return (
                            <a
                              key={`${lane.key}-${stage.key}`}
                              href={`/${locale}?blueprint_stage=${stage.key}#homepage-ai-command-map`}
                              onClick={() => setSelectedBlueprintStageKey(stage.key as HomepageBlueprintStageKey)}
                              aria-current={isSelectedStage ? 'step' : undefined}
                              style={{
                                position: 'relative',
                                display: 'grid',
                                gridTemplateColumns: '22px minmax(0, 1fr)',
                                gap: 7,
                                alignItems: 'center',
                                minHeight: 34,
                                border: `0.5px solid ${isSelectedStage ? stageTone.color : '#e0ddd4'}`,
                                borderRadius: 7,
                                background: isSelectedStage ? stageTone.bg : '#fff',
                                color: 'inherit',
                                textDecoration: 'none',
                                padding: '5px 6px',
                              }}
                            >
                              {index > 0 && (
                                <span style={{
                                  position: 'absolute',
                                  left: 16,
                                  top: -7,
                                  width: 1,
                                  height: 7,
                                  background: '#c8c0b2',
                                }} />
                              )}
                              <span style={{
                                width: 22,
                                height: 22,
                                borderRadius: 999,
                                border: `0.5px solid ${stageTone.border}`,
                                background: stageTone.bg,
                                color: stageTone.color,
                                display: 'inline-flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                fontSize: 9,
                                fontWeight: 900,
                                fontFamily: "'JetBrains Mono', monospace",
                              }}>
                                {automationFlowStages.findIndex(flowStage => flowStage.key === stage.key) + 1}
                              </span>
                              <span style={{
                                minWidth: 0,
                                fontSize: 10,
                                fontWeight: 850,
                                color: '#141413',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                whiteSpace: 'nowrap',
                              }}>
                                {stage.title}
                              </span>
                            </a>
                          )
                        })}
                      </div>
                    </div>
                  )
                })}
              </div>

              <div style={{
                display: 'grid',
                gridTemplateColumns: compactViewport ? '1fr' : 'repeat(4, minmax(0, 1fr))',
                gap: 7,
              }}>
                {automationFlowStages.map((stage, index) => {
                  const tone = automationWorkToneStyle[stage.tone]
                  const isSelectedStage = stage.key === selectedBlueprintStage.key
                  return (
                    <a
                      key={`command-${stage.key}`}
                      href={`/${locale}?blueprint_stage=${stage.key}#homepage-ai-command-map`}
                      onClick={() => setSelectedBlueprintStageKey(stage.key as HomepageBlueprintStageKey)}
                      aria-current={isSelectedStage ? 'step' : undefined}
                      style={{
                        position: 'relative',
                        minHeight: compactViewport ? 68 : 84,
                        border: `0.5px solid ${isSelectedStage ? tone.color : tone.border}`,
                        borderRadius: 8,
                        background: isSelectedStage ? '#fff' : tone.bg,
                        padding: '8px 8px 9px',
                        color: 'inherit',
                        textDecoration: 'none',
                        boxShadow: isSelectedStage ? `inset 0 0 0 1px ${tone.color}` : 'none',
                      }}
                    >
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6 }}>
                        <span style={{
                          width: 22,
                          height: 22,
                          borderRadius: 999,
                          border: `0.5px solid ${tone.border}`,
                          background: tone.bg,
                          color: tone.color,
                          display: 'inline-flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          fontSize: 10,
                          fontWeight: 850,
                          fontFamily: "'JetBrains Mono', monospace",
                        }}>
                          {index + 1}
                        </span>
                        <span style={{
                          border: `0.5px solid ${tone.border}`,
                          background: tone.bg,
                          color: tone.color,
                          borderRadius: 999,
                          padding: '1px 6px',
                          fontSize: 9,
                          fontWeight: 800,
                          whiteSpace: 'nowrap',
                        }}>
                          {stage.status}
                        </span>
                      </div>
                      <div style={{
                        marginTop: 8,
                        fontSize: 11,
                        lineHeight: 1.25,
                        fontWeight: 850,
                        color: '#141413',
                        minHeight: compactViewport ? 0 : 16,
                      }}>
                        {stage.title}
                      </div>
                      <div style={{
                        marginTop: 7,
                        height: 5,
                        borderRadius: 999,
                        background: '#ece8dc',
                        overflow: 'hidden',
                      }}>
                        <div style={{
                          width: stage.tone === 'live' ? '100%' : stage.tone === 'progress' ? '66%' : stage.tone === 'blocked' ? '34%' : '48%',
                          height: '100%',
                          background: tone.color,
                        }} />
                      </div>
                    </a>
                  )
                })}
              </div>
            </div>

            <aside style={{
              border: `0.5px solid ${selectedBlueprintTone.border}`,
              borderRadius: 8,
              background: selectedBlueprintTone.bg,
              padding: compactViewport ? 10 : 12,
              minWidth: 0,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
                <div style={{ fontSize: 10, fontWeight: 800, color: selectedBlueprintTone.color, textTransform: 'uppercase', letterSpacing: 0.5 }}>
                  {tDashboard('homeCommandMap.selectedStage')}
                </div>
                <div style={{
                  border: `0.5px solid ${selectedBlueprintTone.border}`,
                  background: '#fff',
                  color: selectedBlueprintTone.color,
                  borderRadius: 999,
                  padding: '2px 7px',
                  fontSize: 10,
                  fontWeight: 850,
                  whiteSpace: 'nowrap',
                }}>
                  {selectedBlueprintStageIndex + 1}/{automationFlowStages.length}
                </div>
              </div>
              <h3 style={{ margin: '7px 0 0', fontSize: 16, fontWeight: 850, color: '#141413', lineHeight: 1.2 }}>
                {selectedBlueprintStage.title}
              </h3>
              <div style={{ marginTop: 6, fontSize: 11, lineHeight: 1.55, color: '#4e4a43' }}>
                {selectedBlueprintStage.liveEvidence.metric}
              </div>
              <dl style={{ display: 'grid', gap: 8, margin: '11px 0 0' }}>
                {[
                  [tDashboard('automationDiagrams.workspace.inspector.fields.owner'), selectedBlueprintStage.owner],
                  [tDashboard('automationDiagrams.workspace.inspector.fields.evidence'), selectedBlueprintStage.liveEvidence.source],
                  [tDashboard('automationDiagrams.workspace.inspector.fields.nextAction'), selectedBlueprintStage.nextAction],
                ].map(([label, value]) => (
                  <div key={label} style={{
                    border: '0.5px solid rgba(20,20,19,0.12)',
                    borderRadius: 7,
                    background: 'rgba(255,255,255,0.66)',
                    padding: '7px 8px',
                  }}>
                    <dt style={{ fontSize: 9, textTransform: 'uppercase', letterSpacing: 0.4, fontWeight: 800, color: '#77736a' }}>{label}</dt>
                    <dd style={{ margin: '3px 0 0', fontSize: 11, lineHeight: 1.45, color: '#2e2b26' }}>{value}</dd>
                  </div>
                ))}
              </dl>
              <div style={{ marginTop: 12 }}>
                <div style={{ fontSize: 10, fontWeight: 850, color: '#141413', marginBottom: 7 }}>
                  {tDashboard('homeCommandMap.evidenceTitle')}
                </div>
                <div style={{ display: 'grid', gap: 6 }}>
                  {commandMapEvidenceSources.map(source => (
                    <div key={source.key} style={{
                      display: 'grid',
                      gridTemplateColumns: 'minmax(88px, 0.55fr) minmax(0, 1fr)',
                      gap: 8,
                      alignItems: 'center',
                      border: '0.5px solid rgba(20,20,19,0.12)',
                      borderRadius: 7,
                      background: 'rgba(255,255,255,0.62)',
                      padding: '6px 7px',
                    }}>
                      <div style={{ fontSize: 10, fontWeight: 800, color: '#5f5b52', minWidth: 0 }}>{source.label}</div>
                      <div style={{ fontSize: 10, fontWeight: 750, color: '#141413', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{source.value}</div>
                    </div>
                  ))}
                </div>
              </div>
            </aside>
          </div>

          <div style={{ padding: sectionPadding }}>
            <div style={{
              display: 'flex',
              alignItems: compactViewport ? 'flex-start' : 'baseline',
              flexDirection: compactViewport ? 'column' : 'row',
              justifyContent: 'space-between',
              gap: 8,
              marginBottom: 8,
            }}>
              <h2 style={{ margin: 0, fontSize: 14, fontWeight: 850, color: '#141413' }}>
                {tDashboard('automationDelivery.matrix.title')}
              </h2>
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                <a href={`/${locale}/awooop/work-items?project_id=awoooi`} style={{ fontSize: 11, fontWeight: 750, color: '#1f5b9b', textDecoration: 'none' }}>
                  {tDashboard('automationDelivery.openWorkItems')}
                </a>
                <a href={`/${locale}/awooop/runs?project_id=awoooi`} style={{ fontSize: 11, fontWeight: 750, color: '#1f5b9b', textDecoration: 'none' }}>
                  {tDashboard('automationDelivery.openRuns')}
                </a>
              </div>
            </div>
            <div style={{
              display: 'grid',
              gap: 1,
              border: '0.5px solid #e0ddd4',
              borderRadius: 8,
              background: '#e0ddd4',
              overflow: 'hidden',
            }}>
              {!compactViewport && (
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: 'minmax(96px, 0.52fr) minmax(0, 1.42fr) minmax(90px, 0.42fr)',
                  gap: 1,
                  background: '#e0ddd4',
                }}>
                  {[
                    tDashboard('automationDelivery.matrix.columns.group'),
                    tDashboard('automationDelivery.matrix.columns.capability'),
                    tDashboard('automationDelivery.matrix.columns.status'),
                  ].map(label => (
                    <div key={label} style={{
                      background: '#faf9f3',
                      padding: '7px 9px',
                      fontSize: 10,
                      fontWeight: 900,
                      color: '#5f5b52',
                      textTransform: 'uppercase',
                      letterSpacing: 0.35,
                    }}>
                      {label}
                    </div>
                  ))}
                </div>
              )}
              {automationDeliveryMatrixRows.map(item => {
                const tone = automationWorkToneStyle[item.tone]
                return (
                  <a
                    key={`matrix-${item.key}`}
                    href={item.href}
                    style={{
                      display: 'grid',
                      gridTemplateColumns: compactViewport ? '1fr' : 'minmax(96px, 0.52fr) minmax(0, 1.42fr) minmax(90px, 0.42fr)',
                      gap: compactViewport ? 6 : 1,
                      background: compactViewport ? '#fff' : '#e0ddd4',
                      color: 'inherit',
                      textDecoration: 'none',
                    }}
                  >
                    <div style={{
                      background: compactViewport ? tone.bg : '#fff',
                      borderLeft: compactViewport ? `3px solid ${tone.color}` : 'none',
                      padding: compactViewport ? '8px 9px 0' : '8px 9px',
                      minWidth: 0,
                    }}>
                      <span style={{
                        display: 'inline-flex',
                        maxWidth: '100%',
                        border: `0.5px solid ${tone.border}`,
                        background: tone.bg,
                        color: tone.color,
                        borderRadius: 999,
                        padding: '1px 7px',
                        fontSize: 10,
                        fontWeight: 850,
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                      }}>
                        {item.group}
                      </span>
                    </div>
                    <div style={{
                      background: '#fff',
                      padding: compactViewport ? '2px 9px 0' : '8px 9px',
                      minWidth: 0,
                    }}>
                      <div style={{ fontSize: 12, fontWeight: 850, color: '#141413', lineHeight: 1.3, overflowWrap: 'anywhere' }}>
                        {item.title}
                      </div>
                      <div style={{ marginTop: 3, fontSize: 10, lineHeight: 1.45, color: '#5f5b52', overflowWrap: 'anywhere' }}>
                        {item.detail}
                      </div>
                    </div>
                    <div style={{
                      background: '#fff',
                      padding: compactViewport ? '3px 9px 9px' : '8px 9px',
                      minWidth: 0,
                    }}>
                      <span style={{
                        display: 'inline-flex',
                        maxWidth: '100%',
                        border: `0.5px solid ${tone.border}`,
                        background: tone.bg,
                        color: tone.color,
                        borderRadius: 999,
                        padding: '2px 8px',
                        fontSize: 10,
                        fontWeight: 850,
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                      }}>
                        {item.status}
                      </span>
                    </div>
                  </a>
                )
              })}
            </div>
          </div>
        </section>

        <section style={{
          margin: secondarySectionMargin,
          background: '#fff',
          border: '0.5px solid #d8d3c7',
          borderRadius: 10,
          boxShadow: '0 1px 4px rgba(0,0,0,0.05)',
          overflow: 'hidden',
          flexShrink: 0,
        }}>
          <div style={{
            display: 'flex',
            flexDirection: compactViewport ? 'column' : 'row',
            alignItems: 'baseline',
            justifyContent: 'space-between',
            gap: 12,
            padding: compactViewport ? '12px 10px' : '12px 16px',
            borderBottom: '0.5px solid #e0ddd4',
            background: '#faf9f3',
          }}>
            <div>
              <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: 0.5, color: '#77736a', fontWeight: 700 }}>
                {tDashboard('automationDiagrams.eyebrow')}
              </div>
              <h2 style={{ margin: '3px 0 0', fontSize: 16, fontWeight: 800, color: '#141413' }}>
                {tDashboard('automationDiagrams.title')}
              </h2>
            </div>
            <a href={`/${locale}/topology`} style={{ fontSize: 11, fontWeight: 700, color: '#1f5b9b', textDecoration: 'none' }}>
              {tDashboard('automationDiagrams.openTopology')}
            </a>
          </div>
          <div style={{ padding: sectionPadding }}>
            <div style={{
              display: 'grid',
              gap: 1,
              border: '0.5px solid #e0ddd4',
              borderRadius: 8,
              background: '#e0ddd4',
              overflow: 'hidden',
            }}>
              {!compactViewport && (
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: 'minmax(120px, 0.45fr) minmax(0, 1.25fr) minmax(220px, 0.8fr)',
                  gap: 1,
                  background: '#e0ddd4',
                }}>
                  {[
                    tDashboard('automationDiagrams.atlas.columns.standard'),
                    tDashboard('automationDiagrams.atlas.columns.purpose'),
                    tDashboard('automationDiagrams.atlas.columns.preview'),
                  ].map(label => (
                    <div key={label} style={{
                      background: '#faf9f3',
                      padding: '7px 9px',
                      fontSize: 10,
                      fontWeight: 900,
                      color: '#5f5b52',
                      textTransform: 'uppercase',
                      letterSpacing: 0.35,
                    }}>
                      {label}
                    </div>
                  ))}
                </div>
              )}
              {productDiagramCards.map((card) => (
                <a
                  key={card.key}
                  href={card.href}
                  style={{
                    display: 'grid',
                    gridTemplateColumns: compactViewport ? '1fr' : 'minmax(120px, 0.45fr) minmax(0, 1.25fr) minmax(220px, 0.8fr)',
                    gap: compactViewport ? 6 : 1,
                    background: compactViewport ? '#fff' : '#e0ddd4',
                    color: 'inherit',
                    textDecoration: 'none',
                  }}
                >
                  <div style={{
                    background: compactViewport ? '#eef5ff' : '#fff',
                    borderLeft: compactViewport ? '3px solid #1f5b9b' : 'none',
                    padding: compactViewport ? '8px 9px 0' : '8px 9px',
                    minWidth: 0,
                  }}>
                    <span style={{
                      display: 'inline-flex',
                      maxWidth: '100%',
                      border: '0.5px solid #9bb6d9',
                      background: '#eef5ff',
                      color: '#1f5b9b',
                      borderRadius: 999,
                      padding: '1px 7px',
                      fontSize: 10,
                      fontWeight: 850,
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                    }}>
                      {card.standard}
                    </span>
                  </div>
                  <div style={{
                    background: '#fff',
                    padding: compactViewport ? '3px 9px 0' : '8px 9px',
                    minWidth: 0,
                  }}>
                    <div style={{ fontSize: 12, fontWeight: 850, color: '#141413', lineHeight: 1.3, overflowWrap: 'anywhere' }}>
                      {card.title}
                    </div>
                    <div style={{ marginTop: 3, fontSize: 10, lineHeight: 1.45, color: '#5f5b52', overflowWrap: 'anywhere' }}>
                      {card.detail}
                    </div>
                  </div>
                  <div style={{
                    background: '#fff',
                    padding: compactViewport ? '4px 9px 9px' : '8px 9px',
                    minWidth: 0,
                  }}>
                    <div style={{
                      display: 'grid',
                      gridTemplateColumns: compactViewport ? 'repeat(2, minmax(0, 1fr))' : 'repeat(4, minmax(0, 1fr))',
                      gap: 5,
                    }}>
                      {card.nodes.map((node, index) => (
                        <div key={`${card.key}-${node}`} style={{
                          minWidth: 0,
                          border: '0.5px solid #d8d3c7',
                          background: '#fbfaf6',
                          borderRadius: 6,
                          padding: '5px 6px',
                        }}>
                          <div style={{ fontSize: 9, fontWeight: 900, color: '#1f5b9b', fontFamily: "'JetBrains Mono', monospace" }}>
                            {String(index + 1).padStart(2, '0')}
                          </div>
                          <div style={{
                            marginTop: 3,
                            fontSize: 10,
                            fontWeight: 750,
                            lineHeight: 1.25,
                            color: '#2e2b26',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                          }}>
                            {node}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </a>
              ))}
            </div>
          </div>
          <div style={{ borderTop: '0.5px solid #e0ddd4', padding: sectionPadding, background: '#fffdf8' }}>
            <div style={{ marginBottom: 12 }}>
              <div style={{ fontSize: 10, fontWeight: 800, color: '#1f5b9b', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                {tDashboard('automationDiagrams.workspace.eyebrow')}
              </div>
              <h3 style={{ margin: '3px 0 0', fontSize: 15, fontWeight: 800, color: '#141413' }}>
                {tDashboard('automationDiagrams.workspace.title')}
              </h3>
              <p style={{ margin: '5px 0 0', fontSize: 11, lineHeight: 1.55, color: '#5f5b52', maxWidth: 980 }}>
                {tDashboard('automationDiagrams.workspace.subtitle')}
              </p>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: diagramWorkspaceGridTemplate, gap: 12 }}>
              <div style={{ display: 'grid', gap: 12 }}>
                <div style={{
                  border: '0.5px solid #e0ddd4',
                  borderRadius: 8,
                  background: '#fbfaf6',
                  padding: 12,
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'baseline', marginBottom: 10 }}>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 800, color: '#141413' }}>
                        {tDashboard('automationDiagrams.workspace.flow.title')}
                      </div>
                      <div style={{ marginTop: 3, fontSize: 11, color: '#5f5b52', lineHeight: 1.5 }}>
                        {tDashboard('automationDiagrams.workspace.flow.subtitle')}
                      </div>
                    </div>
                  </div>
                  <div style={{
                    display: 'grid',
                    gridTemplateColumns: flowStageGridTemplate,
                    gap: 8,
                  }}>
                    {automationFlowStages.map((stage, index) => {
                      const tone = automationWorkToneStyle[stage.tone]
                      const isSelectedStage = stage.key === selectedBlueprintStage.key
                      return (
                        <a
                          key={stage.key}
                          href={`/${locale}?blueprint_stage=${stage.key}#blueprint-stage-inspector`}
                          onClick={() => setSelectedBlueprintStageKey(stage.key as HomepageBlueprintStageKey)}
                          aria-current={isSelectedStage ? 'step' : undefined}
                          style={{
                            position: 'relative',
                            minHeight: 104,
                            border: `0.5px solid ${isSelectedStage ? tone.color : tone.border}`,
                            borderRadius: 8,
                            background: tone.bg,
                            padding: '9px 10px',
                            color: 'inherit',
                            cursor: 'pointer',
                            textAlign: 'left',
                            font: 'inherit',
                            textDecoration: 'none',
                            boxShadow: isSelectedStage ? `inset 0 0 0 1px ${tone.color}` : 'none',
                          }}
                        >
                          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                            <div style={{
                              width: 22,
                              height: 22,
                              borderRadius: 999,
                              border: `0.5px solid ${tone.border}`,
                              background: '#fff',
                              color: tone.color,
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              fontSize: 10,
                              fontWeight: 800,
                            }}>
                              {index + 1}
                            </div>
                            <span style={{ fontSize: 10, fontWeight: 800, color: tone.color, whiteSpace: 'nowrap' }}>
                              {stage.status}
                            </span>
                          </div>
                          <div style={{ marginTop: 8, fontSize: 12, fontWeight: 800, color: '#141413', lineHeight: 1.3 }}>
                            {stage.title}
                          </div>
                          <div style={{ marginTop: 5, fontSize: 10, color: '#5f5b52', lineHeight: 1.45, overflowWrap: 'anywhere' }}>
                            {stage.detail}
                          </div>
                          <div style={{
                            marginTop: 7,
                            borderTop: `0.5px solid ${tone.border}`,
                            paddingTop: 6,
                            fontSize: 9,
                            fontWeight: 800,
                            color: tone.color,
                            lineHeight: 1.35,
                            overflowWrap: 'anywhere',
                          }}>
                            {stage.liveEvidence.metric}
                          </div>
                        </a>
                      )
                    })}
                  </div>
                  <div style={{
                    scrollMarginTop: 96,
                    marginTop: 10,
                    borderTop: '0.5px solid #e0ddd4',
                    paddingTop: 10,
                    display: 'grid',
                    gridTemplateColumns: compactViewport ? '1fr' : 'minmax(160px, 0.75fr) minmax(0, 1fr)',
                    gap: 10,
                  }}
                    id="blueprint-stage-inspector"
                  >
                    <div style={{
                      border: `0.5px solid ${selectedBlueprintTone.border}`,
                      background: selectedBlueprintTone.bg,
                      borderRadius: 8,
                      padding: '9px 10px',
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <div style={{
                          width: 24,
                          height: 24,
                          borderRadius: 999,
                          border: `0.5px solid ${selectedBlueprintTone.border}`,
                          background: '#fff',
                          color: selectedBlueprintTone.color,
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          fontSize: 10,
                          fontWeight: 800,
                        }}>
                          {selectedBlueprintStageIndex + 1}
                        </div>
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontSize: 10, fontWeight: 800, color: '#77736a', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                            {tDashboard('automationDiagrams.workspace.inspector.title')}
                          </div>
                          <div style={{ marginTop: 2, fontSize: 13, fontWeight: 800, color: '#141413', lineHeight: 1.25 }}>
                            {selectedBlueprintStage.title}
                          </div>
                        </div>
                      </div>
                      <div style={{ marginTop: 8, fontSize: 11, color: '#5f5b52', lineHeight: 1.45 }}>
                        {selectedBlueprintStage.detail}
                      </div>
                      <a
                        href={selectedBlueprintStage.href}
                        style={{
                          display: 'inline-flex',
                          marginTop: 9,
                          border: `0.5px solid ${selectedBlueprintTone.border}`,
                          background: '#fff',
                          color: selectedBlueprintTone.color,
                          borderRadius: 6,
                          padding: '5px 8px',
                          fontSize: 10,
                          fontWeight: 800,
                          textDecoration: 'none',
                        }}
                      >
                        {tDashboard('automationDiagrams.workspace.inspector.openTarget')}
                      </a>
                    </div>
                    <div style={{
                      display: 'grid',
                      gridTemplateColumns: compactViewport ? '1fr' : 'repeat(auto-fit, minmax(190px, 1fr))',
                      gap: 8,
                    }}>
                      {[
                        [tDashboard('automationDiagrams.workspace.inspector.fields.owner'), selectedBlueprintStage.owner],
                        [tDashboard('automationDiagrams.workspace.inspector.fields.evidence'), selectedBlueprintStage.evidence],
                        [tDashboard('automationDiagrams.workspace.inspector.fields.nextAction'), selectedBlueprintStage.nextAction],
                      ].map(([label, value]) => (
                        <div key={label} style={{
                          border: '0.5px solid #e0ddd4',
                          borderRadius: 7,
                          background: '#fff',
                          padding: '8px 9px',
                        }}>
                          <div style={{ fontSize: 9, fontWeight: 800, color: '#77736a', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                            {label}
                          </div>
                          <div style={{ marginTop: 5, fontSize: 11, fontWeight: 700, color: '#2e2b26', lineHeight: 1.45, overflowWrap: 'anywhere' }}>
                            {value}
                          </div>
                        </div>
                      ))}
                    </div>
                    <div style={{
                      gridColumn: compactViewport ? 'auto' : '1 / -1',
                      border: `0.5px solid ${selectedBlueprintTone.border}`,
                      borderRadius: 8,
                      background: '#fff',
                      padding: '9px 10px',
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap' }}>
                        <div style={{ fontSize: 10, fontWeight: 800, color: '#77736a', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                          {tDashboard('automationDiagrams.workspace.liveEvidence.title')}
                        </div>
                        <span style={{
                          border: `0.5px solid ${selectedBlueprintTone.border}`,
                          background: selectedBlueprintTone.bg,
                          color: selectedBlueprintTone.color,
                          borderRadius: 999,
                          padding: '2px 7px',
                          fontSize: 9,
                          fontWeight: 800,
                        }}>
                          {selectedBlueprintStage.liveEvidence.updated}
                        </span>
                      </div>
                      <div style={{
                        marginTop: 8,
                        display: 'grid',
                        gridTemplateColumns: compactViewport ? '1fr' : 'repeat(auto-fit, minmax(170px, 1fr))',
                        gap: 8,
                      }}>
                        {[
                          [tDashboard('automationDiagrams.workspace.liveEvidence.fields.metric'), selectedBlueprintStage.liveEvidence.metric],
                          [tDashboard('automationDiagrams.workspace.liveEvidence.fields.detail'), selectedBlueprintStage.liveEvidence.detail],
                          [tDashboard('automationDiagrams.workspace.liveEvidence.fields.source'), selectedBlueprintStage.liveEvidence.source],
                        ].map(([label, value]) => (
                          <div key={label} style={{
                            border: '0.5px solid #e0ddd4',
                            borderRadius: 7,
                            background: '#fbfaf6',
                            padding: '8px 9px',
                          }}>
                            <div style={{ fontSize: 9, fontWeight: 800, color: '#77736a', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                              {label}
                            </div>
                            <div style={{ marginTop: 5, fontSize: 11, fontWeight: 700, color: '#2e2b26', lineHeight: 1.45, overflowWrap: 'anywhere' }}>
                              {value}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                </div>

                <div style={{
                  border: '0.5px solid #e0ddd4',
                  borderRadius: 8,
                  background: '#fbfaf6',
                  padding: 12,
                }}>
                  <div style={{ fontSize: 13, fontWeight: 800, color: '#141413' }}>
                    {tDashboard('automationDiagrams.workspace.topology.title')}
                  </div>
                  <div style={{ marginTop: 3, fontSize: 11, color: '#5f5b52', lineHeight: 1.5 }}>
                    {tDashboard('automationDiagrams.workspace.topology.subtitle')}
                  </div>
                  <div style={{ marginTop: 10, display: 'grid', gridTemplateColumns: topologyGridTemplate, gap: 8 }}>
                    {runtimeTopologyLayers.map((layer) => (
                      <div key={layer.key} style={{
                        border: '0.5px solid #d8d3c7',
                        borderRadius: 8,
                        background: '#fff',
                        padding: 9,
                      }}>
                        <div style={{ fontSize: 11, fontWeight: 800, color: '#1f5b9b', marginBottom: 7 }}>
                          {layer.title}
                        </div>
                        <div style={{ display: 'grid', gap: 5 }}>
                          {layer.items.map((item) => (
                            <div key={`${layer.key}-${item}`} style={{
                              border: '0.5px solid #e0ddd4',
                              borderRadius: 6,
                              background: '#fbfaf6',
                              padding: '5px 7px',
                              fontSize: 10,
                              fontWeight: 700,
                              color: '#2e2b26',
                              lineHeight: 1.35,
                              overflowWrap: 'anywhere',
                            }}>
                              {item}
                            </div>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              <div style={{ display: 'grid', gap: 12 }}>
                <div style={{
                  border: '0.5px solid #e0ddd4',
                  borderRadius: 8,
                  background: '#fbfaf6',
                  padding: 12,
                }}>
                  <div style={{ fontSize: 13, fontWeight: 800, color: '#141413' }}>
                    {tDashboard('automationDiagrams.workspace.decision.title')}
                  </div>
                  <div style={{ marginTop: 3, fontSize: 11, color: '#5f5b52', lineHeight: 1.5 }}>
                    {tDashboard('automationDiagrams.workspace.decision.subtitle')}
                  </div>
                  <div style={{ marginTop: 10, display: 'grid', gap: 6 }}>
                    <div style={{ display: 'grid', gridTemplateColumns: decisionGridTemplate, gap: 6, fontSize: 9, fontWeight: 800, color: '#77736a', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                      <div>{tDashboard('automationDiagrams.workspace.decision.headers.signal')}</div>
                      <div>{tDashboard('automationDiagrams.workspace.decision.headers.value')}</div>
                      <div>{tDashboard('automationDiagrams.workspace.decision.headers.outcome')}</div>
                    </div>
                    {decisionRows.map((row) => {
                      const tone = automationWorkToneStyle[row.tone]
                      return (
                        <div key={row.key} style={{
                          display: 'grid',
                          gridTemplateColumns: decisionGridTemplate,
                          gap: 6,
                          alignItems: 'stretch',
                          fontSize: 10,
                        }}>
                          <div style={{ border: '0.5px solid #e0ddd4', background: '#fff', borderRadius: 6, padding: '6px 7px', fontWeight: 800, color: '#141413' }}>
                            {row.signal}
                          </div>
                          <div style={{ border: '0.5px solid #e0ddd4', background: '#fff', borderRadius: 6, padding: '6px 7px', color: '#5f5b52', overflowWrap: 'anywhere' }}>
                            {row.value}
                          </div>
                          <div style={{ border: `0.5px solid ${tone.border}`, background: tone.bg, borderRadius: 6, padding: '6px 7px', color: tone.color, fontWeight: 800, overflowWrap: 'anywhere' }}>
                            {row.outcome}
                          </div>
                        </div>
                      )
                    })}
                  </div>
                </div>

                <div style={{
                  border: '0.5px solid #e0ddd4',
                  borderRadius: 8,
                  background: '#fbfaf6',
                  padding: 12,
                }}>
                  <div style={{ fontSize: 13, fontWeight: 800, color: '#141413' }}>
                    {tDashboard('automationDiagrams.workspace.lineage.title')}
                  </div>
                  <div style={{ marginTop: 3, fontSize: 11, color: '#5f5b52', lineHeight: 1.5 }}>
                    {tDashboard('automationDiagrams.workspace.lineage.subtitle')}
                  </div>
                  <div style={{ marginTop: 10, display: 'grid', gap: 7 }}>
                    {lineageNodes.map((node, index) => (
                      <div key={node} style={{ display: 'grid', gridTemplateColumns: '24px 1fr', gap: 8, alignItems: 'center' }}>
                        <div style={{
                          width: 24,
                          height: 24,
                          borderRadius: 999,
                          border: '0.5px solid #9bb6d9',
                          background: '#eef5ff',
                          color: '#1f5b9b',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          fontSize: 10,
                          fontWeight: 800,
                        }}>
                          {index + 1}
                        </div>
                        <div style={{
                          border: '0.5px solid #d8d3c7',
                          background: '#fff',
                          borderRadius: 7,
                          padding: '7px 9px',
                          fontSize: 11,
                          fontWeight: 800,
                          color: '#2e2b26',
                        }}>
                          {node}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* ── KPI Strip (5 卡片 — Sprint 5R 設計稿) ──────────────────────── */}
        <div style={{ display: 'grid', gridTemplateColumns: compactViewport ? '1fr' : 'repeat(5, minmax(0, 1fr))', gap: compactViewport ? 8 : 12, padding: compactViewport ? '10px 8px' : '10px 20px', flexShrink: 0 }}>
          {/* 系統健康 */}
          <div style={{ flex: 1, background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 8, padding: '8px 12px' }}>
            <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.5px', color: '#87867f', fontWeight: 500 }}>{tDashboard('serviceHealth')}</div>
            <div style={{ fontSize: 22, fontWeight: 700, color: '#22C55E', marginTop: 2 }}>
              {totalServices > 0 ? `${Math.round((healthyServices / totalServices) * 100)}%` : '--'}
            </div>
            {totalServices > 0 && (
              <div style={{ height: 3, borderRadius: 2, background: '#ebe8df', marginTop: 4, overflow: 'hidden' }}>
                <div style={{ width: `${systemHealthPct}%`, height: '100%', borderRadius: 2, background: '#22C55E' }} />
              </div>
            )}
          </div>
          {/* 活動事件 */}
          <div style={{ flex: 1, background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 8, padding: '8px 12px' }}>
            <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.5px', color: '#87867f', fontWeight: 500 }}>{tDashboard('unresolvedIncidents')}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 2 }}>
              <span style={{ fontSize: 22, fontWeight: 700, color: incidentCount > 0 ? '#d97757' : '#141413' }}>{incidentCount || '--'}</span>
              {incidentCount > 0 && (
                <span style={{ fontSize: 9, color: '#87867f' }}>
                  {tDashboard('severityBreakdown', { p1: p1Count, p2: p2Count })}
                </span>
              )}
            </div>
            {visibleIncidents.length > 0 && (
              <div style={{ marginTop: 4, fontSize: 9, color: '#87867f' }}>
                {tDashboard('latestIncidentWindow', { shown: visibleIncidents.length })}
              </div>
            )}
          </div>
          {/* 自動修復率 */}
          <div style={{ flex: 1, background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 8, padding: '8px 12px' }}>
            <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.5px', color: '#87867f', fontWeight: 500 }}>{tDashboard('autoRepairVerified24h')}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 2 }}>
              <span style={{ fontSize: 22, fontWeight: 700, color: autoRemediationTone }}>{autoRemediationRate}</span>
              {autoRemediationDetail && <span style={{ fontSize: 10, fontWeight: 700, color: autoRemediationTone }}>{autoRemediationDetail}</span>}
            </div>
            <div style={{ height: 3, borderRadius: 2, background: '#ebe8df', marginTop: 4, overflow: 'hidden' }}>
              <div style={{ width: `${autoRemediationPct}%`, height: '100%', borderRadius: 2, background: autoRemediationTone }} />
            </div>
          </div>
          {/* 待審批 */}
          <div style={{ flex: 1, background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 8, padding: '8px 12px' }}>
            <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.5px', color: '#87867f', fontWeight: 500 }}>{tDashboard('pendingApprovals')}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 2 }}>
              <span style={{ fontSize: 22, fontWeight: 700, color: hasPendingApprovals ? '#F59E0B' : '#141413' }}>{pendingApprovals ?? '--'}</span>
              {hasPendingApprovals && <span style={{ fontSize: 9, color: '#F59E0B' }}>{tDashboard('awaitingConfirm')}</span>}
            </div>
          </div>
          {/* 本週操作 */}
          <div style={{ flex: 1, background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 8, padding: '8px 12px' }}>
            <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.5px', color: '#87867f', fontWeight: 500 }}>{tDashboard('operations24h')}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 2 }}>
              <span style={{ fontSize: 22, fontWeight: 700, color: '#141413' }}>
                {auditStats?.last_24h_count != null ? auditStats.last_24h_count.toLocaleString() : '--'}
              </span>
              {auditStats?.total_executions != null && (
                <span style={{ fontSize: 9, color: '#87867f' }}>
                  {tDashboard('operationsTotal', { total: auditStats.total_executions.toLocaleString() })}
                </span>
              )}
            </div>
          </div>
        </div>

        {/* ── 主體 2 欄 ─────────────────────────────────────────────────────── */}
        <div style={{ display: 'flex', flexDirection: compactViewport ? 'column' : 'row', flex: '0 0 auto', overflow: 'visible', padding: compactViewport ? '10px 8px' : '14px 20px', gap: compactViewport ? 12 : 20, background: '#f5f4ed' }}>

          {/* ── 左欄 (60%): 活躍事件 + 處置統計 + 最近活動 ─────────────── */}
          <div style={{
            flex: compactViewport ? 'none' : 6, minWidth: 0, overflowY: 'visible',
            display: 'flex', flexDirection: 'column', gap: 14,
            paddingBottom: 40,
          }}>

            {/* 活躍事件 */}
            <div style={{
              background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 10,
              overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.04)', flexShrink: 0,
            }}>
              <div style={{
                padding: '10px 14px', borderBottom: '0.5px solid #e0ddd4',
                display: 'flex', alignItems: 'center', gap: 8, background: '#faf9f3',
              }}>
                <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#d97757', flexShrink: 0 }} />
                <span style={{ fontSize: 14, fontWeight: 700, color: '#141413', letterSpacing: '0.5px' }}>
                  {tDashboard('unresolvedIncidents')}
                </span>
                {(incidents?.length ?? 0) > 0 && (
                  <span style={{
                    fontSize: 12, background: 'rgba(217,119,87,0.1)', color: '#a04010',
                    padding: '2px 8px', fontWeight: 700,
                    border: '0.5px solid rgba(217,119,87,0.25)', borderRadius: 10,
                  }}>
                    {incidents?.length}
                  </span>
                )}
                {requestedIncidentIds.length > 0 && (
                  <span style={{
                    fontSize: 11,
                    color: truthChainCoveredCount === requestedIncidentIds.length && !isStatusChainsLoading ? '#17602a' : '#8a5a08',
                    background: truthChainCoveredCount === requestedIncidentIds.length && !isStatusChainsLoading ? '#f0faf2' : '#fff7e8',
                    border: '0.5px solid #e0ddd4',
                    padding: '2px 7px',
                    borderRadius: 10,
                    fontWeight: 700,
                  }}>
                    {truthChainCoverageLabel}
                  </span>
                )}
                <a
                  href={`/${locale}/alerts`}
                  style={{ marginLeft: 'auto', fontSize: 11, color: '#4A90D9', cursor: 'pointer', fontWeight: 500, textDecoration: 'none' }}
                >
                  {tDashboard('viewAllAlerts')}
                </a>
              </div>

              <div style={{ padding: '14px' }}>
                {isIncidentsLoading ? (
                  <PulseSkeleton count={3} height={12} />
                ) : incidentsError ? (
                  <div style={{ padding: 16, fontSize: 13, color: '#cc2200' }}>{incidentsError}</div>
                ) : (incidents?.length ?? 0) === 0 ? (
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 48, gap: 8 }}>
                    <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#22C55E' }} />
                    <span style={{ fontSize: 13, color: '#87867f' }}>
                      {tDashboard('stableUnresolved', {
                        stable: tDashboard('stable'),
                        label: tDashboard('unresolvedIncidents'),
                      })}
                    </span>
                  </div>
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                    {visibleIncidents.map((incident) => (
                      <IncidentCard
                        key={incident.incident_id}
                        incident={incident}
                        decision={incident.decision}
                        statusChain={statusChains[incident.incident_id] ?? null}
                      />
                    ))}
                    {hiddenIncidentCount > 0 && (
                      <a
                        href={`/${locale}/alerts`}
                        style={{
                          padding: '9px 12px',
                          border: '0.5px solid #e0ddd4',
                          borderRadius: 8,
                          background: '#fbfaf6',
                          color: '#4A90D9',
                          fontSize: 12,
                          fontWeight: 600,
                          textAlign: 'center',
                          textDecoration: 'none',
                        }}
                      >
                        {tDashboard('showingLatestIncidents', { shown: visibleIncidents.length, total: incidentCount })}
                      </a>
                    )}
                  </div>
                )}
              </div>
            </div>

            {/* 處置統計迷你版 (S4) */}
            <DispositionMini />

            {/* 最近活動 (S5) */}
            <RecentActivity />

          </div>

          {/* ── 右欄 (40%): OpenClaw + 基礎架構 + 監控工具 ─────────────── */}
          <div style={{
            flex: compactViewport ? 'none' : 4, minWidth: 0,
            overflowY: 'visible',
            display: 'flex',
            flexDirection: 'column',
            gap: 14,
            paddingBottom: 40,
          }}>

            {/* WoooClaw + Reasoning Stream */}
            <div style={{
              background: '#fff',
              border: '0.5px solid #e0ddd4',
              borderRadius: 12,
              overflow: 'hidden',
              boxShadow: '0 1px 4px rgba(0,0,0,0.05)',
              flexShrink: 0,
            }}>
              <div style={{
                padding: '10px 14px',
                borderBottom: '0.5px solid #e0ddd4',
                fontSize: 14, fontWeight: 700, color: '#141413',
                letterSpacing: '0.5px',
                fontFamily: 'var(--font-body), monospace', background: '#faf9f3',
                display: 'flex', alignItems: 'center', gap: 8,
              }}>
                <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#d97757', flexShrink: 0 }} />
                {tDashboard('openclawEngine')}
              </div>
              <OpenClawPanel
                status={(incidents?.length ?? 0) > 0 ? 'analyzing' : 'patrolling'}
              />
            </div>

            {/* 待審批任務 (S7) */}
            <PendingApprovalsCard />

            {/* AI 自動化證據鏈：來源、重複、MCP、修復、人工缺口 */}
            <AutomationEvidenceCard />

            {/* 飛輪健康度 KPI (ADR-073-C C2) */}
            <FlywheelKPICard />

            {/* 基礎架構 — Toggle: 拓撲圖 / 主機網格 */}
            <div style={{
              background: '#fff',
              border: '0.5px solid #e0ddd4',
              borderRadius: 12,
              overflow: 'hidden',
              boxShadow: '0 1px 4px rgba(0,0,0,0.05)',
              flexShrink: 0,
            }}>
              <div style={{
                padding: '10px 14px',
                borderBottom: '0.5px solid #e0ddd4',
                fontSize: 14, fontWeight: 700, color: '#141413',
                letterSpacing: '0.5px',
                fontFamily: 'var(--font-body), monospace', background: '#faf9f3',
                display: 'flex', alignItems: 'center', gap: 8,
                flexShrink: 0,
              }}>
                <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#d97757', flexShrink: 0 }} />
                {tDashboard('infrastructure')}
                {/* Toggle 切換 */}
                <div style={{ marginLeft: 'auto', display: 'flex', background: '#f5f4ed', borderRadius: 5, padding: 2 }}>
                  <button
                    onClick={() => setInfraView('host')}
                    style={{
                      padding: '3px 10px', borderRadius: 3, fontSize: 10, fontWeight: infraView === 'host' ? 600 : 400,
                      cursor: 'pointer', border: 'none',
                      background: infraView === 'host' ? '#fff' : 'transparent',
                      color: infraView === 'host' ? '#d97757' : '#87867f',
                      boxShadow: infraView === 'host' ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
                    }}
                  >{tDashboard('hostView')}</button>
                  <button
                    onClick={() => setInfraView('topo')}
                    style={{
                      padding: '3px 10px', borderRadius: 3, fontSize: 10, fontWeight: infraView === 'topo' ? 600 : 400,
                      cursor: 'pointer', border: 'none',
                      background: infraView === 'topo' ? '#fff' : 'transparent',
                      color: infraView === 'topo' ? '#d97757' : '#87867f',
                      boxShadow: infraView === 'topo' ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
                    }}
                  >{tDashboard('topoView')}</button>
                </div>
              </div>
              {/* 拓撲群組 2×2 (設計稿 L514-519) */}
              {infraView === 'topo' && (
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, padding: 14 }}>
                  {liveTopologyGroups.length === 0 ? (
                    <div style={{ gridColumn: '1 / -1', padding: 18, textAlign: 'center', color: '#87867f', fontSize: 12 }}>
                      {tDashboard('waitingHostData')}
                    </div>
                  ) : liveTopologyGroups.map(g => {
                    const accent = roleAccent(g.role)
                    const isHealthy = g.serviceCount > 0 && g.healthyServices === g.serviceCount
                    const statusLabel = isHealthy ? tTopo('healthy') : tTopo('warning')
                    return (
                      <div key={g.role} style={{
                        border: `0.5px solid ${accent.border}`, borderRadius: 8, padding: '8px 10px',
                        background: accent.bg, transition: 'all 0.12s',
                        ...(!isHealthy ? { boxShadow: '0 0 8px rgba(245,158,11,0.15)' } : {}),
                      }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
                          <span style={{ width: 5, height: 5, borderRadius: '50%', background: isHealthy ? '#22C55E' : '#F59E0B', flexShrink: 0 }} />
                          <div style={{ fontSize: 12, fontWeight: 600 }}>{tTopo(roleLabelKey(g.role) as never)}</div>
                        </div>
                        <div style={{ fontSize: 10, color: '#555550' }}>
                          {g.hosts.length} {tDashboard('hostsLabel')} · {g.healthyServices}/{g.serviceCount} {tTopo('services')} · {statusLabel}
                        </div>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 2, marginTop: 4 }}>
                          {g.serviceNames.map(s => (
                            <span key={s} style={{
                              display: 'flex', alignItems: 'center', gap: 3,
                              padding: '2px 7px', background: '#fff', border: '0.5px solid #e0ddd4',
                              borderRadius: 4, fontSize: 10,
                            }}>
                              <span style={{ width: 3, height: 3, borderRadius: '50%', background: accent.accent }} />
                              {s}
                            </span>
                          ))}
                        </div>
                      </div>
                    )
                  })}
                </div>
              )}
              {/* 主機網格 2×2 (設計稿 L522-527) */}
              {infraView === 'host' && (
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, padding: 14 }}>
                  {hosts.length === 0 ? (
                    <div style={{ gridColumn: '1 / -1', padding: 18, textAlign: 'center', color: '#87867f', fontSize: 12 }}>
                      {tDashboard('waitingHostData')}
                    </div>
                  ) : hosts.map(h => {
                    const cpu = h.metrics?.cpu_percent ?? null
                    const ram = h.metrics?.memory_percent ?? null
                    const isSelected = selectedHost?.ip === h.ip
                    const serviceTotal = h.services.length
                    const serviceHealthy = h.services.filter(service => isHealthyService(service.status)).length
                    return (
                      <div
                        key={h.ip}
                        onClick={() => setSelectedHost(isSelected ? null : h)}
                        style={{
                          border: `0.5px solid ${isSelected ? '#4A90D9' : '#e0ddd4'}`,
                          borderRadius: 8, padding: '8px 10px',
                          background: isSelected ? 'rgba(74,144,217,0.05)' : '#faf9f3',
                          cursor: 'pointer', transition: 'all 0.15s',
                        }}
                      >
                        <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 2 }}>{h.name}</div>
                        <div style={{ fontSize: 10, color: '#555550', fontFamily: "'JetBrains Mono', monospace" }}>{h.ip}</div>
                        <div style={{ fontSize: 9, color: '#87867f', marginTop: 3 }}>
                          {serviceHealthy}/{serviceTotal} {tTopo('services')} · {h.status}
                        </div>
                        <div style={{ display: 'flex', gap: 6, marginTop: 5 }}>
                          {[tTopo('cpu'), tTopo('ram')].map((label, idx) => {
                            const val = idx === 0 ? cpu : ram
                            const color = metricColor(val)
                            return (
                              <div key={label} style={{ flex: 1 }}>
                                <div style={{ fontSize: 7, color: '#87867f', display: 'flex', justifyContent: 'space-between', marginBottom: 2 }}>
                                  <span>{label}</span><span>{metricText(val)}</span>
                                </div>
                                <div style={{ height: 3, borderRadius: 2, background: '#ebe8df', overflow: 'hidden' }}>
                                  <div style={{ width: val != null ? `${val}%` : '0%', height: '100%', borderRadius: 2, background: color }} />
                                </div>
                              </div>
                            )
                          })}
                        </div>
                      </div>
                    )
                  })}
                </div>
              )}

              {/* 主機詳情抽屜 — 點擊主機卡滑入 */}
              {infraView === 'host' && selectedHost && (() => {
                const sh = selectedHost
                const relatedIncidents = incidents.filter(inc => incidentMatchesHost(inc, sh)).slice(0, 3)
                return (
                  <div style={{
                    margin: '0 14px 14px',
                    border: '0.5px solid #4A90D9',
                    borderRadius: 10,
                    overflow: 'hidden',
                    background: '#fff',
                    animation: 'slideDown 0.2s ease',
                  }}>
                    {/* 標頭 */}
                    <div style={{ background: 'rgba(74,144,217,0.06)', borderBottom: '0.5px solid #dbeafe', padding: '10px 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 700, color: '#141413' }}>{sh.name}</div>
                        <div style={{ fontSize: 10, color: '#87867f', fontFamily: "'JetBrains Mono', monospace" }}>{sh.ip}</div>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        {sh.status && (
                          <span style={{ fontSize: 10, background: sh.status === 'healthy' ? 'rgba(34,197,94,0.12)' : 'rgba(204,34,0,0.1)', color: sh.status === 'healthy' ? '#22C55E' : '#cc2200', borderRadius: 4, padding: '2px 8px', fontWeight: 600 }}>
                            {sh.status}
                          </span>
                        )}
                        <button onClick={() => setSelectedHost(null)} style={{ border: 'none', background: 'none', cursor: 'pointer', fontSize: 14, color: '#87867f', padding: '0 2px' }}>✕</button>
                      </div>
                    </div>

                    <div style={{ padding: '12px 14px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                      {/* 左：Metrics 大字 + 服務清單 */}
                      <div>
                        <div style={{ display: 'flex', gap: 12, marginBottom: 10 }}>
                          {[{ label: tTopo('cpu'), val: sh.metrics?.cpu_percent ?? null }, { label: tTopo('ram'), val: sh.metrics?.memory_percent ?? null }].map(m => {
                            const color = metricColor(m.val)
                            return (
                              <div key={m.label} style={{ flex: 1, border: '0.5px solid #e0ddd4', borderRadius: 8, padding: '8px 10px', textAlign: 'center' }}>
                                <div style={{ fontSize: 9, color: '#87867f', fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5 }}>{m.label}</div>
                                <div style={{ fontSize: 24, fontWeight: 700, color, marginTop: 2 }}>{metricText(m.val)}</div>
                              </div>
                            )
                          })}
                        </div>
                        {/* 服務清單 */}
                        <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', color: '#87867f', marginBottom: 5 }}>{tTopo('services')}</div>
                        {sh.services.length === 0 ? (
                          <div style={{ fontSize: 11, color: '#b0ad9f' }}>--</div>
                        ) : sh.services.map((svc, i) => (
                          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '3px 0', borderBottom: '0.5px solid #f5f4ed', fontSize: 11 }}>
                            <div style={{ width: 5, height: 5, borderRadius: '50%', background: isHealthyService(svc.status) ? '#22C55E' : '#cc2200', flexShrink: 0 }} />
                            <span style={{ flex: 1, color: '#141413' }}>{svc.name}</span>
                            {svc.port && <span style={{ color: '#87867f', fontFamily: "'JetBrains Mono', monospace", fontSize: 10 }}>:{svc.port}</span>}
                            {svc.latency_ms != null && <span style={{ color: '#87867f', fontSize: 10 }}>{svc.latency_ms}ms</span>}
                          </div>
                        ))}
                      </div>

                      {/* 右：相關事件 */}
                      <div>
                        <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', color: '#87867f', marginBottom: 5 }}>{tDashboard('relatedIncidents')}</div>
                        {relatedIncidents.length === 0 ? (
                          <div style={{ fontSize: 11, color: '#b0ad9f' }}>{tDashboard('noRelatedIncidents')}</div>
                        ) : relatedIncidents.map((inc, i) => (
                          <div key={i} style={{ padding: '5px 8px', marginBottom: 4, borderRadius: 5, background: '#faf9f3', border: '0.5px solid #e0ddd4' }}>
                            <div style={{ fontSize: 10, fontWeight: 600, color: '#d97757', marginBottom: 2 }}>{inc.severity}</div>
                            <div style={{ fontSize: 11, color: '#141413', lineHeight: 1.3, fontFamily: "'JetBrains Mono', monospace" }}>{inc.incident_id}</div>
                            <div style={{ fontSize: 10, color: '#87867f', marginTop: 2 }}>{inc.status} · {inc.affected_services?.slice(0,2).join(', ') ?? '--'}</div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                )
              })()}
            </div>

            {/* 監控工具 — figma-v2 style: 左彩色條 + 可點擊 + meta行 */}
            <div style={{
              background: '#fff',
              border: '0.5px solid #e0ddd4',
              borderRadius: 12,
              overflow: 'hidden',
              boxShadow: '0 1px 4px rgba(0,0,0,0.05)',
              flexShrink: 0,
            }}>
              <div style={{
                padding: '10px 14px',
                borderBottom: '0.5px solid #e0ddd4',
                fontSize: 14, fontWeight: 700, color: '#141413',
                letterSpacing: '0.5px',
                fontFamily: 'var(--font-body), monospace', background: '#faf9f3',
                display: 'flex', alignItems: 'center', gap: 8,
              }}>
                <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#d97757', flexShrink: 0 }} />
                {tDashboard('monitoringTools')}
              </div>
              <MonitoringTools />
            </div>

            {/* AI 模型狀態 (S9) */}
            <AIModelStatus />

          </div>
        </div>
      </div>
      )}
    </AppLayout>
  )
}
