'use client'

/**
 * AgentMarketTab — AI Agent 市場治理 Tab
 * =====================================
 * 消費：GET /api/v1/agents/market-governance-snapshot
 *
 * 只讀最新 committed governance snapshot；不提供任何批准或執行操作。
 */

import { useEffect, useState } from 'react'
import { AlertTriangle, Ban, CalendarClock, CheckCircle2, ListChecks, Lock, RefreshCw, ShieldCheck } from 'lucide-react'
import { useTranslations } from 'next-intl'
import { GlassCard } from '@/components/ui/glass-card'
import { StatusOrb } from '@/components/ui/status-orb'
import { AgentActivityConstellation } from '@/components/governance/agent-activity-constellation'
import {
  apiClient,
  type AgentMarketGovernanceSnapshot,
  type AiAgentReportLiveDeliveryApprovalPackageSnapshot,
  type AiAgentRuntimeReadbackFixtureApprovalSnapshot,
  type AiTechnologyRadarReadback,
  type AiTechnologyReportCadenceReadback,
} from '@/lib/api-client'

// =============================================================================
// Helpers
// =============================================================================

type AgentWorkloadReport = AiTechnologyReportCadenceReadback['agent_workload_reports'][number]
type DeliveryApprovalPacket = AiAgentReportLiveDeliveryApprovalPackageSnapshot['delivery_approval_packets'][number]
type RuntimeFixtureApprovalCard = AiAgentRuntimeReadbackFixtureApprovalSnapshot['fixture_approval_cards'][number]
type ReportCadence = AiTechnologyReportCadenceReadback['report_cadences'][number]
type ProfessionalEvidenceLabels = {
  role: string
  output: string
  next: string
  deliveryOwnership: string
  fixtureOwnership: string
  blockedActions: string
  evidence: string
  safetyBoundary: string
  noRuntimeOwnership: string
}
type ProfessionalJudgmentLabels = {
  lane: string
  question: string
  evidencePoints: string
  riskTier: string
  allowedNext: string
  blockedBoundary: string
  escalation: string
  readOnlyReady: string
  ownerGate: string
  reportOwnership: string
}
type ProfessionalJudgmentPreset = {
  lane: string
  question: string
  escalation: string
}
type TechnologyReviewLabels = {
  nextGate: string
  reviewNeeds: string
  cost: string
  dependency: string
  security: string
  awoooiGate: string
  agentAssignment: string
}

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

function formatPercent(value: number): string {
  return `${value.toFixed(1)}%`
}

const TECHNOLOGY_AREA_LABELS: Record<string, string> = {
  agent_frameworks: 'Agent 框架',
  evaluation_and_observability: '評測 / 可觀測性',
  mcp_and_a2a: 'MCP / A2A',
  model_providers: '模型 Provider',
  model_serving: '模型服務',
  rag_and_vector: 'RAG / 向量',
}

function formatTechnologyArea(value: string): string {
  return TECHNOLOGY_AREA_LABELS[value] ?? value.replace(/_/g, ' ')
}

function formatSourceHost(value: string): string {
  try {
    return new URL(value).hostname.replace(/^www\./, '')
  } catch {
    return value
  }
}

function normalizeAgentName(value: string): string {
  const normalized = value.toLowerCase()
  if (normalized.includes('openclaw')) return 'openclaw'
  if (normalized.includes('hermes')) return 'hermes'
  if (normalized.includes('nemotron')) return 'nemotron'
  if (normalized.includes('market')) return 'marketradar'
  if (normalized.includes('critic') || normalized.includes('reviewer')) return 'critic'
  return normalized.replace(/[^a-z0-9]+/g, '')
}

function belongsToAgent(ownerAgent: string, workloadAgent: string): boolean {
  return ownerAgent === normalizeAgentName(workloadAgent)
}

function getAgentJudgmentPresetKey(agent: string): 'openclaw' | 'hermes' | 'nemotron' | 'marketradar' | 'reviewer' {
  const normalized = normalizeAgentName(agent)
  if (normalized === 'openclaw') return 'openclaw'
  if (normalized === 'hermes') return 'hermes'
  if (normalized === 'nemotron') return 'nemotron'
  if (normalized === 'marketradar') return 'marketradar'
  return 'reviewer'
}

function uniqueLimited(items: string[], limit = 4): string[] {
  return Array.from(new Set(items.filter(Boolean))).slice(0, limit)
}

// =============================================================================
// Small UI
// =============================================================================

function MetricCard({ label, value, tone = 'neutral' }: { label: string; value: number | string; tone?: 'neutral' | 'ok' | 'warn' }) {
  const color = tone === 'ok' ? '#22C55E' : tone === 'warn' ? '#F59E0B' : '#141413'
  return (
    <GlassCard variant="subtle" padding="md" className="min-w-0">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        <span style={{
          fontFamily: "'DM Mono', monospace",
          fontSize: 10,
          color: '#87867f',
          textTransform: 'uppercase',
          letterSpacing: '0.5px',
        }}>
          {label}
        </span>
        <span style={{
          fontFamily: 'Syne, sans-serif',
          fontSize: 26,
          fontWeight: 700,
          color,
          lineHeight: 1,
        }}>
          {value}
        </span>
      </div>
    </GlassCard>
  )
}

function CandidatePill({ value, muted = false }: { value: string; muted?: boolean }) {
  return (
    <span style={{
      display: 'inline-flex',
      alignItems: 'center',
      minHeight: 22,
      padding: '3px 7px',
      borderRadius: 5,
      border: `0.5px solid ${muted ? '#e0ddd4' : '#d9775740'}`,
      background: muted ? '#faf9f3' : 'rgba(217,119,87,0.06)',
      color: muted ? '#87867f' : '#141413',
      fontFamily: "'DM Mono', monospace",
      fontSize: 10,
      lineHeight: 1.3,
      minWidth: 0,
      maxWidth: '100%',
      overflowX: 'hidden',
      overflowY: 'hidden',
      overflowWrap: 'anywhere',
      wordBreak: 'break-word',
      whiteSpace: 'normal',
    }}>
      {value}
    </span>
  )
}

function CandidateGroup({ title, items, muted = false }: { title: string; items: string[]; muted?: boolean }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8, minWidth: 0 }}>
      <div style={{
        fontFamily: 'Syne, sans-serif',
        fontSize: 12,
        fontWeight: 700,
        color: '#141413',
        textTransform: 'uppercase',
        letterSpacing: '0.7px',
      }}>
        {title}
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
        {items.length > 0 ? items.map(item => (
          <CandidatePill key={item} value={item} muted={muted} />
        )) : (
          <CandidatePill value="--" muted />
        )}
      </div>
    </div>
  )
}

function PolicyGate({ label, approved }: { label: string; approved: number }) {
  const isApproved = approved > 0
  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      gap: 10,
      padding: '9px 11px',
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      minWidth: 0,
    }}>
      <span style={{
        fontFamily: "'DM Mono', monospace",
        fontSize: 11,
        color: '#141413',
        lineHeight: 1.4,
        minWidth: 0,
      }}>
        {label}
      </span>
      <span style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 5,
        color: isApproved ? '#F59E0B' : '#22C55E',
        fontFamily: "'DM Mono', monospace",
        fontSize: 10,
        fontWeight: 700,
        whiteSpace: 'nowrap',
      }}>
        {isApproved ? <AlertTriangle size={12} /> : <Lock size={12} />}
        {approved}
      </span>
    </div>
  )
}

function DetailRow({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6, minWidth: 0 }}>
      <span style={{
        fontFamily: "'DM Mono', monospace",
        fontSize: 10,
        color: '#87867f',
        textTransform: 'uppercase',
        letterSpacing: '0.5px',
      }}>
        {label}
      </span>
      <div style={{
        fontFamily: "'DM Mono', monospace",
        fontSize: 11,
        color: '#141413',
        minWidth: 0,
      }}>
        {children}
      </div>
    </div>
  )
}

function RadarStat({ label, value, tone = 'neutral' }: { label: string; value: number | string; tone?: 'neutral' | 'ok' | 'warn' }) {
  const color = tone === 'ok' ? '#22C55E' : tone === 'warn' ? '#F59E0B' : '#141413'
  return (
    <div style={{
      minWidth: 0,
      padding: 11,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 6,
    }}>
      <span style={{
        fontFamily: "'DM Mono', monospace",
        fontSize: 10,
        color: '#87867f',
        textTransform: 'uppercase',
        letterSpacing: '0.5px',
      }}>
        {label}
      </span>
      <span style={{
        fontFamily: 'Syne, sans-serif',
        fontSize: 22,
        fontWeight: 700,
        color,
        lineHeight: 1,
      }}>
        {value}
      </span>
    </div>
  )
}

function TechnologyDomainCard({ domain }: { domain: AiTechnologyRadarReadback['technology_domains'][number] }) {
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 10,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, minWidth: 0 }}>
        <span style={{
          fontFamily: 'Syne, sans-serif',
          fontSize: 13,
          fontWeight: 700,
          color: '#141413',
          minWidth: 0,
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap',
        }}>
          {formatTechnologyArea(domain.technology_area)}
        </span>
        <CandidatePill value={`${domain.technology_count} tech / P${domain.high_priority_count}`} muted />
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
        {domain.representative_technologies.map(technology => (
          <CandidatePill key={technology} value={technology} />
        ))}
      </div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <CandidatePill value={`changed=${domain.changed_count}`} muted={domain.changed_count === 0} />
        <CandidatePill value={`high_priority=${domain.high_priority_count}`} />
      </div>
    </div>
  )
}

function RollingUpdateCard({ control }: { control: AiTechnologyRadarReadback['rolling_update_controls'][number] }) {
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'center' }}>
        <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
          {control.cadence}
        </span>
        <CandidatePill value={control.gate} muted />
      </div>
      <DetailRow label="AI 自動動作">
        {control.agent_auto_action}
      </DetailRow>
      <DetailRow label="產出">
        {control.output}
      </DetailRow>
    </div>
  )
}

function ProfessionalAgentRoleCard({ role }: { role: AiTechnologyRadarReadback['professional_agent_roles'][number] }) {
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, minWidth: 0 }}>
        <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
          {role.agent}
        </span>
        <CandidatePill value="只讀 readback" />
      </div>
      <DetailRow label="專業角色">
        {role.professional_role}
      </DetailRow>
      <DetailRow label="自動化範圍">
        {role.auto_scope}
      </DetailRow>
      <DetailRow label="審核邊界">
        {role.review_boundary}
      </DetailRow>
    </div>
  )
}

function HighPriorityReviewCard({
  item,
  labels,
}: {
  item: AiTechnologyRadarReadback['high_priority_review_queue'][number]
  labels: TechnologyReviewLabels
}) {
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'flex-start', minWidth: 0 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, minWidth: 0 }}>
          <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
            {item.display_name}
          </span>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
            <CandidatePill value={formatTechnologyArea(item.technology_area)} />
            <CandidatePill value={item.evaluation_priority} muted />
          </div>
        </div>
        <CandidatePill value={item.gate_status} muted />
      </div>
      <DetailRow label={labels.nextGate}>
        {item.next_gate}
      </DetailRow>
      <DetailRow label={labels.reviewNeeds}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
          <CandidatePill value={`${labels.cost}=${item.requires_cost_approval}`} muted />
          <CandidatePill value={`${labels.dependency}=${item.requires_dependency_approval}`} muted />
          <CandidatePill value={`${labels.security}=${item.requires_security_review}`} muted />
        </div>
      </DetailRow>
    </div>
  )
}

function PrimarySourceAlignmentCard({
  item,
  labels,
}: {
  item: AiTechnologyRadarReadback['primary_source_alignment'][number]
  labels: TechnologyReviewLabels
}) {
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'flex-start', minWidth: 0 }}>
        <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413', lineHeight: 1.35 }}>
          {item.practice}
        </span>
        <CandidatePill value={formatSourceHost(item.source)} muted />
      </div>
      <DetailRow label={labels.awoooiGate}>
        <CandidatePill value={item.awoooi_gate} />
      </DetailRow>
      <DetailRow label={labels.agentAssignment}>
        {item.agent_assignment}
      </DetailRow>
    </div>
  )
}

function ReportCadenceCard({ cadence }: { cadence: AiTechnologyReportCadenceReadback['report_cadences'][number] }) {
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'center' }}>
        <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
          {cadence.cadence_label}
        </span>
        <CandidatePill value={cadence.telegram_delivery_status} muted />
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        <CandidatePill value={cadence.owner_agent} />
        <CandidatePill value={cadence.reviewer_agent} muted />
      </div>
      <DetailRow label="報告目的">
        {cadence.report_purpose}
      </DetailRow>
      <DetailRow label="AI 閱讀後分析">
        {cadence.ai_analysis_after_reading}
      </DetailRow>
    </div>
  )
}

function AgentWorkloadCard({ workload }: { workload: AiTechnologyReportCadenceReadback['agent_workload_reports'][number] }) {
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'center' }}>
        <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
          {workload.agent}
        </span>
        <CandidatePill value={`${workload.work_unit_count} ${workload.work_unit_label}`} />
      </div>
      <DetailRow label="專業職責">
        {workload.professional_responsibility}
      </DetailRow>
      <DetailRow label="最新產出">
        {workload.latest_output}
      </DetailRow>
      <DetailRow label="下一步">
        {workload.next_action}
      </DetailRow>
    </div>
  )
}

function AgentProfessionalEvidenceCard({
  workload,
  deliveryPackets,
  fixtureCards,
  labels,
}: {
  workload: AgentWorkloadReport
  deliveryPackets: DeliveryApprovalPacket[]
  fixtureCards: RuntimeFixtureApprovalCard[]
  labels: ProfessionalEvidenceLabels
}) {
  const ownedDeliveryPackets = deliveryPackets.filter(packet => belongsToAgent(packet.owner_agent, workload.agent))
  const ownedFixtureCards = fixtureCards.filter(card => belongsToAgent(card.owner_agent, workload.agent))
  const blockedActionCount =
    ownedDeliveryPackets.reduce((total, packet) => total + packet.blocked_runtime_actions.length, 0) +
    ownedFixtureCards.reduce((total, card) => total + card.blocked_runtime_actions.length, 0)
  const evidenceItems = uniqueLimited([
    ...ownedDeliveryPackets.map(packet => `交付 ${packet.display_name}`),
    ...ownedFixtureCards.map(card => `Fixture ${card.display_name}`),
    `${workload.work_unit_count} ${workload.work_unit_label}`,
  ])

  return (
    <div style={{
      minWidth: 0,
      padding: 13,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 10,
      boxShadow: '0 8px 24px rgba(20, 20, 19, 0.04)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'flex-start', minWidth: 0 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 5, minWidth: 0 }}>
          <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 14, fontWeight: 700, color: '#141413' }}>
            {workload.agent}
          </span>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
            <CandidatePill value={`${workload.work_unit_count} ${workload.work_unit_label}`} />
            <CandidatePill value={ownedDeliveryPackets.length > 0 || ownedFixtureCards.length > 0 ? '治理責任' : labels.noRuntimeOwnership} muted />
          </div>
        </div>
        <ShieldCheck size={16} style={{ color: '#22C55E', flexShrink: 0 }} />
      </div>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
        gap: 8,
      }} className="agent-market-professional-mini-grid">
        <RadarStat label={labels.deliveryOwnership} value={ownedDeliveryPackets.length} />
        <RadarStat label={labels.fixtureOwnership} value={ownedFixtureCards.length} />
        <RadarStat label={labels.blockedActions} value={blockedActionCount} tone={blockedActionCount > 0 ? 'warn' : 'ok'} />
      </div>

      <DetailRow label={labels.role}>
        {workload.professional_responsibility}
      </DetailRow>
      <DetailRow label={labels.output}>
        {workload.latest_output}
      </DetailRow>
      <DetailRow label={labels.next}>
        {workload.next_action}
      </DetailRow>

      <DetailRow label={labels.evidence}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
          {evidenceItems.map(item => <CandidatePill key={item} value={item} />)}
        </div>
      </DetailRow>

      <DetailRow label={labels.safetyBoundary}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
          <CandidatePill value="live_send=0" muted />
          <CandidatePill value="live_query=0" muted />
          <CandidatePill value="write=0" muted />
          <CandidatePill value="owner_review_required" muted />
        </div>
      </DetailRow>
    </div>
  )
}

function AgentProfessionalJudgmentCard({
  workload,
  deliveryPackets,
  fixtureCards,
  reportCadences,
  labels,
  preset,
}: {
  workload: AgentWorkloadReport
  deliveryPackets: DeliveryApprovalPacket[]
  fixtureCards: RuntimeFixtureApprovalCard[]
  reportCadences: ReportCadence[]
  labels: ProfessionalJudgmentLabels
  preset: ProfessionalJudgmentPreset
}) {
  const ownedDeliveryPackets = deliveryPackets.filter(packet => belongsToAgent(packet.owner_agent, workload.agent))
  const ownedFixtureCards = fixtureCards.filter(card => belongsToAgent(card.owner_agent, workload.agent))
  const ownedReportCadences = reportCadences.filter(cadence =>
    belongsToAgent(cadence.owner_agent, workload.agent) ||
    belongsToAgent(cadence.reviewer_agent, workload.agent),
  )
  const blockedActionCount =
    ownedDeliveryPackets.reduce((total, packet) => total + packet.blocked_runtime_actions.length, 0) +
    ownedFixtureCards.reduce((total, card) => total + card.blocked_runtime_actions.length, 0)
  const highRiskReviewCount = ownedReportCadences.reduce(
    (total, cadence) => total + cadence.high_risk_owner_review_actions.length,
    0,
  )
  const evidencePointCount =
    workload.work_unit_count +
    ownedDeliveryPackets.length +
    ownedFixtureCards.length +
    ownedReportCadences.length
  const ownerGateRequired = blockedActionCount > 0 || highRiskReviewCount > 0
  const blockedBoundaries = uniqueLimited([
    ...ownedDeliveryPackets.flatMap(packet => packet.blocked_runtime_actions),
    ...ownedFixtureCards.flatMap(card => card.blocked_runtime_actions),
    ...ownedReportCadences.flatMap(cadence => cadence.high_risk_owner_review_actions),
    'production_write=false',
    'provider_switch=false',
  ], 5)

  return (
    <div style={{
      minWidth: 0,
      padding: 13,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 10,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'flex-start', minWidth: 0 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 5, minWidth: 0 }}>
          <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 14, fontWeight: 700, color: '#141413' }}>
            {workload.agent}
          </span>
          <CandidatePill value={preset.lane} />
        </div>
        <span style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: 5,
          color: ownerGateRequired ? '#F59E0B' : '#22C55E',
          fontFamily: "'DM Mono', monospace",
          fontSize: 10,
          fontWeight: 700,
          whiteSpace: 'nowrap',
        }}>
          {ownerGateRequired ? <AlertTriangle size={13} /> : <ShieldCheck size={13} />}
          {ownerGateRequired ? labels.ownerGate : labels.readOnlyReady}
        </span>
      </div>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
        gap: 8,
      }} className="agent-market-professional-mini-grid">
        <RadarStat label={labels.evidencePoints} value={evidencePointCount} />
        <RadarStat label={labels.reportOwnership} value={ownedReportCadences.length} />
        <RadarStat label={labels.riskTier} value={ownerGateRequired ? labels.ownerGate : labels.readOnlyReady} tone={ownerGateRequired ? 'warn' : 'ok'} />
      </div>

      <DetailRow label={labels.question}>
        {preset.question}
      </DetailRow>
      <DetailRow label={labels.allowedNext}>
        {workload.next_action}
      </DetailRow>
      <DetailRow label={labels.blockedBoundary}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
          {blockedBoundaries.map(item => <CandidatePill key={item} value={item} muted />)}
        </div>
      </DetailRow>
      <DetailRow label={labels.escalation}>
        {preset.escalation}
      </DetailRow>
    </div>
  )
}

function PostReportAnalysisCard({ packet }: { packet: AiTechnologyReportCadenceReadback['post_report_analysis_packets'][number] }) {
  const tone = packet.risk_tier === 'high' ? '#F59E0B' : packet.risk_tier === 'medium' ? '#d97757' : '#22C55E'
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'center' }}>
        <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
          {packet.report_id}
        </span>
        <span style={{
          fontFamily: "'DM Mono', monospace",
          fontSize: 10,
          fontWeight: 700,
          color: tone,
          textTransform: 'uppercase',
        }}>
          {packet.risk_tier}
        </span>
      </div>
      <DetailRow label="關鍵發現">
        {packet.key_finding}
      </DetailRow>
      <DetailRow label="解決方案">
        {packet.proposed_solution}
      </DetailRow>
      <DetailRow label="執行邊界">
        {packet.execution_boundary}
      </DetailRow>
    </div>
  )
}

function DeliveryApprovalPacketCard({ packet }: { packet: AiAgentReportLiveDeliveryApprovalPackageSnapshot['delivery_approval_packets'][number] }) {
  const tone = packet.risk_tier === 'critical' ? '#DC2626' : packet.risk_tier === 'high' ? '#F59E0B' : '#d97757'
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'flex-start', minWidth: 0 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, minWidth: 0 }}>
          <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
            {packet.display_name}
          </span>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
            <CandidatePill value={packet.cadence} />
            <CandidatePill value={packet.owner_agent} muted />
            <CandidatePill value={packet.status} muted={packet.status !== 'blocked_by_policy'} />
          </div>
        </div>
        <span style={{
          fontFamily: "'DM Mono', monospace",
          fontSize: 10,
          fontWeight: 700,
          color: tone,
          textTransform: 'uppercase',
          whiteSpace: 'nowrap',
        }}>
          {packet.risk_tier}
        </span>
      </div>
      <DetailRow label="必填欄位">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
          {packet.required_approval_fields.map(field => (
            <CandidatePill key={field} value={field} muted />
          ))}
        </div>
      </DetailRow>
      <DetailRow label="阻擋動作">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
          {packet.blocked_runtime_actions.map(action => (
            <CandidatePill key={action} value={action} muted />
          ))}
        </div>
      </DetailRow>
      <DetailRow label="操作指引">
        {packet.operator_guidance}
      </DetailRow>
    </div>
  )
}

function DeliveryGateCard({ gate }: { gate: AiAgentReportLiveDeliveryApprovalPackageSnapshot['route_lock_gates'][number] }) {
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'center', minWidth: 0 }}>
        <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
          {gate.display_name}
        </span>
        <CandidatePill value={gate.status} muted={gate.status !== 'blocked_by_policy'} />
      </div>
      <DetailRow label="阻擋路由">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
          {gate.blocked_routes.map(route => (
            <CandidatePill key={route} value={route} muted />
          ))}
        </div>
      </DetailRow>
      <DetailRow label="實發旗標">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
          <CandidatePill value={`send=${gate.telegram_send_enabled}`} muted />
          <CandidatePill value={`bot=${gate.bot_api_call_enabled}`} muted />
          <CandidatePill value={`queue=${gate.gateway_queue_write_enabled}`} muted />
        </div>
      </DetailRow>
    </div>
  )
}

function DryRunReceiptCard({ receipt }: { receipt: AiAgentReportLiveDeliveryApprovalPackageSnapshot['dry_run_delivery_receipts'][number] }) {
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'center', minWidth: 0 }}>
        <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
          {receipt.display_name}
        </span>
        <CandidatePill value={receipt.status} muted={receipt.status !== 'blocked_by_policy'} />
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
        <CandidatePill value={receipt.cadence} />
        <CandidatePill value={`live_send=${receipt.live_send_count}`} muted />
        <CandidatePill value={`receipt_write=${receipt.receipt_write_allowed}`} muted />
      </div>
      <DetailRow label="必填欄位">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
          {receipt.required_fields.map(field => (
            <CandidatePill key={field} value={field} muted />
          ))}
        </div>
      </DetailRow>
    </div>
  )
}

function RuntimeFixtureApprovalCard({ card }: { card: AiAgentRuntimeReadbackFixtureApprovalSnapshot['fixture_approval_cards'][number] }) {
  const tone = card.risk_tier === 'critical' ? '#DC2626' : card.risk_tier === 'high' ? '#F59E0B' : '#d97757'
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'flex-start', minWidth: 0 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, minWidth: 0 }}>
          <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
            {card.display_name}
          </span>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
            <CandidatePill value={card.source_task_id} />
            <CandidatePill value={card.owner_agent} muted />
            <CandidatePill value={card.status} muted={card.status !== 'blocked_by_policy'} />
            <CandidatePill value={`fixture_only=${card.fixture_only}`} muted />
          </div>
        </div>
        <span style={{
          fontFamily: "'DM Mono', monospace",
          fontSize: 10,
          fontWeight: 700,
          color: tone,
          textTransform: 'uppercase',
          whiteSpace: 'nowrap',
        }}>
          {card.risk_tier}
        </span>
      </div>
      <DetailRow label="fixture 欄位">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
          {card.required_fixture_fields.map(field => (
            <CandidatePill key={field} value={field} muted />
          ))}
        </div>
      </DetailRow>
      <DetailRow label="阻擋 runtime 動作">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
          {card.blocked_runtime_actions.map(action => (
            <CandidatePill key={action} value={action} muted />
          ))}
        </div>
      </DetailRow>
      <DetailRow label="操作指引">
        {card.operator_guidance}
      </DetailRow>
    </div>
  )
}

function AdapterContractCard({ contract }: { contract: AiAgentRuntimeReadbackFixtureApprovalSnapshot['adapter_contracts'][number] }) {
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'center', minWidth: 0 }}>
        <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
          {contract.display_name}
        </span>
        <CandidatePill value={contract.status} muted={contract.status !== 'blocked_by_policy'} />
      </div>
      <DetailRow label="Schema 對接">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
          <CandidatePill value={contract.input_schema} muted />
          <CandidatePill value={contract.output_schema} muted />
        </div>
      </DetailRow>
      <DetailRow label="必要證據">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
          {contract.required_evidence.map(evidence => (
            <CandidatePill key={evidence} value={evidence} muted />
          ))}
        </div>
      </DetailRow>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
        <CandidatePill value={`target_read=${contract.canonical_target_read_enabled}`} muted />
        <CandidatePill value={`live_query=${contract.live_query_enabled}`} muted />
      </div>
    </div>
  )
}

function VerifierFixtureCheckCard({ check }: { check: AiAgentRuntimeReadbackFixtureApprovalSnapshot['verifier_fixture_checks'][number] }) {
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'center', minWidth: 0 }}>
        <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
          {check.display_name}
        </span>
        <CandidatePill value={check.status} muted={check.status !== 'blocked_by_policy'} />
      </div>
      <DetailRow label="fixture 條件">
        {check.required_fixture}
      </DetailRow>
      <DetailRow label="缺漏時阻擋">
        {check.failure_if_missing}
      </DetailRow>
      <CandidatePill value={`live_verifier=${check.live_verifier_enabled}`} muted />
    </div>
  )
}

function RuntimeBlockerMappingCard({ blocker }: { blocker: AiAgentRuntimeReadbackFixtureApprovalSnapshot['blocker_mappings'][number] }) {
  const tone = blocker.severity === 'critical' ? '#DC2626' : blocker.severity === 'high' ? '#F59E0B' : '#d97757'
  return (
    <div style={{
      minWidth: 0,
      padding: 12,
      border: '0.5px solid #e0ddd4',
      borderRadius: 7,
      background: '#fff',
      display: 'flex',
      flexDirection: 'column',
      gap: 9,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'flex-start', minWidth: 0 }}>
        <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
          {blocker.display_name}
        </span>
        <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, fontWeight: 700, color: tone, textTransform: 'uppercase', whiteSpace: 'nowrap' }}>
          {blocker.severity}
        </span>
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
        <CandidatePill value={blocker.status} muted={blocker.status !== 'blocked_by_policy'} />
        <CandidatePill value={blocker.blocked_action} muted />
      </div>
      <DetailRow label="來源 blocker">
        {blocker.source_blocker}
      </DetailRow>
      <DetailRow label="解除條件">
        {blocker.blocked_until}
      </DetailRow>
    </div>
  )
}

// =============================================================================
// Component
// =============================================================================

export function AgentMarketTab() {
  const t = useTranslations('governance.agentMarket')
  const [snapshot, setSnapshot] = useState<AgentMarketGovernanceSnapshot | null>(null)
  const [technologyRadar, setTechnologyRadar] = useState<AiTechnologyRadarReadback | null>(null)
  const [technologyReportCadence, setTechnologyReportCadence] = useState<AiTechnologyReportCadenceReadback | null>(null)
  const [reportDeliveryApproval, setReportDeliveryApproval] = useState<AiAgentReportLiveDeliveryApprovalPackageSnapshot | null>(null)
  const [runtimeFixtureApproval, setRuntimeFixtureApproval] = useState<AiAgentRuntimeReadbackFixtureApprovalSnapshot | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(false)

  const fetchSnapshot = () => {
    setLoading(true)
    Promise.all([
      apiClient.getAgentMarketGovernanceSnapshot(),
      apiClient.getAiTechnologyRadarReadback(),
      apiClient.getAiTechnologyReportCadenceReadback(),
      apiClient.getAiAgentReportLiveDeliveryApprovalPackage(),
      apiClient.getAiAgentRuntimeReadbackFixtureApproval(),
    ])
      .then(([marketSnapshot, radarReadback, reportCadenceReadback, deliveryApprovalPackage, runtimeFixtureApprovalPackage]) => {
        setSnapshot(marketSnapshot)
        setTechnologyRadar(radarReadback)
        setTechnologyReportCadence(reportCadenceReadback)
        setReportDeliveryApproval(deliveryApprovalPackage)
        setRuntimeFixtureApproval(runtimeFixtureApprovalPackage)
        setError(false)
      })
      .catch(() => setError(true))
      .finally(() => setLoading(false))
  }

  useEffect(() => {
    fetchSnapshot()
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  if (loading) {
    return (
      <div style={{ padding: 20, display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 12 }} className="agent-market-kpi-grid">
        {[0, 1, 2, 3].map(i => (
          <GlassCard key={i} variant="subtle" padding="md">
            <div style={{ width: 84, height: 10, borderRadius: 4, background: '#e0ddd4', animation: 'pulse 1.5s infinite', marginBottom: 10, animationDelay: `${i * 0.08}s` }} />
            <div style={{ width: 52, height: 26, borderRadius: 4, background: '#e0ddd4', animation: 'pulse 1.5s infinite' }} />
          </GlassCard>
        ))}
      </div>
    )
  }

  if (error || !snapshot || !technologyRadar || !technologyReportCadence || !reportDeliveryApproval || !runtimeFixtureApproval) {
    return (
      <div style={{ padding: 20 }}>
        <GlassCard variant="subtle" padding="lg">
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, padding: '24px 0' }}>
            <AlertTriangle size={24} style={{ color: '#F59E0B' }} />
            <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 12, color: '#87867f' }}>
              {t('error')}
            </span>
            <button
              onClick={fetchSnapshot}
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: 6,
                padding: '6px 14px',
                border: '0.5px solid #d97757',
                borderRadius: 6,
                background: 'transparent',
                color: '#d97757',
                cursor: 'pointer',
                fontFamily: "'DM Mono', monospace",
                fontSize: 11,
              }}
            >
              <RefreshCw size={12} />
              {t('retry')}
            </button>
          </div>
        </GlassCard>
      </div>
    )
  }

  const summary = snapshot.summary
  const radarSummary = technologyRadar.summary
  const reportSummary = technologyReportCadence.summary
  const deliveryRollups = reportDeliveryApproval.rollups
  const fixtureRollups = runtimeFixtureApproval.rollups
  const totalAgentWorkUnits = technologyReportCadence.agent_workload_reports.reduce(
    (total, workload) => total + workload.work_unit_count,
    0,
  )
  const professionalEvidenceLabels: ProfessionalEvidenceLabels = {
    role: t('technologyReports.professionalEvidence.role'),
    output: t('technologyReports.professionalEvidence.output'),
    next: t('technologyReports.professionalEvidence.next'),
    deliveryOwnership: t('technologyReports.professionalEvidence.deliveryOwnership'),
    fixtureOwnership: t('technologyReports.professionalEvidence.fixtureOwnership'),
    blockedActions: t('technologyReports.professionalEvidence.blockedActions'),
    evidence: t('technologyReports.professionalEvidence.evidence'),
    safetyBoundary: t('technologyReports.professionalEvidence.safetyBoundary'),
    noRuntimeOwnership: t('technologyReports.professionalEvidence.noRuntimeOwnership'),
  }
  const professionalJudgmentLabels: ProfessionalJudgmentLabels = {
    lane: t('technologyReports.professionalJudgment.lane'),
    question: t('technologyReports.professionalJudgment.question'),
    evidencePoints: t('technologyReports.professionalJudgment.evidencePoints'),
    riskTier: t('technologyReports.professionalJudgment.riskTier'),
    allowedNext: t('technologyReports.professionalJudgment.allowedNext'),
    blockedBoundary: t('technologyReports.professionalJudgment.blockedBoundary'),
    escalation: t('technologyReports.professionalJudgment.escalation'),
    readOnlyReady: t('technologyReports.professionalJudgment.readOnlyReady'),
    ownerGate: t('technologyReports.professionalJudgment.ownerGate'),
    reportOwnership: t('technologyReports.professionalJudgment.reportOwnership'),
  }
  const professionalJudgmentPresets: Record<ReturnType<typeof getAgentJudgmentPresetKey>, ProfessionalJudgmentPreset> = {
    openclaw: {
      lane: t('technologyReports.professionalJudgment.presets.openclaw.lane'),
      question: t('technologyReports.professionalJudgment.presets.openclaw.question'),
      escalation: t('technologyReports.professionalJudgment.presets.openclaw.escalation'),
    },
    hermes: {
      lane: t('technologyReports.professionalJudgment.presets.hermes.lane'),
      question: t('technologyReports.professionalJudgment.presets.hermes.question'),
      escalation: t('technologyReports.professionalJudgment.presets.hermes.escalation'),
    },
    nemotron: {
      lane: t('technologyReports.professionalJudgment.presets.nemotron.lane'),
      question: t('technologyReports.professionalJudgment.presets.nemotron.question'),
      escalation: t('technologyReports.professionalJudgment.presets.nemotron.escalation'),
    },
    marketradar: {
      lane: t('technologyReports.professionalJudgment.presets.marketradar.lane'),
      question: t('technologyReports.professionalJudgment.presets.marketradar.question'),
      escalation: t('technologyReports.professionalJudgment.presets.marketradar.escalation'),
    },
    reviewer: {
      lane: t('technologyReports.professionalJudgment.presets.reviewer.lane'),
      question: t('technologyReports.professionalJudgment.presets.reviewer.question'),
      escalation: t('technologyReports.professionalJudgment.presets.reviewer.escalation'),
    },
  }
  const technologyReviewLabels: TechnologyReviewLabels = {
    nextGate: t('technologyRadar.reviewLabels.nextGate'),
    reviewNeeds: t('technologyRadar.reviewLabels.reviewNeeds'),
    cost: t('technologyRadar.reviewLabels.cost'),
    dependency: t('technologyRadar.reviewLabels.dependency'),
    security: t('technologyRadar.reviewLabels.security'),
    awoooiGate: t('technologyRadar.reviewLabels.awoooiGate'),
    agentAssignment: t('technologyRadar.reviewLabels.agentAssignment'),
  }
  const allApprovals =
    summary.priority_upgrades_approved +
    summary.market_scorecard_updates_approved +
    summary.replay_candidates_approved +
    summary.sdk_installations_approved +
    summary.paid_api_calls_approved +
    summary.production_changes_approved +
    summary.shadow_or_canary_approved +
    summary.replacement_decisions_approved
  const radarPolicyHolds = Object.entries(technologyRadar.policy)
    .filter(([key, value]) => key !== 'read_only' && value === false)
    .length
  const watchHealth = snapshot.market_watch_health
  const watchHealthHealthy = watchHealth.status === 'healthy'
  const watchHealthReasons = watchHealth.controlled_queue_reasons ?? watchHealth.operator_blockers ?? []
  const controlledReviewGate = snapshot.evaluation_cadence.controlled_review_gate ?? snapshot.evaluation_cadence.operator_review_gate

  return (
    <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 16 }}>
      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
            <div style={{
              width: 34,
              height: 34,
              borderRadius: 8,
              border: '0.5px solid #22C55E40',
              background: 'rgba(34,197,94,0.08)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              flexShrink: 0,
            }}>
              <ShieldCheck size={17} style={{ color: '#22C55E' }} />
            </div>
            <div style={{ minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 3 }}>
                <StatusOrb status={allApprovals === 0 ? 'healthy' : 'warning'} size="sm" glow />
                <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 15, fontWeight: 700, color: '#141413' }}>
                  {t('title')}
                </span>
              </div>
              <div style={{
                fontFamily: "'DM Mono', monospace",
                fontSize: 11,
                color: '#87867f',
                maxWidth: '100%',
                overflowX: 'auto',
                overflowY: 'hidden',
                overflowWrap: 'normal',
                whiteSpace: 'nowrap',
              }}>
                {snapshot.current_decision}
              </div>
            </div>
          </div>
          <div style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, color: '#87867f' }}>
            {t('generatedAt')} {formatDateTime(snapshot.generated_at)}
          </div>
        </div>
      </GlassCard>

      <AgentActivityConstellation
        mode="market"
        statusValue={snapshot.current_decision}
        metrics={[
          { label: t('agentActivity.metrics.candidates'), value: summary.candidate_count, tone: 'neutral' },
          { label: t('agentActivity.metrics.prescreenReady'), value: summary.eligible_for_market_scorecard_prescreen, tone: 'ok' },
          { label: t('agentActivity.metrics.blocked'), value: summary.blocked_from_integration, tone: summary.blocked_from_integration > 0 ? 'warn' : 'ok' },
          { label: t('agentActivity.metrics.approvals'), value: allApprovals, tone: allApprovals === 0 ? 'ok' : 'warn' },
        ]}
      />

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
              <ShieldCheck size={15} style={{ color: '#22C55E' }} />
              <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 14, fontWeight: 700, color: '#141413' }}>
                {t('technologyReports.professionalTitle')}
              </span>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: 'flex-end', minWidth: 0, maxWidth: '100%' }}>
              <CandidatePill value={technologyReportCadence.summary.status} />
              <CandidatePill value={`runtime=${technologyReportCadence.policy.low_medium_runtime_auto_write_enabled}`} muted />
            </div>
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(5, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-professional-metrics-grid">
            <RadarStat label={t('technologyReports.professionalMetrics.agents')} value={technologyReportCadence.agent_workload_reports.length} />
            <RadarStat label={t('technologyReports.professionalMetrics.workUnits')} value={totalAgentWorkUnits} />
            <RadarStat label={t('technologyReports.professionalMetrics.delivery')} value={deliveryRollups.delivery_approval_packet_count} />
            <RadarStat label={t('technologyReports.professionalMetrics.fixture')} value={fixtureRollups.fixture_approval_card_count} />
            <RadarStat label={t('technologyReports.professionalMetrics.blockedGates')} value={technologyReportCadence.blocked_gates.length} tone={technologyReportCadence.blocked_gates.length > 0 ? 'warn' : 'ok'} />
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
            <ListChecks size={14} style={{ color: '#d97757', flexShrink: 0 }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('technologyReports.professionalJudgmentTitle')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-professional-judgment-grid">
            {technologyReportCadence.agent_workload_reports.map(workload => {
              const presetKey = getAgentJudgmentPresetKey(workload.agent)
              return (
                <AgentProfessionalJudgmentCard
                  key={workload.agent}
                  workload={workload}
                  deliveryPackets={reportDeliveryApproval.delivery_approval_packets}
                  fixtureCards={runtimeFixtureApproval.fixture_approval_cards}
                  reportCadences={technologyReportCadence.report_cadences}
                  labels={professionalJudgmentLabels}
                  preset={professionalJudgmentPresets[presetKey]}
                />
              )
            })}
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-professional-evidence-grid">
            {technologyReportCadence.agent_workload_reports.map(workload => (
              <AgentProfessionalEvidenceCard
                key={workload.agent}
                workload={workload}
                deliveryPackets={reportDeliveryApproval.delivery_approval_packets}
                fixtureCards={runtimeFixtureApproval.fixture_approval_cards}
                labels={professionalEvidenceLabels}
              />
            ))}
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
              <CalendarClock size={15} style={{ color: '#d97757' }} />
              <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 14, fontWeight: 700, color: '#141413' }}>
                {t('technologyRadar.title')}
              </span>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: 'flex-end', minWidth: 0, maxWidth: '100%' }}>
              <CandidatePill value={technologyRadar.report_contract.schedule_workflow} />
              <CandidatePill value={technologyRadar.report_contract.schedule_cron_utc} muted />
            </div>
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(5, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-radar-metrics-grid">
            <RadarStat label={t('technologyRadar.metrics.progress')} value={formatPercent(radarSummary.ai_technology_radar_completion_percent)} tone="ok" />
            <RadarStat label={t('technologyRadar.metrics.technologies')} value={radarSummary.technology_count} />
            <RadarStat label={t('technologyRadar.metrics.sources')} value={radarSummary.source_count} />
            <RadarStat label={t('technologyRadar.metrics.failures')} value={radarSummary.source_failures} tone={radarSummary.source_failures > 0 ? 'warn' : 'ok'} />
            <RadarStat label={t('technologyRadar.metrics.policyHolds')} value={radarPolicyHolds} tone={radarPolicyHolds > 0 ? 'warn' : 'ok'} />
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-radar-contract-grid">
            <DetailRow label={t('technologyRadar.status')}>
              <CandidatePill value={radarSummary.rolling_update_status} />
            </DetailRow>
            <DetailRow label={t('technologyRadar.nearRealTime')}>
              {technologyRadar.report_contract.near_real_time}
            </DetailRow>
            <DetailRow label={t('technologyRadar.reviewQueue')}>
              {t('technologyRadar.reviewQueueValue', {
                queue: radarSummary.review_queue_count,
                high: radarSummary.high_priority_count,
                changed: radarSummary.changed_technologies,
              })}
            </DetailRow>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
            <AlertTriangle size={14} style={{ color: '#F59E0B', flexShrink: 0 }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('technologyRadar.highPriorityTitle')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-radar-review-grid">
            {technologyRadar.high_priority_review_queue.length > 0 ? (
              technologyRadar.high_priority_review_queue.map(item => (
                <HighPriorityReviewCard
                  key={item.technology_id}
                  item={item}
                  labels={technologyReviewLabels}
                />
              ))
            ) : (
              <DetailRow label={t('technologyRadar.highPriorityTitle')}>
                <CandidatePill value={t('technologyRadar.emptyReviewQueue')} muted />
              </DetailRow>
            )}
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
            <ListChecks size={14} style={{ color: '#d97757', flexShrink: 0 }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('technologyRadar.primarySourceTitle')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-radar-source-grid">
            {technologyRadar.primary_source_alignment.map(item => (
              <PrimarySourceAlignmentCard
                key={`${item.awoooi_gate}-${item.source}`}
                item={item}
                labels={technologyReviewLabels}
              />
            ))}
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
              <ShieldCheck size={15} style={{ color: '#d97757' }} />
              <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 14, fontWeight: 700, color: '#141413' }}>
                {t('technologyReports.runtimeFixtureTitle')}
              </span>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: 'flex-end', minWidth: 0, maxWidth: '100%' }}>
              <CandidatePill value={runtimeFixtureApproval.program_status.current_task_id} />
              <CandidatePill value={runtimeFixtureApproval.program_status.runtime_authority} muted />
            </div>
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(5, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-runtime-fixture-metrics-grid">
            <RadarStat label={t('technologyReports.runtimeFixtureMetrics.cards')} value={fixtureRollups.fixture_approval_card_count} />
            <RadarStat label={t('technologyReports.runtimeFixtureMetrics.adapters')} value={fixtureRollups.adapter_contract_count} />
            <RadarStat label={t('technologyReports.runtimeFixtureMetrics.verifiers')} value={fixtureRollups.verifier_fixture_check_count} />
            <RadarStat label={t('technologyReports.runtimeFixtureMetrics.blockers')} value={fixtureRollups.blocker_mapping_count} tone="warn" />
            <RadarStat label={t('technologyReports.runtimeFixtureMetrics.liveQuery')} value={fixtureRollups.live_query_count} tone="ok" />
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(5, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-runtime-fixture-truth-grid">
            <DetailRow label={t('technologyReports.runtimeFixtureTruth.targetRead')}>
              <CandidatePill value={String(runtimeFixtureApproval.fixture_approval_truth.canonical_runtime_target_read_enabled)} muted />
            </DetailRow>
            <DetailRow label={t('technologyReports.runtimeFixtureTruth.runtimeReadback')}>
              <CandidatePill value={String(runtimeFixtureApproval.fixture_approval_truth.runtime_readback_execution_enabled)} muted />
            </DetailRow>
            <DetailRow label={t('technologyReports.runtimeFixtureTruth.resultCapture')}>
              <CandidatePill value={String(runtimeFixtureApproval.fixture_approval_truth.result_capture_write_enabled)} muted />
            </DetailRow>
            <DetailRow label={t('technologyReports.runtimeFixtureTruth.productionWrite')}>
              <CandidatePill value={String(runtimeFixtureApproval.fixture_approval_truth.production_write_enabled)} muted />
            </DetailRow>
            <DetailRow label={t('technologyReports.runtimeFixtureTruth.ownerApproval')}>
              <CandidatePill value={String(runtimeFixtureApproval.fixture_approval_truth.owner_approval_received_count)} muted />
            </DetailRow>
          </div>

          <DetailRow label={t('technologyReports.runtimeFixtureTruth.note')}>
            {runtimeFixtureApproval.fixture_approval_truth.truth_note}
          </DetailRow>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-runtime-fixture-card-grid">
            {runtimeFixtureApproval.fixture_approval_cards.map(card => (
              <RuntimeFixtureApprovalCard key={card.card_id} card={card} />
            ))}
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <Lock size={14} style={{ color: '#F59E0B' }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('technologyReports.runtimeFixtureGuardTitle')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-runtime-adapter-grid">
            {runtimeFixtureApproval.adapter_contracts.map(contract => (
              <AdapterContractCard key={contract.contract_id} contract={contract} />
            ))}
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-runtime-verifier-grid">
            {runtimeFixtureApproval.verifier_fixture_checks.map(check => (
              <VerifierFixtureCheckCard key={check.check_id} check={check} />
            ))}
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-runtime-blocker-grid">
            {runtimeFixtureApproval.blocker_mappings.map(blocker => (
              <RuntimeBlockerMappingCard key={blocker.blocker_id} blocker={blocker} />
            ))}
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
              <Lock size={15} style={{ color: '#F59E0B' }} />
              <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 14, fontWeight: 700, color: '#141413' }}>
                {t('technologyReports.deliveryTitle')}
              </span>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: 'flex-end', minWidth: 0, maxWidth: '100%' }}>
              <CandidatePill value={reportDeliveryApproval.program_status.current_task_id} />
              <CandidatePill value={reportDeliveryApproval.program_status.runtime_authority} muted />
            </div>
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(5, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-delivery-metrics-grid">
            <RadarStat label={t('technologyReports.deliveryMetrics.packets')} value={deliveryRollups.delivery_approval_packet_count} />
            <RadarStat label={t('technologyReports.deliveryMetrics.routes')} value={deliveryRollups.route_lock_gate_count} />
            <RadarStat label={t('technologyReports.deliveryMetrics.redaction')} value={deliveryRollups.payload_redaction_check_count} tone="ok" />
            <RadarStat label={t('technologyReports.deliveryMetrics.receipts')} value={deliveryRollups.dry_run_delivery_receipt_count} />
            <RadarStat label={t('technologyReports.deliveryMetrics.liveSend')} value={deliveryRollups.telegram_send_count} tone="ok" />
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-delivery-gate-grid">
            <DetailRow label={t('technologyReports.deliveryTruth.scheduler')}>
              <CandidatePill value={String(reportDeliveryApproval.delivery_approval_truth.scheduler_enabled)} muted />
            </DetailRow>
            <DetailRow label={t('technologyReports.deliveryTruth.queue')}>
              <CandidatePill value={String(reportDeliveryApproval.delivery_approval_truth.gateway_queue_write_enabled)} muted />
            </DetailRow>
            <DetailRow label={t('technologyReports.deliveryTruth.botApi')}>
              <CandidatePill value={String(reportDeliveryApproval.delivery_approval_truth.bot_api_call_enabled)} muted />
            </DetailRow>
            <DetailRow label={t('technologyReports.deliveryTruth.receiptWrite')}>
              <CandidatePill value={String(reportDeliveryApproval.delivery_approval_truth.report_receipt_write_enabled)} muted />
            </DetailRow>
          </div>

          <DetailRow label={t('technologyReports.deliveryTruth.note')}>
            {reportDeliveryApproval.delivery_approval_truth.truth_note}
          </DetailRow>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-delivery-packet-grid">
            {reportDeliveryApproval.delivery_approval_packets.map(packet => (
              <DeliveryApprovalPacketCard key={packet.packet_id} packet={packet} />
            ))}
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <ShieldCheck size={14} style={{ color: '#d97757' }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('technologyReports.deliveryGuardTitle')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-delivery-guard-grid">
            {reportDeliveryApproval.route_lock_gates.map(gate => (
              <DeliveryGateCard key={gate.gate_id} gate={gate} />
            ))}
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-delivery-receipt-grid">
            {reportDeliveryApproval.dry_run_delivery_receipts.map(receipt => (
              <DryRunReceiptCard key={receipt.receipt_id} receipt={receipt} />
            ))}
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
              <ListChecks size={15} style={{ color: '#d97757' }} />
              <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 14, fontWeight: 700, color: '#141413' }}>
                {t('technologyReports.title')}
              </span>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: 'flex-end', minWidth: 0, maxWidth: '100%' }}>
              <CandidatePill value={technologyReportCadence.report_contract.api_endpoint} />
              <CandidatePill value={technologyReportCadence.telegram_report_bridge.integration_status} muted />
            </div>
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(6, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-report-metrics-grid">
            <RadarStat label={t('technologyReports.metrics.reports')} value={`${reportSummary.report_ready_count}/${reportSummary.report_cadence_count}`} tone="ok" />
            <RadarStat label={t('technologyReports.metrics.charts')} value={reportSummary.chart_section_count} />
            <RadarStat label={t('technologyReports.metrics.agentStatus')} value={reportSummary.agent_status_report_count} />
            <RadarStat label={t('technologyReports.metrics.analysisPackets')} value={reportSummary.post_report_analysis_packet_count} />
            <RadarStat label={t('technologyReports.metrics.lowMedium')} value={reportSummary.low_medium_auto_action_proposal_count} tone="ok" />
            <RadarStat label={t('technologyReports.metrics.highRisk')} value={reportSummary.high_risk_owner_review_count} tone="warn" />
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-report-gate-grid">
            <DetailRow label={t('technologyReports.status')}>
              <CandidatePill value={reportSummary.status} />
            </DetailRow>
            <DetailRow label={t('technologyReports.telegram')}>
              <CandidatePill value={`send=${technologyReportCadence.policy.telegram_send_enabled}`} muted />
            </DetailRow>
            <DetailRow label={t('technologyReports.receipt')}>
              <CandidatePill value={`receipt=${technologyReportCadence.policy.report_receipt_write_enabled}`} muted />
            </DetailRow>
            <DetailRow label={t('technologyReports.autoWrite')}>
              <CandidatePill value={`runtime=${technologyReportCadence.policy.low_medium_runtime_auto_write_enabled}`} muted />
            </DetailRow>
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <CalendarClock size={14} style={{ color: '#d97757' }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('technologyReports.cadencesTitle')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-report-cadence-grid">
            {technologyReportCadence.report_cadences.map(cadence => (
              <ReportCadenceCard key={cadence.cadence} cadence={cadence} />
            ))}
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <ShieldCheck size={14} style={{ color: '#d97757' }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('technologyReports.workloadTitle')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-report-workload-grid">
            {technologyReportCadence.agent_workload_reports.map(workload => (
              <AgentWorkloadCard key={workload.agent} workload={workload} />
            ))}
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <AlertTriangle size={14} style={{ color: '#F59E0B' }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('technologyReports.analysisTitle')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-report-analysis-grid">
            {technologyReportCadence.post_report_analysis_packets.map(packet => (
              <PostReportAnalysisCard key={packet.report_id} packet={packet} />
            ))}
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <ListChecks size={14} style={{ color: '#d97757' }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('technologyRadar.domainsTitle')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-radar-domain-grid">
            {technologyRadar.technology_domains.map(domain => (
              <TechnologyDomainCard key={domain.technology_area} domain={domain} />
            ))}
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <RefreshCw size={14} style={{ color: '#d97757' }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('technologyRadar.rollingTitle')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-radar-rolling-grid">
            {technologyRadar.rolling_update_controls.map(control => (
              <RollingUpdateCard key={`${control.cadence}-${control.gate}`} control={control} />
            ))}
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <ShieldCheck size={14} style={{ color: '#d97757' }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('technologyRadar.rolesTitle')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-radar-role-grid">
            {technologyRadar.professional_agent_roles.map(role => (
              <ProfessionalAgentRoleCard key={role.agent} role={role} />
            ))}
          </div>
        </div>
      </GlassCard>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
        gap: 12,
      }} className="agent-market-kpi-grid">
        <MetricCard label={t('metrics.candidates')} value={summary.candidate_count} />
        <MetricCard label={t('metrics.sources')} value={summary.source_count} />
        <MetricCard label={t('metrics.blocked')} value={summary.blocked_from_integration} tone="warn" />
        <MetricCard label={t('metrics.prescreenReady')} value={summary.eligible_for_market_scorecard_prescreen} tone="ok" />
      </div>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            {watchHealthHealthy ? (
              <ShieldCheck size={14} style={{ color: '#22C55E' }} />
            ) : (
              <AlertTriangle size={14} style={{ color: '#F59E0B' }} />
            )}
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('health.title')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
            gap: 12,
          }} className="agent-market-health-grid">
            <DetailRow label={t('health.status')}>
              <span style={{ color: watchHealthHealthy ? '#22C55E' : '#F59E0B', fontWeight: 700 }}>
                {t(`health.statuses.${watchHealth.status}`)}
              </span>
            </DetailRow>
            <DetailRow label={t('health.freshnessSla')}>
              {t('health.slaValue', {
                slaHours: watchHealth.freshness_sla_hours,
                graceHours: watchHealth.stale_grace_hours,
              })}
            </DetailRow>
            <DetailRow label={t('health.staleAfter')}>
              {formatDateTime(watchHealth.stale_after)}
            </DetailRow>
            <DetailRow label={t('health.priorityGate')}>
              {watchHealth.source_failures_require_controlled_reverify ? t('health.controlledReverify') : t('health.clear')}
            </DetailRow>
            <DetailRow label={t('health.blockedIntegrations')}>
              {watchHealth.blocked_from_integration}
            </DetailRow>
            <DetailRow label={t('health.blockers')}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
                {watchHealthReasons.length > 0 ? (
                  watchHealthReasons.map(blocker => (
                    <CandidatePill key={blocker} value={blocker} muted />
                  ))
                ) : (
                  <CandidatePill value={t('health.noBlockers')} />
                )}
              </div>
            </DetailRow>
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <CalendarClock size={14} style={{ color: '#d97757' }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('cadence.title')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
            gap: 12,
          }} className="agent-market-cadence-grid">
            <DetailRow label={t('cadence.workflow')}>
              <CandidatePill value={snapshot.evaluation_cadence.workflow} />
            </DetailRow>
            <DetailRow label={t('cadence.schedule')}>
              <CandidatePill value={snapshot.evaluation_cadence.schedule} />
            </DetailRow>
            <DetailRow label={t('cadence.nextRun')}>
              {formatDateTime(snapshot.evaluation_cadence.next_scheduled_run_at)}
            </DetailRow>
            <DetailRow label={t('cadence.sourcePolicy')}>
              <CandidatePill value={snapshot.evaluation_cadence.primary_source_policy} />
            </DetailRow>
            <DetailRow label={t('cadence.reviewGate')}>
              <CandidatePill value={controlledReviewGate} muted />
            </DetailRow>
            <DetailRow label={t('cadence.triggerModes')}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
                {snapshot.evaluation_cadence.trigger_modes.map(mode => (
                  <CandidatePill key={mode} value={mode} />
                ))}
              </div>
            </DetailRow>
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
          gap: 18,
        }} className="agent-market-groups-grid">
          <CandidateGroup title={t('groups.baseline')} items={snapshot.candidate_groups.production_baseline} />
          <CandidateGroup title={t('groups.blocked')} items={snapshot.candidate_groups.replay_or_integration_blocked} muted />
          <CandidateGroup title={t('groups.watchOnly')} items={snapshot.candidate_groups.watch_only_candidates} />
          <CandidateGroup title={t('groups.prescreenReady')} items={snapshot.candidate_groups.watch_only_scorecard_prescreen_ready} />
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <ListChecks size={14} style={{ color: '#d97757' }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('decisionQueue.title')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-decision-grid">
            {snapshot.operator_decision_queue.map(item => {
              const activeBoundaries = Object.entries(item.approval_boundary)
                .filter(([, required]) => required)
                .map(([key]) => key)
              return (
                <div
                  key={item.candidate_id}
                  style={{
                    minWidth: 0,
                    padding: 12,
                    border: '0.5px solid #e0ddd4',
                    borderRadius: 7,
                    background: '#fff',
                    display: 'flex',
                    flexDirection: 'column',
                    gap: 9,
                  }}
                >
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, minWidth: 0 }}>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0 }}>
                      <span style={{
                        fontFamily: 'Syne, sans-serif',
                        fontSize: 13,
                        fontWeight: 700,
                        color: '#141413',
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                      }}>
                        {item.display_name}
                      </span>
                      <CandidatePill value={item.candidate_id} muted />
                    </div>
                    <span style={{
                      color: item.queue_status === 'baseline_protected' ? '#22C55E' : '#F59E0B',
                      fontFamily: "'DM Mono', monospace",
                      fontSize: 10,
                      fontWeight: 700,
                      whiteSpace: 'nowrap',
                    }}>
                      {t('decisionQueue.priority')} {item.priority}
                    </span>
                  </div>

                  <div style={{
                    display: 'grid',
                    gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
                    gap: 8,
                  }} className="agent-market-status-detail-grid">
                    <DetailRow label={t('decisionQueue.status')}>
                      <CandidatePill value={t(`decisionQueue.statuses.${item.queue_status}`)} />
                    </DetailRow>
                    <DetailRow label={t('decisionQueue.nextAction')}>
                      <CandidatePill value={item.recommended_action} muted />
                    </DetailRow>
                  </div>

                  <DetailRow label={t('decisionQueue.approvalBoundary')}>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
                      {activeBoundaries.length > 0 ? (
                        activeBoundaries.map(key => (
                          <CandidatePill key={key} value={t(`decisionQueue.boundaries.${key}`)} muted />
                        ))
                      ) : (
                        <CandidatePill value={t('decisionQueue.none')} muted />
                      )}
                    </div>
                  </DetailRow>

                  <DetailRow label={t('decisionQueue.riskNotes')}>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
                      {item.risk_notes.length > 0 ? (
                        item.risk_notes.map(note => <CandidatePill key={note} value={note} muted />)
                      ) : (
                        <CandidatePill value={t('decisionQueue.none')} muted />
                      )}
                    </div>
                  </DetailRow>

                  <DetailRow label={t('decisionQueue.evidence')}>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
                      {item.evidence_refs.length > 0 ? (
                        item.evidence_refs.map(ref => <CandidatePill key={ref} value={ref} />)
                      ) : (
                        <CandidatePill value={t('decisionQueue.none')} muted />
                      )}
                    </div>
                  </DetailRow>
                </div>
              )
            })}
          </div>
        </div>
      </GlassCard>

      <GlassCard variant="subtle" padding="md">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <ShieldCheck size={14} style={{ color: '#d97757' }} />
            <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
              {t('matrix.title')}
            </span>
          </div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
            gap: 10,
          }} className="agent-market-status-grid">
            {snapshot.candidate_statuses.map(candidate => {
              const evidence = [
                candidate.evidence.latest_smoke_model,
                candidate.evidence.latest_replay_summary,
                candidate.evidence.latest_smoke_gate,
              ].filter((item): item is string => Boolean(item))
              return (
                <div
                  key={candidate.candidate_id}
                  style={{
                    minWidth: 0,
                    padding: 12,
                    border: '0.5px solid #e0ddd4',
                    borderRadius: 7,
                    background: '#fff',
                    display: 'flex',
                    flexDirection: 'column',
                    gap: 9,
                  }}
                >
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, minWidth: 0 }}>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0 }}>
                      <span style={{
                        fontFamily: 'Syne, sans-serif',
                        fontSize: 13,
                        fontWeight: 700,
                        color: '#141413',
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                      }}>
                        {candidate.display_name}
                      </span>
                      <CandidatePill value={candidate.candidate_id} muted />
                    </div>
                    <span style={{
                      color: candidate.gate_status === 'production_baseline' ? '#22C55E' : '#F59E0B',
                      fontFamily: "'DM Mono', monospace",
                      fontSize: 10,
                      fontWeight: 700,
                      whiteSpace: 'nowrap',
                    }}>
                      {t(`matrix.gateStatuses.${candidate.gate_status}`)}
                    </span>
                  </div>

                  <div style={{
                    display: 'grid',
                    gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
                    gap: 8,
                  }} className="agent-market-status-detail-grid">
                    <DetailRow label={t('matrix.role')}>
                      <CandidatePill value={candidate.role || t('matrix.none')} />
                    </DetailRow>
                    <DetailRow label={t('matrix.score')}>
                      {candidate.score === null ? t('matrix.noScore') : candidate.score.toFixed(4)}
                    </DetailRow>
                    <DetailRow label={t('matrix.currentGate')}>
                      <CandidatePill value={candidate.current_gate || t('matrix.none')} />
                    </DetailRow>
                    <DetailRow label={t('matrix.nextGate')}>
                      <CandidatePill value={candidate.required_next_gate || t('matrix.none')} muted />
                    </DetailRow>
                    <DetailRow label={t('matrix.runtimeApprovals')}>
                      {t('matrix.noRuntimeApprovals')}
                    </DetailRow>
                    <DetailRow label={t('matrix.blockers')}>
                      {candidate.operator_blockers.length}
                    </DetailRow>
                  </div>

                  <DetailRow label={t('matrix.evidence')}>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, minWidth: 0 }}>
                      {evidence.length > 0 ? (
                        evidence.map(item => <CandidatePill key={item} value={item} />)
                      ) : (
                        <CandidatePill value={t('matrix.noEvidence')} muted />
                      )}
                    </div>
                  </DetailRow>
                </div>
              )
            })}
          </div>
        </div>
      </GlassCard>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)',
        gap: 12,
      }} className="agent-market-policy-grid">
        <GlassCard variant="subtle" padding="md" className="min-w-0">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
              <Ban size={14} style={{ color: '#d97757' }} />
              <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
                {t('policy.title')}
              </span>
            </div>
            <div style={{ display: 'grid', gap: 7 }}>
              <PolicyGate label={t('policy.replacement')} approved={summary.replacement_decisions_approved} />
              <PolicyGate label={t('policy.replay')} approved={summary.replay_candidates_approved} />
              <PolicyGate label={t('policy.sdk')} approved={summary.sdk_installations_approved} />
              <PolicyGate label={t('policy.paidApi')} approved={summary.paid_api_calls_approved} />
              <PolicyGate label={t('policy.production')} approved={summary.production_changes_approved} />
              <PolicyGate label={t('policy.shadowCanary')} approved={summary.shadow_or_canary_approved} />
            </div>
          </div>
        </GlassCard>

        <GlassCard variant="subtle" padding="md" className="min-w-0">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 13, minWidth: 0 }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 8 }}>
                <CheckCircle2 size={14} style={{ color: '#22C55E' }} />
                <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
                  {t('allowed.title')}
                </span>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {snapshot.next_allowed_actions.map(action => (
                  <CandidatePill key={action} value={action} />
                ))}
              </div>
            </div>

            <div style={{ minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 8 }}>
                <Lock size={14} style={{ color: '#F59E0B' }} />
                <span style={{ fontFamily: 'Syne, sans-serif', fontSize: 13, fontWeight: 700, color: '#141413' }}>
                  {t('forbidden.title')}
                </span>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {snapshot.forbidden_actions_without_new_approval.map(action => (
                  <CandidatePill key={action} value={action} muted />
                ))}
              </div>
            </div>
          </div>
        </GlassCard>
      </div>

      <style suppressHydrationWarning>{`
        @media (max-width: 900px) {
          .agent-market-kpi-grid,
          .agent-market-radar-metrics-grid,
          .agent-market-radar-contract-grid,
          .agent-market-radar-review-grid,
          .agent-market-radar-source-grid,
          .agent-market-radar-domain-grid,
          .agent-market-radar-rolling-grid,
          .agent-market-radar-role-grid,
          .agent-market-professional-metrics-grid,
          .agent-market-professional-judgment-grid,
          .agent-market-professional-evidence-grid,
          .agent-market-professional-mini-grid,
          .agent-market-report-metrics-grid,
          .agent-market-report-gate-grid,
          .agent-market-report-cadence-grid,
          .agent-market-report-workload-grid,
          .agent-market-report-analysis-grid,
          .agent-market-delivery-metrics-grid,
          .agent-market-delivery-gate-grid,
          .agent-market-delivery-packet-grid,
          .agent-market-delivery-guard-grid,
          .agent-market-delivery-receipt-grid,
          .agent-market-runtime-fixture-metrics-grid,
          .agent-market-runtime-fixture-truth-grid,
          .agent-market-runtime-fixture-card-grid,
          .agent-market-runtime-adapter-grid,
          .agent-market-runtime-verifier-grid,
          .agent-market-runtime-blocker-grid,
          .agent-market-health-grid,
          .agent-market-cadence-grid,
          .agent-market-decision-grid,
          .agent-market-status-grid,
          .agent-market-status-detail-grid,
          .agent-market-policy-grid,
          .agent-market-groups-grid {
            grid-template-columns: 1fr !important;
          }
        }
      `}</style>
    </div>
  )
}
