// =============================================================================
// WOOO AIOps - AwoooP 工作鏈路
// =============================================================================
// 將已完成、推進中、阻塞中的 AI 自動化工作對齊到真實前端觀測面。

"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import { useLocale, useTranslations } from "next-intl";
import {
  Activity,
  Archive,
  ArrowRight,
  CheckCircle2,
  ClipboardList,
  Database,
  Fingerprint,
  FileText,
  Gauge,
  GitBranch,
  GitPullRequest,
  ListChecks,
  Network,
  RefreshCw,
  SearchCheck,
  ShieldCheck,
  TriangleAlert,
} from "lucide-react";

import { Link } from "@/i18n/routing";
import { IncidentEvidenceHeader } from "@/components/awooop/incident-evidence-header";
import {
  AwoooPStatusChainPanel,
  type AwoooPStatusChain,
} from "@/components/awooop/status-chain";
import { cn } from "@/lib/utils";

type WorkStatus = "live" | "in_progress" | "blocked" | "watching";

type AutomationQualitySummary = {
  evaluated_total: number;
  verified_auto_repair_total: number;
  production_claim?: {
    can_claim_full_auto_repair?: boolean;
    reason?: string | null;
  };
  gate_failures?: Array<{ gate: string; total: number }>;
};

type GovernanceEventsResponse = {
  total: number;
  items?: Array<{ id: string; event_type: string; resolved: boolean }>;
};

type GovernanceQueueItem = {
  id: string;
  governance_event_id: string;
  event_type: string;
  dispatch_status: string;
  executor_type?: string | null;
  proposed_action?: string | null;
  playbook_id?: string | null;
  playbook_trust?: number | null;
  created_at?: string | null;
  dispatched_at?: string | null;
  started_at?: string | null;
  completed_at?: string | null;
  decision_path?: string | null;
  workflow_stage?: string | null;
  workflow_steps?: string[];
  next_action?: string | null;
  lead_agent?: string | null;
  support_agents?: string[];
  human_owner?: string | null;
  kb_draft_entry_id?: string | null;
  worker_status?: string | null;
  dry_run_plan_fingerprint?: string | null;
  archived_count?: number | null;
  stale_ratio_snapshot?: {
    stale_count?: number | null;
    total_count?: number | null;
    stale_ratio?: number | null;
    threshold?: number | null;
    stale_days?: number | null;
  } | null;
};

type GovernanceQueueResponse = {
  total: number;
  table_pending?: boolean;
  items?: GovernanceQueueItem[];
};

type RecentEventsResponse = {
  total: number;
  events?: Array<{ provider_event_id: string; is_duplicate: boolean }>;
};

type RecurrenceWorkItem = {
  work_item_id?: string | null;
  incident_id?: string | null;
  matched_incident_id?: string | null;
  auto_repair_id?: string | null;
  status?: string | null;
  kind?: string | null;
  next_step?: string | null;
  reason?: string | null;
  needs_human?: boolean | null;
};

type RecurrenceItem = {
  recurrence_key: string;
  provider?: string | null;
  alertname?: string | null;
  severity?: string | null;
  namespace?: string | null;
  target_resource?: string | null;
  latest_stage?: string | null;
  latest_provider_event_id?: string | null;
  latest_run_id?: string | null;
  latest_run_state?: string | null;
  latest_incident_id?: string | null;
  occurrence_total: number;
  duplicate_total: number;
  source_ref_total?: number;
  sentry_ref_total?: number;
  signoz_ref_total?: number;
  repair_summary?: {
    status?: string | null;
    latest_auto_repair_id?: string | null;
    latest_verification_result?: string | null;
    auto_repair_total?: number | null;
  } | null;
  work_item?: RecurrenceWorkItem | null;
  source_correlation_review?: {
    review_id?: string | null;
    decision?: string | null;
    review_status?: string | null;
    target_incident_id?: string | null;
    reviewer_id?: string | null;
    recorded_at?: string | null;
  } | null;
  source_correlation_apply?: {
    apply_id?: string | null;
    apply_status?: string | null;
    target_incident_id?: string | null;
    source_event_id?: string | null;
    source_event_provider_event_id?: string | null;
    recorded_at?: string | null;
  } | null;
};

type RecurrenceResponse = {
  project_id: string;
  summary: {
    source_event_total: number;
    recurrence_group_total: number;
    recurrent_group_total: number;
    duplicate_event_total: number;
    linked_run_total: number;
    auto_repair_linked_total?: number;
    verified_repair_group_total?: number;
    open_work_item_group_total?: number;
    manual_gate_group_total?: number;
    automation_gap_group_total?: number;
    failed_repair_group_total?: number;
    source_correlation_review_group_total?: number;
    source_correlation_decision_recorded_group_total?: number;
    source_correlation_applied_group_total?: number;
  };
  items: RecurrenceItem[];
};

type RecurrenceWorkItemActionResult = {
  schema_version?: string;
  work_item_id?: string | null;
  incident_id?: string | null;
  mode?: string | null;
  requested_mode?: string | null;
  handoff_kind?: string | null;
  handoff_status?: string | null;
  handoff_owner?: string | null;
  decision?: string | null;
  review_status?: string | null;
  review_record_status?: string | null;
  apply_status?: string | null;
  target_incident_id?: string | null;
  latest_provider_event_id?: string | null;
  source_event_id?: string | null;
  source_event_provider_event_id?: string | null;
  allowed?: boolean | null;
  executed?: boolean | null;
  safety_level?: string | null;
  writes_incident_state?: boolean | null;
  writes_source_event?: boolean | null;
  writes_auto_repair_result?: boolean | null;
  writes_ticket?: boolean | null;
  writes_approval_record?: boolean | null;
  creates_external_ticket?: boolean | null;
  deduplicated?: boolean | null;
  fingerprint?: string | null;
  verification_result_preview?: string | null;
  next_step?: string | null;
  checks?: Array<{ name?: string | null; passed?: boolean | null; detail?: string | null }>;
  current_state_summary?: {
    repair_status?: string | null;
    occurrence_total?: number | null;
    duplicate_total?: number | null;
    linked_run_total?: number | null;
    latest_stage?: string | null;
    latest_provider_event_id?: string | null;
  } | null;
  ticket_preview?: {
    would_create?: boolean | null;
    title?: string | null;
    labels?: string[] | null;
    body_preview?: string | null;
  } | null;
  replay_gate?: {
    status?: string | null;
    next_step?: string | null;
    can_runtime_replay?: boolean | null;
    execution_authorized?: boolean | null;
    repair_executed?: boolean | null;
    mutating_step_count?: number | null;
    supported_write_route_count?: number | null;
    unsupported_step_count?: number | null;
    approval_required_count?: number | null;
  } | null;
  approval_id?: string | null;
  approval?: {
    id?: string | null;
    status?: string | null;
    risk_level?: string | null;
    required_signatures?: number | null;
    current_signatures?: number | null;
    requested_by?: string | null;
    incident_id?: string | null;
    matched_playbook_id?: string | null;
  } | null;
  plan?: {
    step?: string | null;
    flywheel_node?: string | null;
    agent_id?: string | null;
    required_scope?: string | null;
    target_action?: string | null;
    writes?: string[] | null;
  } | null;
  read_model_route?: {
    agent_id?: string | null;
    tool_name?: string | null;
    required_scope?: string | null;
    flywheel_node?: string | null;
  } | null;
  history?: {
    recorded?: boolean | null;
    reason?: string | null;
    alert_operation_id?: string | null;
    timeline_event_id?: string | null;
  } | null;
};

type RecurrenceWorkItemActionState = {
  loading?:
    | "preview"
    | "dryRun"
    | "approval"
    | "handoff"
    | "acceptSource"
    | "rejectSource"
    | "applySource"
    | null;
  result?: RecurrenceWorkItemActionResult | null;
  error?: string | null;
};

type RecurrenceSourceFlowStatus =
  | "applied"
  | "reviewed"
  | "review"
  | "evidence"
  | "provider"
  | "waiting";

type SloResponse = {
  adr100?: {
    verification_coverage?: {
      remediation_queue?: {
        total: number;
        ready_for_ai: number;
        needs_human: number;
        items?: RemediationQueueItem[];
        by_status?: Array<{ name?: string | null; count?: number | null }>;
        by_action?: Array<{ name?: string | null; count?: number | null }>;
      };
    };
  };
};

type RemediationQueueItem = {
  work_item_id?: string | null;
  incident_id?: string | null;
  auto_repair_id?: string | null;
  alertname?: string | null;
  playbook_id?: string | null;
  failure_class?: string | null;
  verification_result?: string | null;
  remediation_status?: string | null;
  remediation_action?: string | null;
  remediation_owner?: string | null;
  remediation_reason?: string | null;
  source?: string | null;
  auto_created_at?: string | null;
  verification_collected_at?: string | null;
};

type RemediationQueue = NonNullable<
  NonNullable<NonNullable<SloResponse["adr100"]>["verification_coverage"]>["remediation_queue"]
>;

type RemediationHistoryItem = {
  work_item_id?: string | null;
  incident_id?: string | null;
  verification_result_preview?: string | null;
  agent_id?: string | null;
  tool_name?: string | null;
  required_scope?: string | null;
  writes_incident_state?: boolean | null;
  writes_auto_repair_result?: boolean | null;
  created_at?: string | null;
};

type RemediationHistoryResponse = {
  schema_version?: string;
  total?: number;
  items?: RemediationHistoryItem[];
};

type KnowledgeEntry = {
  id: string;
  title: string;
  content?: string | null;
  entry_type: string;
  category?: string | null;
  tags: string[];
  source?: string | null;
  status: string;
  created_by?: string | null;
  created_at?: string | null;
  updated_at?: string | null;
};

type KnowledgeListResponse = {
  total: number;
  items?: KnowledgeEntry[];
};

type KnowledgeReviewDraftGroup = {
  eventId: string;
  canonical: KnowledgeEntry;
  entries: KnowledgeEntry[];
  duplicateCount: number;
};

type KnowledgeReviewDraftDedupeGroup = {
  governance_event_id: string;
  canonical_entry_id: string;
  canonical_title: string;
  canonical_updated_at?: string | null;
  preferred_source: "dispatch_context" | "latest_review_draft";
  duplicate_entry_ids: string[];
  duplicate_count: number;
  total_entries: number;
  suggested_action: string;
  owner_action: string;
  writes_on_read: boolean;
  can_archive_without_owner_approval: boolean;
  archive_history?: GovernanceQueueItem[];
};

type KnowledgeReviewDraftDedupeResponse = {
  schema_version?: string;
  total_review_drafts: number;
  event_group_total: number;
  duplicate_draft_total: number;
  groups: KnowledgeReviewDraftDedupeGroup[];
  generated_at?: string | null;
};

type KnowledgeReviewDraftArchiveResponse = {
  schema_version?: string;
  governance_event_id: string;
  canonical_entry_id: string;
  requested_duplicate_entry_ids: string[];
  archived_entry_ids: string[];
  skipped_entry_ids: string[];
  would_archive_entry_ids: string[];
  status: "dry_run" | "archived" | "noop_already_archived";
  owner: string;
  owner_approved: boolean;
  dry_run: boolean;
  writes_km: boolean;
  writes_governance_audit: boolean;
  audit_dispatch_id?: string | null;
  stale_ratio_snapshot?: {
    stale_count: number;
    total_count: number;
    stale_ratio: number;
    threshold: number;
    stale_days: number;
  } | null;
  stale_ratio_recheck_status:
    | "dry_run"
    | "completed"
    | "already_active"
    | "not_requested";
  stale_ratio_recheck_dispatch_id?: string | null;
  dry_run_plan_fingerprint?: string | null;
  next_action: string;
  generated_at?: string | null;
};

type KnowledgeReviewDraftArchiveAction = {
  previewLoading: boolean;
  confirmLoading: boolean;
  previewResult: KnowledgeReviewDraftArchiveResponse | null;
  result: KnowledgeReviewDraftArchiveResponse | null;
  error: string | null;
};

type KnowledgeStaleCandidate = {
  entry_id: string;
  project_id: string;
  title: string;
  entry_type: string;
  category?: string | null;
  status: string;
  source?: string | null;
  updated_at?: string | null;
  stale_days: number;
  view_count: number;
  priority_score: number;
  priority_tier: "P0" | "P1" | "P2";
  recommended_action: "refresh_with_evidence" | "owner_review" | "archive_or_supersede";
  reasons: string[];
  correlation_sources: string[];
  related_incident_id?: string | null;
  related_playbook_id?: string | null;
  related_approval_id?: string | null;
  tags: string[];
  owner_review_dispatch_id?: string | null;
  owner_review_status?: string | null;
  owner_review_stage?: string | null;
  owner_review_next_action?: string | null;
};

type KnowledgeStaleCandidatesResponse = {
  schema_version?: string;
  project_id: string;
  total_stale: number;
  returned: number;
  threshold_days: number;
  writes_on_read: boolean;
  manual_review_required: boolean;
  items: KnowledgeStaleCandidate[];
  generated_at?: string | null;
};

type KnowledgeStaleOwnerReviewResponse = {
  schema_version?: string;
  entry_id: string;
  project_id: string;
  status: "dry_run" | "queued" | "already_queued";
  governance_event_id?: string | null;
  dispatch_id?: string | null;
  workflow_stage: string;
  recommended_action: "refresh_with_evidence" | "owner_review" | "archive_or_supersede";
  owner: string;
  owner_note?: string | null;
  writes_km: boolean;
  writes_governance_audit: boolean;
  next_action: string;
  generated_at?: string | null;
};

type KnowledgeStaleOwnerReviewAction = {
  loading: boolean;
  result: KnowledgeStaleOwnerReviewResponse | null;
  error: string | null;
};

type KnowledgeStaleOwnerReviewBatchItem = {
  entry_id: string;
  title: string;
  priority_tier: "P0" | "P1" | "P2";
  recommended_action: "refresh_with_evidence" | "owner_review" | "archive_or_supersede";
  status: "would_queue" | "queued" | "already_queued" | "skipped";
  reason?: string | null;
  governance_event_id?: string | null;
  dispatch_id?: string | null;
  workflow_stage: string;
};

type KnowledgeStaleOwnerReviewBatchResponse = {
  schema_version?: string;
  project_id: string;
  status: "dry_run" | "queued" | "noop_already_queued";
  owner: string;
  owner_note?: string | null;
  dry_run: boolean;
  priority_tiers: string[];
  requested_limit: number;
  candidate_count: number;
  queued_count: number;
  already_queued_count: number;
  skipped_count: number;
  batch_governance_event_id?: string | null;
  batch_dispatch_id?: string | null;
  workflow_stage: string;
  writes_km: boolean;
  writes_governance_audit: boolean;
  stale_ratio_snapshot?: {
    stale_count: number;
    total_count: number;
    stale_ratio: number;
    threshold: number;
    stale_days: number;
  } | null;
  dry_run_plan_fingerprint?: string | null;
  items: KnowledgeStaleOwnerReviewBatchItem[];
  next_action: string;
  generated_at?: string | null;
};

type KnowledgeStaleOwnerReviewBatchAction = {
  previewLoading: boolean;
  confirmLoading: boolean;
  previewResult: KnowledgeStaleOwnerReviewBatchResponse | null;
  result: KnowledgeStaleOwnerReviewBatchResponse | null;
  error: string | null;
};

type KnowledgeStaleOwnerReviewInboxItem = {
  dispatch_id: string;
  governance_event_id: string;
  entry_id: string;
  project_id: string;
  title: string;
  dispatch_status: string;
  workflow_stage: string;
  next_action?: string | null;
  owner?: string | null;
  owner_note?: string | null;
  batch_governance_event_id?: string | null;
  batch_dispatch_id?: string | null;
  priority_tier: "P0" | "P1" | "P2";
  priority_score: number;
  recommended_action: "refresh_with_evidence" | "owner_review" | "archive_or_supersede";
  stale_days: number;
  view_count: number;
  correlation_sources: string[];
  reasons: string[];
  related_incident_id?: string | null;
  related_playbook_id?: string | null;
  related_approval_id?: string | null;
  dry_run_plan_fingerprint?: string | null;
  queued_at?: string | null;
  started_at?: string | null;
  completed_at?: string | null;
};

type KnowledgeStaleOwnerReviewInboxResponse = {
  schema_version?: string;
  project_id: string;
  dispatch_status: string;
  total: number;
  returned: number;
  writes_on_read: boolean;
  manual_review_required: boolean;
  items: KnowledgeStaleOwnerReviewInboxItem[];
  generated_at?: string | null;
};

type KnowledgeStaleRatioSnapshot = {
  stale_count: number;
  total_count: number;
  stale_ratio: number;
  threshold: number;
  stale_days: number;
};

type KnowledgeStaleOwnerReviewBurnDownItem = {
  completion_dispatch_id: string;
  governance_event_id: string;
  source_dispatch_id?: string | null;
  recheck_dispatch_id?: string | null;
  entry_id?: string | null;
  project_id: string;
  dispatch_status: string;
  workflow_stage: string;
  review_outcome?: "refresh_with_evidence" | "archive" | "supersede" | null;
  owner?: string | null;
  completed_at?: string | null;
  stale_ratio_snapshot?: KnowledgeStaleRatioSnapshot | null;
  stale_count_delta?: number | null;
  stale_ratio_delta?: number | null;
  above_threshold?: boolean | null;
};

type KnowledgeStaleOwnerReviewBurnDownResponse = {
  schema_version?: string;
  project_id: string;
  burn_down_status: "above_threshold" | "at_or_below_threshold" | "no_data";
  current_snapshot?: KnowledgeStaleRatioSnapshot | null;
  entries_to_threshold: number;
  pending_owner_reviews: number;
  completed_owner_reviews: number;
  completion_audit_total: number;
  stale_ratio_recheck_total: number;
  latest_stale_count_delta?: number | null;
  latest_stale_ratio_delta?: number | null;
  writes_on_read: boolean;
  manual_review_required: boolean;
  returned: number;
  items: KnowledgeStaleOwnerReviewBurnDownItem[];
  generated_at?: string | null;
};

type KnowledgeStaleOwnerReviewCompletionQueueItem = {
  dispatch_id: string;
  governance_event_id: string;
  entry_id: string;
  project_id: string;
  title: string;
  dispatch_status: string;
  workflow_stage: string;
  readiness: "ready" | "blocked" | "completed" | "failed";
  recommended_completion_outcome: "refresh_with_evidence" | "archive" | "supersede";
  next_action: string;
  blockers: string[];
  required_owner_fields: string[];
  can_preview: boolean;
  can_confirm_after_preview: boolean;
  writes_km_on_confirm: boolean;
  owner?: string | null;
  owner_note?: string | null;
  batch_governance_event_id?: string | null;
  batch_dispatch_id?: string | null;
  priority_tier: "P0" | "P1" | "P2";
  priority_score: number;
  recommended_action: "refresh_with_evidence" | "owner_review" | "archive_or_supersede";
  stale_days: number;
  view_count: number;
  correlation_sources: string[];
  reasons: string[];
  related_incident_id?: string | null;
  related_playbook_id?: string | null;
  related_approval_id?: string | null;
  dry_run_plan_fingerprint?: string | null;
  queued_at?: string | null;
  started_at?: string | null;
  completed_at?: string | null;
};

type KnowledgeStaleOwnerReviewCompletionQueueResponse = {
  schema_version?: string;
  project_id: string;
  status_bucket: "all" | "ready" | "blocked" | "completed" | "failed" | "pending";
  priority_tiers?: string[];
  recommended_completion_outcome?: "all" | "refresh_with_evidence" | "archive" | "supersede";
  batch_governance_event_id?: string | null;
  can_preview?: boolean | null;
  total: number;
  returned: number;
  pending_count: number;
  ready_count: number;
  blocked_count: number;
  completed_count: number;
  failed_count: number;
  writes_on_read: boolean;
  manual_review_required: boolean;
  batch_writes_allowed: boolean;
  items: KnowledgeStaleOwnerReviewCompletionQueueItem[];
  generated_at?: string | null;
};

type KnowledgeStaleOwnerReviewCompletionBatchPreviewResponse = {
  schema_version?: string;
  project_id: string;
  status: "dry_run";
  owner: string;
  owner_note?: string | null;
  status_bucket: "all" | "ready" | "blocked" | "completed" | "failed" | "pending";
  priority_tiers: string[];
  recommended_completion_outcome: "all" | "refresh_with_evidence" | "archive" | "supersede";
  batch_governance_event_id?: string | null;
  requested_limit: number;
  candidate_count: number;
  previewable_count: number;
  blocked_count: number;
  completed_count: number;
  failed_count: number;
  writes_km: boolean;
  writes_governance_audit: boolean;
  batch_writes_allowed: boolean;
  manual_review_required: boolean;
  dry_run_plan_fingerprint: string;
  next_action: string;
  items: KnowledgeStaleOwnerReviewCompletionQueueItem[];
  generated_at?: string | null;
};

type KnowledgeStaleOwnerReviewCompletionBatchPreviewAction = {
  loading: boolean;
  result: KnowledgeStaleOwnerReviewCompletionBatchPreviewResponse | null;
  error: string | null;
};

type KnowledgeStaleOwnerReviewCompleteResponse = {
  schema_version?: string;
  entry_id: string;
  project_id: string;
  status: "dry_run" | "completed" | "already_completed";
  review_outcome: "refresh_with_evidence" | "archive" | "supersede";
  governance_event_id: string;
  dispatch_id: string;
  audit_dispatch_id?: string | null;
  stale_ratio_recheck_dispatch_id?: string | null;
  workflow_stage: string;
  owner: string;
  owner_approved: boolean;
  dry_run: boolean;
  writes_km: boolean;
  writes_governance_audit: boolean;
  stale_ratio_snapshot?: KnowledgeStaleRatioSnapshot | null;
  dry_run_plan_fingerprint?: string | null;
  next_action: string;
  generated_at?: string | null;
};

type KnowledgeStaleOwnerReviewCompleteAction = {
  previewLoading: boolean;
  confirmLoading: boolean;
  previewResult: KnowledgeStaleOwnerReviewCompleteResponse | null;
  result: KnowledgeStaleOwnerReviewCompleteResponse | null;
  error: string | null;
};

type DriftFingerprintState = {
  schema_version?: string;
  namespace?: string;
  fingerprint?: string;
  latest_report_id?: string;
  latest_status?: string;
  summary?: string;
  high_count?: number;
  medium_count?: number;
  info_count?: number;
  occurrences_12h?: number;
  fsm_state?: string;
  operator_stage?: string;
  next_step?: string;
  open_pr?: {
    number?: number | string | null;
    title?: string | null;
    state?: string | null;
    merged?: boolean | null;
    mergeable?: boolean | null;
    html_url?: string | null;
    url?: string | null;
    file_count?: number | null;
    commit_count?: number | null;
    is_zero_diff?: boolean | null;
    lookup_status?: string | null;
    lookup_error?: string | null;
  } | null;
  latest_handoff?: {
    handoff_kind?: string | null;
    handoff_status?: string | null;
    pr_url?: string | null;
    created_at?: string | null;
    lookup_error?: string | null;
  } | null;
  latest_remediation?: {
    remediation_kind?: string | null;
    remediation_status?: string | null;
    remediated_report_id?: string | null;
    verification_report_id?: string | null;
    verification_summary?: {
      report_id?: string | null;
      status?: string | null;
      summary?: string | null;
      high_count?: number | null;
      medium_count?: number | null;
      info_count?: number | null;
      is_no_drift?: boolean | null;
    } | null;
    note?: string | null;
    created_at?: string | null;
    lookup_error?: string | null;
  } | null;
  p0_escalation?: {
    suppresses_repeated_p0?: boolean | null;
    dedup_window_hours?: number | null;
  } | null;
  writes_incident_state?: boolean | null;
  writes_auto_repair_result?: boolean | null;
  writes_drift_status?: boolean | null;
  writes_ticket?: boolean | null;
  creates_external_ticket?: boolean | null;
};

type DriftFingerprintHandoffResult = DriftFingerprintState & {
  handoff_kind?: string | null;
  handoff_status?: string | null;
  history?: {
    recorded?: boolean | null;
    alert_operation_id?: string | null;
    timeline_event_id?: string | null;
    reason?: string | null;
  } | null;
};

type KmStaleCallbackOwnerReviewWorkItem = {
  schema_version?: string;
  work_item_id?: string | null;
  kind?: string | null;
  status?: string | null;
  project_id?: string | null;
  incident_id?: string | null;
  reason?: string | null;
  title?: string | null;
  next_step?: string | null;
  target_surface?: string | null;
  target_href?: string | null;
  work_item_href?: string | null;
  triage?: KmStaleCallbackOwnerReviewTriage | null;
  writes_on_read?: boolean | null;
  manual_review_required?: boolean | null;
  batch_writes_allowed?: boolean | null;
};

type KmStaleCallbackOwnerReviewTriage = {
  schema_version?: string;
  flow_stage?: string | null;
  ai_lead_agent?: string | null;
  supporting_agents?: string[];
  automation_state?: string | null;
  safe_to_auto_repair?: boolean | null;
  blocking_reason?: string | null;
  matching_strategy?: string | null;
  already_done?: string[];
  next_actions?: string[];
};

type KmStaleCallbackCompletionSummary = {
  schema_version?: string;
  status?: string | null;
  project_id?: string | null;
  incident_id?: string | null;
  reason?: string | null;
  pending_count?: number;
  ready_count?: number;
  blocked_count?: number;
  completed_count?: number;
  failed_count?: number;
  work_item?: KmStaleCallbackOwnerReviewWorkItem | null;
};

type CallbackReplyWorkItemEvent = {
  message_id: string;
  project_id: string;
  status: string;
  action?: string | null;
  incident_id?: string | null;
  event_at?: string | null;
  km_stale_completion_summary?: KmStaleCallbackCompletionSummary | null;
};

type CallbackReplyAuditSummary = {
  outbound_reply_markup_missing_trace_ref_total?: number;
  outbound_reply_markup_missing_trace_ref_recent_1h_total?: number;
  outbound_reply_markup_missing_trace_ref_recent_24h_total?: number;
  outbound_reply_markup_missing_trace_ref_latest_sent_at?: string | null;
  outbound_reply_markup_trace_ref_gap_status?: string | null;
  outbound_reply_markup_trace_ref_gap_next_action?: string | null;
  outbound_reply_markup_trace_ref_after_gap_total?: number;
  outbound_reply_markup_trace_ref_after_gap_first_sent_at?: string | null;
  outbound_reply_markup_trace_ref_after_gap_latest_sent_at?: string | null;
  outbound_reply_markup_trace_ref_gap_recovery_status?: string | null;
};

type CallbackRepliesWorkItemResponse = {
  items?: CallbackReplyWorkItemEvent[];
  total: number;
  page: number;
  per_page: number;
  summary?: CallbackReplyAuditSummary | null;
};

type CallbackTraceRecoveryActionKey =
  | "unavailable"
  | "closed"
  | "investigateActiveGap"
  | "verifyInstrumentation"
  | "waitDecay"
  | "observeRecovery";

type CallbackTraceRecoveryAction = {
  actionKey: CallbackTraceRecoveryActionKey;
  humanRequired: boolean;
};

type AiRouteRepairEvidence = {
  target_resource?: string | null;
  access_blockers?: string[];
  source_ref_count?: number | null;
  work_item?: {
    work_item_id?: string | null;
    status?: string | null;
    next_step?: string | null;
    reason?: string | null;
    owner?: string | null;
    target_href?: string | null;
    needs_human?: boolean | null;
  } | null;
  playbook_recommendation?: {
    playbook_id?: string | null;
    status?: string | null;
    safe_to_auto_execute?: boolean | null;
    requires_approval?: boolean | null;
    steps?: Array<{ step?: string | null; scope?: string | null; mode?: string | null }>;
  } | null;
  owner_action?: {
    lead_agent?: string | null;
    supporting_agents?: string[];
    human_owner?: string | null;
    automation_state?: string | null;
    next_step?: string | null;
    playbook_id?: string | null;
    safe_to_auto_repair?: boolean | null;
    blocking_reason?: string | null;
  } | null;
};

type AiRouteStatusResponse = {
  lane_mode?: string | null;
  selected_provider?: string | null;
  skipped_lanes?: Array<{ provider_name?: string | null }>;
  operator_action?: {
    action?: string | null;
    human_required?: boolean | null;
  } | null;
  repair_evidence?: AiRouteRepairEvidence | null;
};

type Telemetry = {
  quality: AutomationQualitySummary | null;
  governanceEvents: GovernanceEventsResponse | null;
  governanceQueue: GovernanceQueueResponse | null;
  governanceKnowledgeQueue: GovernanceQueueResponse | null;
  knowledgeReviewDrafts: KnowledgeListResponse | null;
  knowledgeReviewDedupe: KnowledgeReviewDraftDedupeResponse | null;
  knowledgeStaleCandidates: KnowledgeStaleCandidatesResponse | null;
  knowledgeStaleOwnerReviews: KnowledgeStaleOwnerReviewInboxResponse | null;
  knowledgeStaleOwnerReviewBurnDown: KnowledgeStaleOwnerReviewBurnDownResponse | null;
  knowledgeStaleOwnerReviewCompletionQueue: KnowledgeStaleOwnerReviewCompletionQueueResponse | null;
  channelEvents: RecentEventsResponse | null;
  eventRecurrence: RecurrenceResponse | null;
  slo: SloResponse | null;
  remediationHistory: RemediationHistoryResponse | null;
  driftFingerprintState: DriftFingerprintState | null;
  callbackReplies: CallbackRepliesWorkItemResponse | null;
  statusChain: AwoooPStatusChain | null;
  incidentTimeline: IncidentTimelineResponse | null;
  aiRouteStatus: AiRouteStatusResponse | null;
};

type IncidentTimelineEvent = {
  stage: string;
  status: string;
  title: string;
  description?: string | null;
  actor?: string | null;
  timestamp?: string | null;
  source_table?: string | null;
  data?: Record<string, unknown>;
};

type IncidentTimelineStage = IncidentTimelineEvent & {
  label: string;
  events?: IncidentTimelineEvent[];
};

type IncidentTimelineResponse = {
  incident_id: string;
  title: string;
  status: string;
  severity: string;
  started_at?: string | null;
  updated_at?: string | null;
  resolved_at?: string | null;
  affected_services?: string[];
  approval_ids?: string[];
  timeline: IncidentTimelineStage[];
  events: IncidentTimelineEvent[];
  ascii_timeline: string;
  reconciliation?: Record<string, unknown>;
};

type WorkItem = {
  id: string;
  phase: string;
  status: WorkStatus;
  surfaceKey: string;
  source: string;
  gateKey: string;
  evidence: string;
  evidenceDetails?: string[];
  href: string;
};

type RepairCandidateDraftFocus = {
  workItemId: string;
  projectId: string;
  incidentId: string | null;
  lane: string;
};

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? "";

const REPAIR_CANDIDATE_DRAFT_PREFIX = "repair-candidate-draft";
const REPAIR_CANDIDATE_DRAFT_REQUIRED_FIELDS = [
  "alertname",
  "target_selector",
  "mcp_evidence_refs",
  "repair_command",
  "rollback_command",
  "verifier_plan",
  "owner_review",
] as const;

const REPAIR_CANDIDATE_DRAFT_BLOCKED_OPERATIONS = [
  "auto_execute",
  "approve_no_action_as_repair",
  "generic_fallback_repair",
] as const;

const statusConfig: Record<WorkStatus, { className: string; icon: typeof Activity }> = {
  live: {
    className: "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
    icon: Activity,
  },
  in_progress: {
    className: "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
    icon: GitBranch,
  },
  blocked: {
    className: "border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]",
    icon: TriangleAlert,
  },
  watching: {
    className: "border-[#9bb6d9] bg-[#eef5ff] text-[#1f5b9b]",
    icon: Gauge,
  },
};

async function fetchJson<T>(url: string, timeoutMs = 8000): Promise<T | null> {
  const controller = new AbortController();
  const timeout = window.setTimeout(() => controller.abort(), timeoutMs);
  try {
    const response = await fetch(url, {
      cache: "no-store",
      signal: controller.signal,
    });
    if (!response.ok) return null;
    return (await response.json()) as T;
  } catch {
    return null;
  } finally {
    window.clearTimeout(timeout);
  }
}

async function postJson<T>(
  url: string,
  body: Record<string, unknown>,
  timeoutMs = 8000
): Promise<T | null> {
  const controller = new AbortController();
  const timeout = window.setTimeout(() => controller.abort(), timeoutMs);
  try {
    const response = await fetch(url, {
      method: "POST",
      cache: "no-store",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
      signal: controller.signal,
    });
    if (!response.ok) return null;
    return (await response.json()) as T;
  } catch {
    return null;
  } finally {
    window.clearTimeout(timeout);
  }
}

function hasGateFailure(summary: AutomationQualitySummary | null, gate: string) {
  return Boolean(summary?.gate_failures?.some((row) => row.gate === gate && row.total > 0));
}

function routeLabel(item?: RemediationHistoryItem | null) {
  if (!item) return "--";
  const route = [item.agent_id, item.tool_name, item.required_scope]
    .filter(Boolean)
    .map(String)
    .join("/");
  return route || "--";
}

function recurrenceOpenItems(recurrence: RecurrenceResponse | null) {
  return (recurrence?.items ?? []).filter((item) => item.work_item?.status === "open");
}

function firstIncidentId(...candidates: Array<string | null | undefined>) {
  return candidates.find((candidate) => Boolean(candidate?.trim()))?.trim() ?? null;
}

function parseRepairCandidateDraftWorkItemId(
  workItemId: string | null,
  queryIncidentId: string | null,
  fallbackProjectId: string
): RepairCandidateDraftFocus | null {
  if (!workItemId?.startsWith(`${REPAIR_CANDIDATE_DRAFT_PREFIX}:`)) return null;
  const [, parsedProjectId, parsedIncidentId, ...laneParts] = workItemId.split(":");
  const projectId = parsedProjectId?.trim() || fallbackProjectId;
  const incidentId = firstIncidentId(queryIncidentId, parsedIncidentId);
  const lane = laneParts.join(":").trim() || "owner_review_playbook_trust_gate";
  return {
    workItemId,
    projectId,
    incidentId,
    lane,
  };
}

function selectStatusChainIncidentId(
  focusedIncidentId: string | null,
  remediationHistory: RemediationHistoryResponse | null,
  recurrence: RecurrenceResponse | null
) {
  const latestRemediationIncident = remediationHistory?.items?.find(
    (item) => Boolean(item.incident_id?.trim())
  )?.incident_id;
  const latestOpenRecurrence = recurrenceOpenItems(recurrence)[0] ?? null;
  const latestRecurrenceIncident = recurrence?.items?.find(
    (item) => Boolean(item.latest_incident_id?.trim() || item.work_item?.incident_id?.trim())
  );

  return firstIncidentId(
    focusedIncidentId,
    latestRemediationIncident,
    latestOpenRecurrence?.latest_incident_id,
    latestOpenRecurrence?.work_item?.incident_id,
    latestRecurrenceIncident?.latest_incident_id,
    latestRecurrenceIncident?.work_item?.incident_id
  );
}

function auditStatusClass(status?: string | null) {
  if (status === "success" || status === "completed" || status === "resolved") {
    return "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]";
  }
  if (status === "warning" || status === "warn" || status === "pending" || status === "info") {
    return "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]";
  }
  if (status === "failed" || status === "error" || status === "blocked") {
    return "border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]";
  }
  return "border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]";
}

function auditStatusLabelKey(status?: string | null) {
  if (
    status === "success" ||
    status === "completed" ||
    status === "warning" ||
    status === "warn" ||
    status === "failed" ||
    status === "error" ||
    status === "blocked" ||
    status === "pending" ||
    status === "info" ||
    status === "skipped"
  ) {
    return status;
  }
  return "unknown";
}

function recurrenceRepairStatusKey(status?: string | null) {
  if (
    status === "auto_repair_verified" ||
    status === "auto_repair_succeeded_unverified" ||
    status === "auto_repair_failed" ||
    status === "auto_repair_recorded" ||
    status === "manual_gate" ||
    status === "investigating" ||
    status === "run_completed_no_repair" ||
    status === "source_correlation_review" ||
    status === "source_correlation_accepted" ||
    status === "source_correlation_rejected" ||
    status === "no_repair_record"
  ) {
    return status;
  }
  return "unknown";
}

function recurrenceActionModeKey(mode?: string | null) {
  if (
    mode === "auto" ||
    mode === "ticket" ||
    mode === "reverify" ||
    mode === "approval_review" ||
    mode === "observe"
  ) {
    return mode;
  }
  return "unknown";
}

function recurrencePreviewKey(preview?: string | null) {
  if (
    preview === "ticket_preview_ready" ||
    preview === "reverify_preview_ready" ||
    preview === "approval_review_required" ||
    preview === "observe_only" ||
    preview === "blocked"
  ) {
    return preview;
  }
  return "unknown";
}

function recurrenceHandoffStatusKey(status?: string | null) {
  if (
    status === "ready_to_record" ||
    status === "recorded" ||
    status === "record_failed" ||
    status === "blocked"
  ) {
    return status;
  }
  return "unknown";
}

function recurrenceHandoffKindKey(kind?: string | null) {
  if (kind === "ticket_proposal" || kind === "manual_review") {
    return kind;
  }
  return "unknown";
}

function sourceReviewDecisionKey(decision?: string | null) {
  if (
    decision === "accepted" ||
    decision === "rejected" ||
    decision === "needs_more_evidence"
  ) {
    return decision;
  }
  return "unknown";
}

function sourceReviewRecordStatusKey(status?: string | null) {
  if (
    status === "recorded" ||
    status === "record_failed" ||
    status === "blocked" ||
    status === "accepted" ||
    status === "rejected" ||
    status === "needs_more_evidence"
  ) {
    return status;
  }
  return "unknown";
}

function driftFsmStateKey(state?: string | null) {
  if (
    state === "pending_human" ||
    state === "pending_human_repeated" ||
    state === "pr_open_zero_diff" ||
    state === "pr_open_waiting_review" ||
    state === "pr_merged_unverified" ||
    state === "handoff_recorded" ||
    state === "no_drift_verified" ||
    state === "remediated_verified" ||
    state === "remediation_executed_unverified" ||
    state === "remediation_verification_failed" ||
    state === "adopted_unverified" ||
    state === "rolled_back" ||
    state === "acknowledged" ||
    state === "ignored"
  ) {
    return state;
  }
  return "unknown";
}

function driftNextStepKey(step?: string | null) {
  if (
    step === "close_zero_diff_pr_and_prepare_real_yaml_patch" ||
    step === "review_pr_then_merge_or_reject" ||
    step === "verify_git_baseline_then_mark_adopted" ||
    step === "operator_review_handoff_and_execute_manual_plan" ||
    step === "run_verification_scan_then_record_result" ||
    step === "open_manual_investigation_with_failed_verification" ||
    step === "verify_k8s_matches_git_baseline" ||
    step === "confirm_no_repeat_after_rollback" ||
    step === "monitor_for_recurrence" ||
    step === "retry_pr_lookup_then_review_drift" ||
    step === "manual_investigation_or_ansible_check_mode"
  ) {
    return step;
  }
  return "unknown";
}

function driftRemediationKindKey(kind?: string | null) {
  if (
    kind === "live_env_rollback" ||
    kind === "git_adopted" ||
    kind === "git_rollback" ||
    kind === "zero_diff_pr_cleanup" ||
    kind === "manual_noop"
  ) {
    return kind;
  }
  return "unknown";
}

function driftRemediationStatusKey(status?: string | null) {
  if (
    status === "executed_unverified" ||
    status === "verified_no_drift" ||
    status === "verification_failed" ||
    status === "record_failed" ||
    status === "lookup_failed"
  ) {
    return status;
  }
  return "unknown";
}

function driftStatusForWorkItem(state: DriftFingerprintState | null): WorkStatus {
  const fsm = state?.fsm_state;
  if (!state) return "blocked";
  if (fsm === "no_drift_verified" || fsm === "remediated_verified") return "live";
  if (fsm === "remediation_executed_unverified") return "in_progress";
  if (fsm === "remediation_verification_failed") return "blocked";
  if (fsm === "adopted_unverified" || fsm === "pr_merged_unverified") return "in_progress";
  if (fsm === "rolled_back" || fsm === "acknowledged" || fsm === "ignored") return "watching";
  if (fsm === "pr_open_waiting_review" || fsm === "handoff_recorded") return "in_progress";
  return "blocked";
}

function governanceKmDispatchStatusKey(status?: string | null) {
  if (
    status === "pending" ||
    status === "dispatched" ||
    status === "executing" ||
    status === "succeeded" ||
    status === "failed" ||
    status === "skipped" ||
    status === "cancelled"
  ) {
    return status;
  }
  return "unknown";
}

function governanceKmStageKey(stage?: string | null) {
  if (
    stage === "queued_kb_healthcheck" ||
    stage === "detected" ||
    stage === "ai_analyzed" ||
    stage === "draft_km_updates" ||
    stage === "batch_owner_review_previewed" ||
    stage === "batch_owner_review_queued" ||
    stage === "batch_noop_already_queued" ||
    stage === "waiting_owner_review" ||
    stage === "owner_updates_or_archives_km" ||
    stage === "km_writeback_after_approval" ||
    stage === "km_archive_after_approval" ||
    stage === "km_supersede_after_approval" ||
    stage === "stale_ratio_recheck" ||
    stage === "owner_approved_duplicate_archive" ||
    stage === "km_duplicate_archive_after_owner_approval" ||
    stage === "km_governance_rechecked" ||
    stage === "km_governance_close_or_continue" ||
    stage === "needs_manual_km_triage" ||
    stage === "cancelled" ||
    stage === "queued_for_review" ||
    stage === "dispatched" ||
    stage === "executing" ||
    stage === "completed" ||
    stage === "failed" ||
    stage === "skipped"
  ) {
    return stage;
  }
  return "unknown";
}

function governanceKmStatusForWorkItem(queue: GovernanceQueueResponse | null): WorkStatus {
  if (queue === null || queue.table_pending) return "blocked";
  const items = queue.items ?? [];
  if (items.some((item) => ["pending", "dispatched", "executing"].includes(item.dispatch_status))) {
    return "in_progress";
  }
  if (items.some((item) => item.dispatch_status === "skipped" || item.dispatch_status === "failed")) {
    return "blocked";
  }
  if (items.some((item) => item.dispatch_status === "succeeded")) {
    return "live";
  }
  return "watching";
}

function governanceEventIdForDraft(entry: KnowledgeEntry) {
  const tag = entry.tags.find((item) => item.startsWith("governance_event:"));
  return tag?.replace("governance_event:", "") || null;
}

function groupKnowledgeReviewDrafts(
  reviewDrafts: KnowledgeListResponse | null,
  queueItems: GovernanceQueueItem[] = []
): KnowledgeReviewDraftGroup[] {
  const entries = reviewDrafts?.items ?? [];
  const preferredDraftByEvent = new Map<string, string>();
  for (const item of queueItems) {
    if (item.governance_event_id && item.kb_draft_entry_id) {
      preferredDraftByEvent.set(item.governance_event_id, item.kb_draft_entry_id);
    }
  }

  const groups = new Map<string, KnowledgeEntry[]>();
  for (const entry of entries) {
    const eventId = governanceEventIdForDraft(entry);
    if (!eventId) continue;
    groups.set(eventId, [...(groups.get(eventId) ?? []), entry]);
  }

  return Array.from(groups.entries()).map(([eventId, draftEntries]) => {
    const sorted = [...draftEntries].sort((a, b) =>
      String(b.updated_at ?? b.created_at ?? "").localeCompare(
        String(a.updated_at ?? a.created_at ?? "")
      )
    );
    const preferredId = preferredDraftByEvent.get(eventId);
    const canonical = sorted.find((entry) => entry.id === preferredId) ?? sorted[0];
    return {
      eventId,
      canonical,
      entries: sorted,
      duplicateCount: Math.max(sorted.length - 1, 0),
    };
  });
}

function draftGroupForQueueItem(
  item: GovernanceQueueItem,
  groups: KnowledgeReviewDraftGroup[]
) {
  return groups.find((group) => group.eventId === item.governance_event_id) ?? null;
}

function draftDedupeGroupForQueueItem(
  item: GovernanceQueueItem,
  groups: KnowledgeReviewDraftDedupeGroup[]
) {
  return groups.find((group) => group.governance_event_id === item.governance_event_id) ?? null;
}

function kmArchiveTraceForDedupeGroup(
  group: KnowledgeReviewDraftDedupeGroup,
  queueItems: GovernanceQueueItem[]
) {
  if (group.archive_history?.length) {
    return group.archive_history.slice(0, 3);
  }
  return queueItems
    .filter((item) =>
      item.governance_event_id === group.governance_event_id &&
      (
        item.executor_type === "hermes_km_review_dedupe_owner_archive" ||
        item.executor_type === "hermes_km_stale_ratio_recheck"
      )
    )
    .sort((a, b) =>
      String(b.completed_at ?? b.started_at ?? b.created_at ?? "").localeCompare(
        String(a.completed_at ?? a.started_at ?? a.created_at ?? "")
      )
    )
    .slice(0, 3);
}

function kmArchiveExecutorKey(executorType?: string | null) {
  if (
    executorType === "hermes_km_review_dedupe_owner_archive" ||
    executorType === "hermes_km_stale_ratio_recheck"
  ) {
    return executorType;
  }
  return "unknown";
}

function kmDedupeActionKey(action?: string | null) {
  if (
    action === "owner_review_canonical_then_archive_duplicates" ||
    action === "review_canonical_and_archive_duplicate_drafts"
  ) {
    return action;
  }
  return "unknown";
}

function groupArchiveStatusKey(status?: string | null) {
  if (
    status === "dry_run" ||
    status === "archived" ||
    status === "noop_already_archived"
  ) {
    return status;
  }
  return "unknown";
}

function staleRatioRecheckStatusKey(status?: string | null) {
  if (
    status === "dry_run" ||
    status === "completed" ||
    status === "already_active" ||
    status === "not_requested"
  ) {
    return status;
  }
  return "unknown";
}

function sourceApplyStatusKey(status?: string | null) {
  if (
    status === "ready_to_apply" ||
    status === "applied" ||
    status === "partial" ||
    status === "record_failed" ||
    status === "blocked"
  ) {
    return status;
  }
  return "unknown";
}

function recurrenceSourceFlowStatus({
  item,
  actionResult,
  sourceApplyStatus,
  sourceDecision,
  reviewStatus,
}: {
  item: RecurrenceItem;
  actionResult?: RecurrenceWorkItemActionResult | null;
  sourceApplyStatus: string;
  sourceDecision: string;
  reviewStatus: string;
}): RecurrenceSourceFlowStatus {
  const hasAppliedLink =
    sourceApplyStatus === "applied" ||
    sourceApplyStatus === "partial" ||
    Boolean(
      actionResult?.source_event_provider_event_id ||
        item.source_correlation_apply?.source_event_provider_event_id
    );
  if (hasAppliedLink) return "applied";

  const hasRecordedReview =
    sourceDecision !== "unknown" ||
    reviewStatus === "recorded" ||
    reviewStatus === "accepted" ||
    reviewStatus === "rejected" ||
    reviewStatus === "needs_more_evidence";
  if (hasRecordedReview) return "reviewed";

  if (item.work_item?.kind === "source_correlation_review" || item.source_correlation_review) {
    return "review";
  }

  const sourceRefTotal =
    (item.source_ref_total ?? 0) +
    (item.sentry_ref_total ?? 0) +
    (item.signoz_ref_total ?? 0);
  if (sourceRefTotal > 0) return "evidence";
  if (item.latest_provider_event_id) return "provider";
  return "waiting";
}

function recurrenceSourceFlowClass(status: RecurrenceSourceFlowStatus) {
  if (status === "applied") return "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]";
  if (status === "reviewed") return "border-[#9bb6d9] bg-[#eef5ff] text-[#1f5b9b]";
  if (status === "review" || status === "evidence") {
    return "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]";
  }
  if (status === "provider") return "border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]";
  return "border-[#e0ddd4] bg-white text-[#77736a]";
}

function recurrenceSourceFlowIcon(status: RecurrenceSourceFlowStatus) {
  if (status === "applied") return ShieldCheck;
  if (status === "reviewed") return GitBranch;
  if (status === "review" || status === "evidence") return SearchCheck;
  if (status === "provider") return Network;
  return Database;
}

function formatStaleRatio(value: number) {
  return `${(value * 100).toFixed(1)}%`;
}

function formatSignedNumber(value: number | null | undefined) {
  if (value === null || value === undefined) return "--";
  return value > 0 ? `+${value}` : String(value);
}

function formatSignedRatio(value: number | null | undefined) {
  if (value === null || value === undefined) return "--";
  const formatted = formatStaleRatio(Math.abs(value));
  if (value > 0) return `+${formatted}`;
  if (value < 0) return `-${formatted}`;
  return formatted;
}

function kmStaleReasonKey(value: string | null | undefined) {
  switch (value) {
    case "linked_incident":
    case "linked_approval":
    case "linked_playbook":
    case "sentry_context":
    case "signoz_context":
    case "anti_pattern_priority":
    case "auto_runbook_review_needed":
    case "ai_extracted_needs_owner_check":
    case "already_waiting_review":
    case "viewed_by_operator":
    case "older_than_30_days":
    case "stale_by_age":
      return value;
    default:
      return "unknown";
  }
}

function kmStaleActionKey(value: string | null | undefined) {
  switch (value) {
    case "refresh_with_evidence":
    case "owner_review":
    case "archive_or_supersede":
      return value;
    default:
      return "owner_review";
  }
}

function kmStaleReviewStatusKey(value: string | null | undefined) {
  switch (value) {
    case "dry_run":
    case "queued":
    case "already_queued":
      return value;
    default:
      return "queued";
  }
}

function kmStaleBatchStatusKey(value: string | null | undefined) {
  switch (value) {
    case "dry_run":
    case "queued":
    case "noop_already_queued":
      return value;
    default:
      return "unknown";
  }
}

function kmStaleBatchItemStatusKey(value: string | null | undefined) {
  switch (value) {
    case "would_queue":
    case "queued":
    case "already_queued":
    case "skipped":
      return value;
    default:
      return "unknown";
  }
}

function kmStaleCompletionReadinessKey(value: string | null | undefined) {
  switch (value) {
    case "ready":
    case "blocked":
    case "completed":
    case "failed":
      return value;
    default:
      return "blocked";
  }
}

function kmStaleReviewCompleteStatusKey(value: string | null | undefined) {
  switch (value) {
    case "dry_run":
    case "completed":
    case "already_completed":
      return value;
    default:
      return "unknown";
  }
}

function kmStaleReviewOutcomeForCandidate(
  candidate: KnowledgeStaleCandidate
): "refresh_with_evidence" | "archive" | "supersede" {
  if (candidate.recommended_action === "archive_or_supersede") return "archive";
  return "refresh_with_evidence";
}

function staleCandidateFromOwnerReviewItem(
  item: KnowledgeStaleOwnerReviewInboxItem | KnowledgeStaleOwnerReviewCompletionQueueItem
): KnowledgeStaleCandidate {
  return {
    entry_id: item.entry_id,
    project_id: item.project_id,
    title: item.title,
    entry_type: "auto_runbook",
    status: "review",
    stale_days: item.stale_days,
    view_count: item.view_count,
    priority_score: item.priority_score,
    priority_tier: item.priority_tier,
    recommended_action: item.recommended_action,
    reasons: item.reasons,
    correlation_sources: item.correlation_sources,
    related_incident_id: item.related_incident_id,
    related_playbook_id: item.related_playbook_id,
    related_approval_id: item.related_approval_id,
    tags: [],
    owner_review_dispatch_id: item.dispatch_id,
    owner_review_status: item.dispatch_status,
    owner_review_stage: item.workflow_stage,
    owner_review_next_action: item.next_action,
  };
}

function ownerReviewRailTone(state: "done" | "ready" | "waiting" | "blocked") {
  switch (state) {
    case "done":
      return "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]";
    case "ready":
      return "border-[#9bb6d9] bg-[#eef5ff] text-[#1f5b9b]";
    case "blocked":
      return "border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]";
    default:
      return "border-[#d8d3c7] bg-white text-[#5f5b52]";
  }
}

function KnowledgeOwnerReviewSingleItemRail({
  candidate,
  action,
  queuedDispatchId,
  canPreview,
  canConfirmAfterPreview = true,
  writesKmOnConfirm = true,
  requiredOwnerFields = [],
  blockers = [],
  onPreview,
  onConfirm,
}: {
  candidate: KnowledgeStaleCandidate;
  action?: KnowledgeStaleOwnerReviewCompleteAction;
  queuedDispatchId?: string | null;
  canPreview: boolean;
  canConfirmAfterPreview?: boolean;
  writesKmOnConfirm?: boolean;
  requiredOwnerFields?: string[];
  blockers?: string[];
  onPreview: () => void;
  onConfirm: () => void;
}) {
  const t = useTranslations("awooop.workItems.knowledgeGovernance");
  const preview = action?.previewResult ?? null;
  const result = action?.result ?? null;
  const previewReady = Boolean(preview?.dry_run_plan_fingerprint);
  const completed = result?.status === "completed" || result?.status === "already_completed";
  const previewStatusKey = kmStaleReviewCompleteStatusKey(preview?.status);
  const resultStatusKey = kmStaleReviewCompleteStatusKey(result?.status);
  const outcome = preview?.review_outcome ?? kmStaleReviewOutcomeForCandidate(candidate);
  const dryRunState = previewReady ? "done" : queuedDispatchId && canPreview ? "ready" : "waiting";
  const confirmState = completed
    ? "done"
    : !queuedDispatchId || blockers.length > 0
      ? "blocked"
      : previewReady && canConfirmAfterPreview
        ? "ready"
        : "waiting";
  const recheckState = result?.stale_ratio_recheck_dispatch_id ? "done" : "waiting";
  const steps = [
    {
      key: "dispatch",
      icon: ClipboardList,
      state: queuedDispatchId ? "done" : "blocked",
      detail: t("staleCandidates.singleItemRail.detail.dispatch", {
        dispatch: queuedDispatchId ?? "--",
      }),
    },
    {
      key: "dryRun",
      icon: SearchCheck,
      state: dryRunState,
      detail: previewReady
        ? t("staleCandidates.singleItemRail.detail.dryRunReady")
        : queuedDispatchId
          ? t("staleCandidates.singleItemRail.detail.dryRunPending")
          : t("staleCandidates.singleItemRail.detail.dryRunBlocked"),
    },
    {
      key: "confirm",
      icon: ShieldCheck,
      state: confirmState,
      detail: completed
        ? t("staleCandidates.singleItemRail.detail.confirmDone")
        : previewReady
          ? t("staleCandidates.singleItemRail.detail.confirmReady")
          : t("staleCandidates.singleItemRail.detail.confirmWaiting"),
    },
    {
      key: "recheck",
      icon: RefreshCw,
      state: recheckState,
      detail: result?.stale_ratio_recheck_dispatch_id
        ? t("staleCandidates.singleItemRail.detail.recheckDone", {
            recheck: result.stale_ratio_recheck_dispatch_id,
          })
        : t("staleCandidates.singleItemRail.detail.recheckWaiting"),
    },
  ] as const;

  return (
    <div className="mt-2 min-w-0 border border-[#e0ddd4] bg-white px-3 py-2 text-[11px] leading-5 text-[#5f5b52]">
      <div className="flex flex-wrap items-start justify-between gap-2">
        <div className="min-w-0 flex-1">
          <p className="break-words font-semibold text-[#141413]">
            {t("staleCandidates.singleItemRail.title")}
          </p>
          <p className="mt-1 break-words text-[#77736a]">
            {t("staleCandidates.singleItemRail.subtitle")}
          </p>
        </div>
        <div className="flex min-w-0 flex-wrap gap-1 font-mono leading-5">
          <span className="max-w-full break-words border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
            {t("staleCandidates.singleItemRail.outcome", {
              outcome: t(`staleCandidates.completeActions.outcomes.${outcome}` as never),
            })}
          </span>
          <span className="max-w-full break-words border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
            {t("staleCandidates.singleItemRail.writeGate", {
              writes: String(writesKmOnConfirm),
              confirm: String(canConfirmAfterPreview),
            })}
          </span>
        </div>
      </div>
      <div className="mt-2 grid grid-cols-1 gap-px border border-[#e0ddd4] bg-[#e0ddd4] sm:grid-cols-2 xl:grid-cols-4">
        {steps.map((step) => {
          const Icon = step.icon;
          const tone = ownerReviewRailTone(step.state);
          return (
            <div key={step.key} className="min-w-0 bg-[#faf9f3] px-2 py-2">
              <div className="flex items-start justify-between gap-2">
                <div className={cn("flex h-7 w-7 shrink-0 items-center justify-center border", tone)}>
                  <Icon className="h-3.5 w-3.5" aria-hidden="true" />
                </div>
                <span className={cn("max-w-full break-words border px-2 py-0.5 text-[10px] font-semibold leading-4", tone)}>
                  {t(`staleCandidates.operationRail.state.${step.state}` as never)}
                </span>
              </div>
              <p className="mt-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-[#77736a]">
                {t(`staleCandidates.singleItemRail.step.${step.key}` as never)}
              </p>
              <p className="mt-1 break-words text-[11px] text-[#5f5b52] sm:line-clamp-2">
                {step.detail}
              </p>
            </div>
          );
        })}
      </div>
      <div className="mt-2 grid gap-2 lg:grid-cols-[minmax(0,1fr)_minmax(220px,0.65fr)]">
        <div className="min-w-0 break-words border border-[#d8d3c7] bg-[#faf9f3] px-2 py-1.5">
          <p>
            {t("staleCandidates.singleItemRail.required", {
              fields: requiredOwnerFields.length > 0 ? requiredOwnerFields.join(", ") : "--",
            })}
          </p>
          {blockers.length > 0 ? (
            <p className="text-[#9f2f25]">
              {t("staleCandidates.singleItemRail.blockers", {
                blockers: blockers.join(", "),
              })}
            </p>
          ) : (
            <p>
              {t("staleCandidates.singleItemRail.noBlockers")}
            </p>
          )}
          <p className="mt-1">
            {t("staleCandidates.singleItemRail.writeGateDetail")}
          </p>
        </div>
        <div className="flex min-w-0 flex-wrap items-center gap-2">
          <button
            type="button"
            onClick={onPreview}
            disabled={!queuedDispatchId || !canPreview || action?.previewLoading || action?.confirmLoading}
            className="inline-flex max-w-full items-center gap-1.5 whitespace-normal border border-[#d8d3c7] bg-white px-2 py-1 text-left text-xs font-semibold leading-5 text-[#2e2b26] hover:border-[#d9b36f] hover:bg-[#fff7e8] hover:text-[#8a5a08] disabled:cursor-not-allowed disabled:opacity-60"
          >
            <SearchCheck className="h-3.5 w-3.5" aria-hidden="true" />
            {action?.previewLoading
              ? t("staleCandidates.completeActions.previewing")
              : t("staleCandidates.singleItemRail.actions.preview")}
          </button>
          <button
            type="button"
            onClick={onConfirm}
            disabled={
              !queuedDispatchId ||
              !previewReady ||
              !canConfirmAfterPreview ||
              action?.previewLoading ||
              action?.confirmLoading
            }
            className="inline-flex max-w-full items-center gap-1.5 whitespace-normal border border-[#d8d3c7] bg-white px-2 py-1 text-left text-xs font-semibold leading-5 text-[#2e2b26] hover:border-[#9bc7a4] hover:bg-[#f0faf2] hover:text-[#17602a] disabled:cursor-not-allowed disabled:opacity-60"
          >
            <ShieldCheck className="h-3.5 w-3.5" aria-hidden="true" />
            {action?.confirmLoading
              ? t("staleCandidates.completeActions.confirming")
              : t("staleCandidates.singleItemRail.actions.confirm")}
          </button>
        </div>
      </div>
      {action?.error ? (
        <p className="mt-2 border border-[#e2a29b] bg-[#fff0ef] px-2 py-1 text-[#9f2f25]">
          {action.error}
        </p>
      ) : null}
      {preview ? (
        <div className="mt-2 border border-[#d9b36f] bg-[#fff7e8] px-2 py-1.5 text-[#8a5a08]">
          <p className="font-semibold">
            {t(`staleCandidates.completeActions.statuses.${previewStatusKey}` as never)}
          </p>
          <p className="mt-1 text-[#5f5b52]">
            {t("staleCandidates.completeActions.previewResult", {
              outcome: t(`staleCandidates.completeActions.outcomes.${preview.review_outcome}` as never),
              writesKm: String(preview.writes_km),
              writesAudit: String(preview.writes_governance_audit),
            })}
          </p>
          <p className="mt-1 break-all font-mono text-[11px] text-[#5f5b52]">
            {t("staleCandidates.completeActions.planFingerprint", {
              fingerprint: preview.dry_run_plan_fingerprint ?? "--",
            })}
          </p>
          {preview.stale_ratio_snapshot ? (
            <p className="mt-1 text-[#5f5b52]">
              {t("staleCandidates.completeActions.snapshot", {
                stale: preview.stale_ratio_snapshot.stale_count,
                total: preview.stale_ratio_snapshot.total_count,
                ratio: formatStaleRatio(preview.stale_ratio_snapshot.stale_ratio),
                threshold: formatStaleRatio(preview.stale_ratio_snapshot.threshold),
              })}
            </p>
          ) : null}
        </div>
      ) : null}
      {result ? (
        <div className="mt-2 border border-[#9bc7a4] bg-[#f0faf2] px-2 py-1.5 text-[#17602a]">
          <p className="font-semibold">
            {t(`staleCandidates.completeActions.statuses.${resultStatusKey}` as never)}
          </p>
          <p className="mt-1 text-[#5f5b52]">
            {t("staleCandidates.completeActions.result", {
              audit: result.audit_dispatch_id ?? "--",
              recheck: result.stale_ratio_recheck_dispatch_id ?? "--",
            })}
          </p>
          {result.stale_ratio_snapshot ? (
            <p className="mt-1 text-[#5f5b52]">
              {t("staleCandidates.completeActions.snapshot", {
                stale: result.stale_ratio_snapshot.stale_count,
                total: result.stale_ratio_snapshot.total_count,
                ratio: formatStaleRatio(result.stale_ratio_snapshot.stale_ratio),
                threshold: formatStaleRatio(result.stale_ratio_snapshot.threshold),
              })}
            </p>
          ) : null}
        </div>
      ) : null}
    </div>
  );
}

function kmCorrelationSourceKey(value: string | null | undefined) {
  switch (value) {
    case "incident":
    case "approval":
    case "playbook":
    case "sentry":
    case "signoz":
      return value;
    default:
      return "unknown";
  }
}

function governanceEventHistoryHref(eventId: string) {
  return `/governance?tab=events&event_id=${encodeURIComponent(eventId)}`;
}

function callbackOwnerReviewOpenEvents(
  response: CallbackRepliesWorkItemResponse | null
): CallbackReplyWorkItemEvent[] {
  return (response?.items ?? []).filter((item) => {
    const summary = item.km_stale_completion_summary;
    return (
      summary?.status === "no_related_owner_review" &&
      summary.work_item?.status === "open"
    );
  });
}

function callbackTraceRecoveryStatus(
  summary: CallbackReplyAuditSummary | null | undefined
): WorkStatus {
  const action = callbackTraceRecoveryAction(summary);
  if (action.actionKey === "closed") {
    return "live";
  }
  if (
    action.actionKey === "investigateActiveGap" ||
    action.actionKey === "verifyInstrumentation" ||
    action.actionKey === "unavailable"
  ) {
    return "blocked";
  }
  if (action.actionKey === "waitDecay") {
    return "in_progress";
  }
  return "watching";
}

function callbackTraceRecoveryAction(
  summary: CallbackReplyAuditSummary | null | undefined
): CallbackTraceRecoveryAction {
  if (!summary) {
    return { actionKey: "unavailable", humanRequired: true };
  }
  const missingTrace = summary.outbound_reply_markup_missing_trace_ref_total ?? 0;
  if (missingTrace <= 0) {
    return { actionKey: "closed", humanRequired: false };
  }
  const recent1h =
    summary.outbound_reply_markup_missing_trace_ref_recent_1h_total ?? 0;
  const recent24h =
    summary.outbound_reply_markup_missing_trace_ref_recent_24h_total ?? 0;
  const gapStatus = summary.outbound_reply_markup_trace_ref_gap_status;
  const recoveryStatus = summary.outbound_reply_markup_trace_ref_gap_recovery_status;
  if (gapStatus === "active_gap" || recent1h > 0) {
    return { actionKey: "investigateActiveGap", humanRequired: true };
  }
  if (recoveryStatus === "no_recovery_signal") {
    return { actionKey: "verifyInstrumentation", humanRequired: true };
  }
  if (recoveryStatus === "recovered_after_gap") {
    if (recent24h > 0) {
      return { actionKey: "waitDecay", humanRequired: false };
    }
    return { actionKey: "closed", humanRequired: false };
  }
  return { actionKey: "observeRecovery", humanRequired: false };
}

function aiRouteOperatorActionText(
  action: string | null | undefined,
  t: ReturnType<typeof useTranslations>
) {
  if (
    action === "monitor" ||
    action === "repair_skipped_primary_lane" ||
    action === "restore_ollama_lanes" ||
    action === "inspect_ai_router"
  ) {
    return t(`evidence.aiRouteActions.${action}` as never);
  }
  return t("evidence.aiRouteActions.unknown");
}

function buildWorkItems(
  telemetry: Telemetry,
  t: ReturnType<typeof useTranslations>
): WorkItem[] {
  const verifiedAutoRepairs = telemetry.quality?.verified_auto_repair_total ?? 0;
  const evaluatedIncidents = telemetry.quality?.evaluated_total ?? 0;
  const recentChannelEvents = telemetry.channelEvents?.total ?? 0;
  const governanceUnresolved = telemetry.governanceEvents?.total ?? 0;
  const governanceQueuePending = telemetry.governanceQueue?.total ?? 0;
  const knowledgeDispatches = telemetry.governanceKnowledgeQueue?.items ?? [];
  const latestKnowledgeDispatch = knowledgeDispatches[0] ?? null;
  const knowledgeReviewDraftGroups = groupKnowledgeReviewDrafts(
    telemetry.knowledgeReviewDrafts,
    knowledgeDispatches
  );
  const knowledgeDuplicateDrafts = knowledgeReviewDraftGroups.reduce(
    (sum, group) => sum + group.duplicateCount,
    0
  );
  const knowledgeDedupeDuplicates =
    telemetry.knowledgeReviewDedupe?.duplicate_draft_total ?? knowledgeDuplicateDrafts;
  const knowledgeStaleTotal = telemetry.knowledgeStaleCandidates?.total_stale ?? 0;
  const topKnowledgeStaleCandidate = telemetry.knowledgeStaleCandidates?.items?.[0] ?? null;
  const knowledgeCompletionQueue = telemetry.knowledgeStaleOwnerReviewCompletionQueue;
  const latestKnowledgeCompletion = knowledgeCompletionQueue?.items?.[0] ?? null;
  const callbackOwnerReviewEvents = callbackOwnerReviewOpenEvents(
    telemetry.callbackReplies
  );
  const latestCallbackOwnerReview = callbackOwnerReviewEvents[0] ?? null;
  const latestCallbackSummary =
    latestCallbackOwnerReview?.km_stale_completion_summary ?? null;
  const latestCallbackWorkItem = latestCallbackSummary?.work_item ?? null;
  const latestCallbackTriage = latestCallbackWorkItem?.triage ?? null;
  const callbackTraceSummary = telemetry.callbackReplies?.summary ?? null;
  const callbackTraceAction = callbackTraceRecoveryAction(callbackTraceSummary);
  const aiRoute = telemetry.aiRouteStatus;
  const aiRouteRepairEvidence = aiRoute?.repair_evidence ?? null;
  const aiRouteWorkItem = aiRouteRepairEvidence?.work_item ?? null;
  const aiRoutePlaybook = aiRouteRepairEvidence?.playbook_recommendation ?? null;
  const aiRouteOwnerAction = aiRouteRepairEvidence?.owner_action ?? null;
  const aiRouteBlockers = aiRouteRepairEvidence?.access_blockers ?? [];
  const aiRouteSkipped = aiRoute?.skipped_lanes
    ?.map((lane) => lane.provider_name)
    .filter(Boolean)
    .join(" -> ");
  const aiRouteActionText = aiRouteOperatorActionText(
    aiRoute?.operator_action?.action,
    t
  );
  const aiRouteHumanRequired = aiRoute?.operator_action?.human_required === true;
  const aiRouteHumanRequiredText = aiRouteHumanRequired
    ? t("evidence.humanRequired.yes")
    : t("evidence.humanRequired.no");
  const remediationQueue = telemetry.slo?.adr100?.verification_coverage?.remediation_queue;
  const remediationTotal = remediationQueue?.total ?? 0;
  const remediationReadyForAi = remediationQueue?.ready_for_ai ?? 0;
  const remediationNeedsHuman = remediationQueue?.needs_human ?? 0;
  const remediationHistoryTotal = telemetry.remediationHistory?.total ?? 0;
  const latestRemediationHistory = telemetry.remediationHistory?.items?.[0] ?? null;
  const recurrenceSummary = telemetry.eventRecurrence?.summary;
  const recurrenceOpen = recurrenceSummary?.open_work_item_group_total ?? 0;
  const recurrenceAutomationGap = recurrenceSummary?.automation_gap_group_total ?? 0;
  const recurrenceFailedRepair = recurrenceSummary?.failed_repair_group_total ?? 0;
  const recurrenceManualGate = recurrenceSummary?.manual_gate_group_total ?? 0;
  const recurrenceSourceReview =
    recurrenceSummary?.source_correlation_review_group_total ?? 0;
  const recurrenceSourceReviewRecorded =
    recurrenceSummary?.source_correlation_decision_recorded_group_total ?? 0;
  const recurrenceSourceApplied =
    recurrenceSummary?.source_correlation_applied_group_total ?? 0;
  const latestRecurrenceOpenItem = recurrenceOpenItems(telemetry.eventRecurrence)[0] ?? null;
  const driftState = telemetry.driftFingerprintState;
  const driftFsmKey = driftFsmStateKey(driftState?.fsm_state);
  const driftNextKey = driftNextStepKey(driftState?.next_step);
  const driftRemediationKind = driftRemediationKindKey(
    driftState?.latest_remediation?.remediation_kind
  );
  const driftRemediationStatus = driftRemediationStatusKey(
    driftState?.latest_remediation?.remediation_status
  );
  const governanceEventsUnavailable = telemetry.governanceEvents === null;
  const governanceQueueMissing = telemetry.governanceQueue?.table_pending === true;
  const governanceDispatchBlocked =
    governanceEventsUnavailable ||
    governanceQueueMissing ||
    (governanceUnresolved > 0 && governanceQueuePending === 0);
  const mcpGateMissing = hasGateFailure(telemetry.quality, "mcp_gateway_observed");
  const timelineGateMissing = hasGateFailure(telemetry.quality, "timeline_recorded");

  return [
    {
      id: "sourceDossier",
      phase: "T15",
      status: recentChannelEvents > 0 ? "live" : "watching",
      surfaceKey: "runs",
      source: "awooop_conversation_event",
      gateKey: "sourceDossier",
      evidence: t("evidence.channelEvents", { count: recentChannelEvents }),
      href: "/awooop/runs",
    },
    {
      id: "autoRepair",
      phase: "T16",
      status: verifiedAutoRepairs > 0 ? "live" : "in_progress",
      surfaceKey: "runs",
      source: "auto_repair_executions / incident_evidence",
      gateKey: "autoRepair",
      evidence: t("evidence.autoRepair", {
        verified: verifiedAutoRepairs,
        evaluated: evaluatedIncidents,
      }),
      href: "/awooop/runs",
    },
    {
      id: "recurrenceWorkItems",
      phase: "T61",
      status: recurrenceOpen > 0
        ? "in_progress"
        : telemetry.eventRecurrence
          ? "watching"
          : "blocked",
      surfaceKey: "workItems",
      source: "/api/v1/platform/events/dossier/recurrence",
      gateKey: "recurrenceWorkItems",
      evidence: t("evidence.recurrenceWorkItems", {
        open: recurrenceOpen,
        gap: recurrenceAutomationGap,
        failed: recurrenceFailedRepair,
        manual: recurrenceManualGate,
        source: recurrenceSourceReview,
      }),
      evidenceDetails: latestRecurrenceOpenItem
        ? [
            t("evidence.recurrenceLatest", {
              alert: latestRecurrenceOpenItem.alertname ?? "--",
              incident: latestRecurrenceOpenItem.latest_incident_id ?? "--",
            }),
            t("evidence.recurrenceReason", {
              reason: t(
                `recurrence.reasons.${latestRecurrenceOpenItem.work_item?.reason ?? "unknown"}` as never
              ),
            }),
            t("evidence.recurrenceSourceReviewRecorded", {
              count: recurrenceSourceReviewRecorded,
            }),
            t("evidence.recurrenceSourceApplied", {
              count: recurrenceSourceApplied,
            }),
          ]
        : [
            t("evidence.recurrenceEmpty"),
            t("evidence.recurrenceSourceReviewRecorded", {
              count: recurrenceSourceReviewRecorded,
            }),
            t("evidence.recurrenceSourceApplied", {
              count: recurrenceSourceApplied,
            }),
          ],
      href: latestRecurrenceOpenItem?.work_item?.work_item_id
        ? `/awooop/work-items?project_id=${encodeURIComponent(telemetry.eventRecurrence?.project_id ?? "awoooi")}&work_item_id=${encodeURIComponent(latestRecurrenceOpenItem.work_item.work_item_id)}${latestRecurrenceOpenItem.work_item.incident_id ? `&incident_id=${encodeURIComponent(latestRecurrenceOpenItem.work_item.incident_id)}` : ""}`
        : "/awooop/runs",
    },
    {
      id: "aiRouteRepairWorkItem",
      phase: "T178",
      status: aiRouteWorkItem?.status === "open"
        ? "blocked"
        : aiRoute
          ? "watching"
          : "blocked",
      surfaceKey: "runs",
      source: "/api/v1/platform/ai-route-status + ai_route_repair",
      gateKey: "aiRouteRepairWorkItem",
      evidence: t("evidence.aiRouteRepairWorkItem", {
        lane: aiRoute?.lane_mode ?? "--",
        selected: aiRoute?.selected_provider ?? "--",
        target: aiRouteRepairEvidence?.target_resource ?? "--",
        blockers: aiRouteBlockers.length,
      }),
      evidenceDetails: aiRouteRepairEvidence
        ? [
            t("evidence.aiRouteRepairSummary", {
              selected: aiRoute?.selected_provider ?? "--",
              action: aiRouteActionText,
              human: aiRouteHumanRequiredText,
            }),
            t("evidence.aiRouteRepairWorkItemId", {
              id: aiRouteWorkItem?.work_item_id ?? "--",
            }),
            t("evidence.aiRouteRepairSkipped", {
              skipped: aiRouteSkipped || "--",
            }),
            t("evidence.aiRouteRepairOwner", {
              owner: aiRouteOwnerAction?.human_owner ?? aiRouteWorkItem?.owner ?? "--",
              lead: aiRouteOwnerAction?.lead_agent ?? "--",
            }),
            t("evidence.aiRouteRepairPlaybook", {
              playbook: aiRoutePlaybook?.playbook_id ?? "--",
              steps: aiRoutePlaybook?.steps?.length ?? 0,
            }),
            t("evidence.aiRouteRepairSafety", {
              safe: String(aiRouteOwnerAction?.safe_to_auto_repair ?? false),
            }),
          ]
        : [
            t("evidence.aiRouteRepairSummary", {
              selected: aiRoute?.selected_provider ?? "--",
              action: aiRouteActionText,
              human: aiRouteHumanRequiredText,
            }),
            t("evidence.aiRouteRepairUnavailable"),
          ],
      href: aiRouteWorkItem?.target_href ?? "/awooop/runs",
    },
    {
      id: "configDriftFsm",
      phase: "T64",
      status: driftStatusForWorkItem(driftState),
      surfaceKey: "workItems",
      source: "/api/v1/drift/fingerprints/state",
      gateKey: "configDriftFsm",
      evidence: driftState
        ? t("evidence.driftFingerprint", {
            state: t(`driftFingerprint.fsmStates.${driftFsmKey}` as never),
            count: driftState.occurrences_12h ?? 0,
          })
        : t("evidence.driftFingerprintUnavailable"),
      evidenceDetails: driftState
        ? [
            t("evidence.driftFingerprintId", {
              fingerprint: driftState.fingerprint ?? "--",
              report: driftState.latest_report_id ?? "--",
            }),
            t("evidence.driftFingerprintPr", {
              pr: driftState.open_pr?.number ?? "--",
              zeroDiff: String(driftState.open_pr?.is_zero_diff ?? false),
            }),
            t("evidence.driftFingerprintNext", {
              step: t(`driftFingerprint.nextSteps.${driftNextKey}` as never),
            }),
            t("evidence.driftFingerprintRemediation", {
              kind: t(`driftFingerprint.remediationKinds.${driftRemediationKind}` as never),
              status: t(
                `driftFingerprint.remediationStatuses.${driftRemediationStatus}` as never
              ),
              report: driftState.latest_remediation?.verification_report_id ?? "--",
            }),
          ]
        : [t("evidence.driftFingerprintEmpty")],
      href: "/drift",
    },
    {
      id: "remediationQueue",
      phase: "T24",
      status: remediationTotal === 0
        ? "watching"
        : remediationReadyForAi > 0
          ? "in_progress"
          : "blocked",
      surfaceKey: "governance",
      source: "/api/v1/ai/slo remediation_queue + remediation_history",
      gateKey: "remediationQueue",
      evidence: t("evidence.remediationQueue", {
        total: remediationTotal,
        ready: remediationReadyForAi,
        human: remediationNeedsHuman,
      }),
      evidenceDetails: latestRemediationHistory
        ? [
            t("evidence.remediationHistory", {
              count: remediationHistoryTotal,
              preview: latestRemediationHistory.verification_result_preview ?? "--",
            }),
            t("evidence.remediationRoute", {
              route: routeLabel(latestRemediationHistory),
            }),
            t("evidence.remediationWrites", {
              incident: String(latestRemediationHistory.writes_incident_state ?? "--"),
              autoRepair: String(latestRemediationHistory.writes_auto_repair_result ?? "--"),
            }),
          ]
        : [t("evidence.remediationHistoryEmpty")],
      href: "/governance",
    },
    {
      id: "telegramCallbacks",
      phase: "T45",
      status: "live",
      surfaceKey: "runs",
      source: "telegram_callback / 真相鏈鏡像",
      gateKey: "telegramCallbacks",
      evidence: t("evidence.telegramCallbacksLive"),
      href: "/awooop/runs",
    },
    {
      id: "iwooosSecurityMirror",
      phase: "S2.54",
      status: "watching",
      surfaceKey: "iwooos",
      source: "security_mirror_status_rollup_v1 / iwooos_posture_projection_v1",
      gateKey: "iwooosSecurityMirror",
      evidence: t("evidence.iwooosSecurityMirror", {
        headline: "64%",
        framework: "92%",
        runtime: "40-45%",
        gates: 0,
      }),
      evidenceDetails: [
        t("evidence.iwooosSecurityMirrorOwner"),
        t("evidence.iwooosSecurityMirrorBoundary"),
      ],
      href: "/iwooos",
    },
    {
      id: "githubPrimaryReadiness",
      phase: "S2.64",
      status: "watching",
      surfaceKey: "iwooos",
      source: "source-control-primary-readiness-gate.snapshot.json / iwooos_posture_projection_v1",
      gateKey: "githubPrimaryReadiness",
      evidence: t("evidence.githubPrimaryReadiness", {
        candidates: 8,
        inScope: 7,
        ready: 0,
      }),
      evidenceDetails: [
        t("evidence.githubPrimaryOwnerResponses"),
        t("evidence.githubPrimaryWorkflowNames"),
        t("evidence.githubPrimaryBoundary"),
      ],
      href: "/iwooos",
    },
    {
      id: "ownerResponseValidation",
      phase: "S2.73",
      status: "watching",
      surfaceKey: "iwooos",
      source: "source-control-owner-response-validation-rollup.snapshot.json / security_mirror_status_rollup_v1",
      gateKey: "ownerResponseValidation",
      evidence: t("evidence.ownerResponseValidation", {
        packets: 4,
        templates: 22,
        received: 0,
        accepted: 0,
        rejected: 0,
      }),
      evidenceDetails: [
        t("evidence.ownerResponseValidationChecks", {
          crossPacket: 10,
          routing: 6,
          sections: 8,
        }),
        t("evidence.ownerResponseValidationBoundary"),
      ],
      href: "/iwooos",
    },
    {
      id: "callbackOwnerReview",
      phase: "T164",
      status: callbackOwnerReviewEvents.length > 0
        ? "in_progress"
        : telemetry.callbackReplies
          ? "watching"
          : "blocked",
      surfaceKey: "workItems",
      source: "/api/v1/platform/runs/callback-replies + km_stale_completion_summary",
      gateKey: "callbackOwnerReview",
      evidence: t("evidence.callbackOwnerReview", {
        open: callbackOwnerReviewEvents.length,
        total: telemetry.callbackReplies?.total ?? 0,
      }),
      evidenceDetails: latestCallbackOwnerReview
        ? [
            t("evidence.callbackOwnerReviewLatest", {
              incident: latestCallbackOwnerReview.incident_id ?? "--",
              action: latestCallbackOwnerReview.action ?? "--",
            }),
            t("evidence.callbackOwnerReviewQueue", {
              ready: latestCallbackSummary?.ready_count ?? 0,
              blocked: latestCallbackSummary?.blocked_count ?? 0,
              completed: latestCallbackSummary?.completed_count ?? 0,
              failed: latestCallbackSummary?.failed_count ?? 0,
            }),
            t("evidence.callbackOwnerReviewNext", {
              next: latestCallbackWorkItem?.next_step ?? "--",
            }),
            t("evidence.callbackOwnerReviewFlow", {
              stage: latestCallbackTriage?.flow_stage ?? "--",
              strategy: latestCallbackTriage?.matching_strategy ?? "--",
            }),
            t("evidence.callbackOwnerReviewAgents", {
              lead: latestCallbackTriage?.ai_lead_agent ?? "--",
              support: latestCallbackTriage?.supporting_agents?.join(" / ") || "--",
            }),
            t("evidence.callbackOwnerReviewAutomation", {
              state: latestCallbackTriage?.automation_state ?? "--",
              safe: String(latestCallbackTriage?.safe_to_auto_repair ?? false),
            }),
            t("evidence.callbackOwnerReviewBlocker", {
              reason: latestCallbackTriage?.blocking_reason ?? "--",
            }),
          ]
        : [t("evidence.callbackOwnerReviewEmpty")],
      href: latestCallbackWorkItem?.target_href ?? "/awooop/runs",
    },
    {
      id: "callbackTraceRecoveryBacklog",
      phase: "T195",
      status: callbackTraceRecoveryStatus(callbackTraceSummary),
      surfaceKey: "workItems",
      source: "/api/v1/platform/runs/callback-replies summary",
      gateKey: "callbackTraceRecoveryBacklog",
      evidence: t("evidence.callbackTraceRecoveryBacklog", {
        missing:
          callbackTraceSummary?.outbound_reply_markup_missing_trace_ref_total ??
          0,
        recent1h:
          callbackTraceSummary
            ?.outbound_reply_markup_missing_trace_ref_recent_1h_total ?? 0,
        recent24h:
          callbackTraceSummary
            ?.outbound_reply_markup_missing_trace_ref_recent_24h_total ?? 0,
        recovered:
          callbackTraceSummary?.outbound_reply_markup_trace_ref_after_gap_total ??
          0,
        status:
          callbackTraceSummary
            ?.outbound_reply_markup_trace_ref_gap_recovery_status ?? "--",
      }),
      evidenceDetails: callbackTraceSummary
        ? [
            t("evidence.callbackTraceRecoveryAction", {
              action: t(
                `callbackTraceRecoveryActions.${callbackTraceAction.actionKey}` as never
              ),
              human: t(
                `humanRequired.${callbackTraceAction.humanRequired ? "yes" : "no"}` as never
              ),
            }),
            t("evidence.callbackTraceRecoveryOwner"),
            t("evidence.callbackTraceRecoveryEvidenceSurface"),
            t("evidence.callbackTraceRecoveryClosure", {
              recent1h:
                callbackTraceSummary
                  .outbound_reply_markup_missing_trace_ref_recent_1h_total ??
                0,
              recent24h:
                callbackTraceSummary
                  .outbound_reply_markup_missing_trace_ref_recent_24h_total ??
                0,
            }),
            t("evidence.callbackTraceRecoveryDecision", {
              gap:
                callbackTraceSummary.outbound_reply_markup_trace_ref_gap_status ??
                "--",
              next:
                callbackTraceSummary
                  .outbound_reply_markup_trace_ref_gap_next_action ?? "--",
            }),
            t("evidence.callbackTraceRecoveryLatest", {
              missing:
                callbackTraceSummary
                  .outbound_reply_markup_missing_trace_ref_latest_sent_at ??
                "--",
              first:
                callbackTraceSummary
                  .outbound_reply_markup_trace_ref_after_gap_first_sent_at ??
                "--",
              latest:
                callbackTraceSummary
                  .outbound_reply_markup_trace_ref_after_gap_latest_sent_at ??
                "--",
            }),
          ]
        : [t("evidence.callbackTraceRecoveryUnavailable")],
      href: "/awooop/runs?project_id=awoooi#tg-callback-evidence",
    },
    {
      id: "ciSecretHygiene",
      phase: "T44",
      status: "in_progress",
      surfaceKey: "workItems",
      source: ".gitea/workflows / scripts/ci/check-gitea-step-env-secrets.js",
      gateKey: "ciSecretHygiene",
      evidence: t("evidence.ciSecretHygiene"),
      href: "/awooop/work-items",
    },
    {
      id: "governanceDispatch",
      phase: "T17",
      status: governanceDispatchBlocked
        ? "blocked"
        : governanceUnresolved > 0
          ? "in_progress"
          : "watching",
      surfaceKey: "governance",
      source: "ai_governance_events / governance_remediation_dispatch",
      gateKey: "governanceDispatch",
      evidence: governanceEventsUnavailable
        ? t("evidence.governanceUnavailable", { queued: governanceQueuePending })
        : governanceQueueMissing
          ? t("evidence.governanceQueueMissing", { unresolved: governanceUnresolved })
          : t("evidence.governance", {
              unresolved: governanceUnresolved,
              queued: governanceQueuePending,
            }),
      href: "/governance",
    },
    {
      id: "knowledgeHealthcheck",
      phase: "T88",
      status: governanceKmStatusForWorkItem(telemetry.governanceKnowledgeQueue),
      surfaceKey: "workItems",
      source: "/api/v1/ai/governance/queue?event_type=knowledge_degradation",
      gateKey: "knowledgeHealthcheck",
      evidence: t("evidence.knowledgeHealthcheck", {
        total: telemetry.governanceKnowledgeQueue?.total ?? 0,
        stage: latestKnowledgeDispatch
          ? t(`knowledgeGovernance.stages.${governanceKmStageKey(latestKnowledgeDispatch.workflow_stage)}` as never)
          : "--",
      }),
      evidenceDetails: latestKnowledgeDispatch
        ? [
            t("evidence.knowledgeOwner", {
              lead: latestKnowledgeDispatch.lead_agent ?? "--",
              human: latestKnowledgeDispatch.human_owner ?? "--",
            }),
            t("evidence.knowledgeNext", {
              action: latestKnowledgeDispatch.next_action ?? latestKnowledgeDispatch.proposed_action ?? "--",
            }),
            t("evidence.knowledgeDrafts", {
              drafts: telemetry.knowledgeReviewDedupe?.total_review_drafts
                ?? telemetry.knowledgeReviewDrafts?.total
                ?? 0,
              duplicates: knowledgeDedupeDuplicates,
            }),
            t("evidence.knowledgeStaleCandidates", {
              total: knowledgeStaleTotal,
              top: topKnowledgeStaleCandidate?.entry_id ?? "--",
              tier: topKnowledgeStaleCandidate?.priority_tier ?? "--",
            }),
            t("evidence.knowledgeCompletionQueue", {
              ready: knowledgeCompletionQueue?.ready_count ?? 0,
              blocked: knowledgeCompletionQueue?.blocked_count ?? 0,
              completed: knowledgeCompletionQueue?.completed_count ?? 0,
              failed: knowledgeCompletionQueue?.failed_count ?? 0,
            }),
            t("evidence.knowledgeCompletionLatest", {
              entry: latestKnowledgeCompletion?.entry_id ?? "--",
              readiness: latestKnowledgeCompletion
                ? t(
                    `knowledgeGovernance.staleCandidates.completionQueue.readiness.${kmStaleCompletionReadinessKey(latestKnowledgeCompletion.readiness)}` as never
                  )
                : "--",
              next: latestKnowledgeCompletion?.next_action ?? "--",
            }),
          ]
        : [
            t("evidence.knowledgeEmpty"),
            t("evidence.knowledgeStaleCandidates", {
              total: knowledgeStaleTotal,
              top: topKnowledgeStaleCandidate?.entry_id ?? "--",
              tier: topKnowledgeStaleCandidate?.priority_tier ?? "--",
            }),
            t("evidence.knowledgeCompletionQueue", {
              ready: knowledgeCompletionQueue?.ready_count ?? 0,
              blocked: knowledgeCompletionQueue?.blocked_count ?? 0,
              completed: knowledgeCompletionQueue?.completed_count ?? 0,
              failed: knowledgeCompletionQueue?.failed_count ?? 0,
            }),
          ],
      href: "/awooop/work-items",
    },
    {
      id: "frontendConsole",
      phase: "T17",
      status: "in_progress",
      surfaceKey: "workItems",
      source: "apps/web/src/app/[locale]/awooop",
      gateKey: "frontendConsole",
      evidence: t("evidence.frontendConsole"),
      href: "/awooop/work-items",
    },
    {
      id: "mcpGateway",
      phase: "T18",
      status: mcpGateMissing ? "watching" : "live",
      surfaceKey: "runs",
      source: "awooop_mcp_gateway_audit / mcp_audit_log",
      gateKey: "mcpGateway",
      evidence: mcpGateMissing ? t("evidence.mcpMissing") : t("evidence.mcpReady"),
      href: "/awooop/runs",
    },
    {
      id: "timelineContract",
      phase: "T18",
      status: timelineGateMissing ? "in_progress" : "live",
      surfaceKey: "runs",
      source: "timeline_events / automation_operation_log / KM",
      gateKey: "timelineContract",
      evidence: timelineGateMissing ? t("evidence.timelineMissing") : t("evidence.timelineReady"),
      href: "/awooop/runs",
    },
  ];
}

function StatusBadge({ status }: { status: WorkStatus }) {
  const t = useTranslations("awooop.workItems.status");
  const config = statusConfig[status];
  const Icon = config.icon;
  return (
    <span
      className={cn(
        "inline-flex min-w-[86px] items-center justify-center gap-1.5 border px-2 py-0.5 text-xs font-semibold",
        config.className
      )}
    >
      <Icon className="h-3.5 w-3.5" aria-hidden="true" />
      {t(status)}
    </span>
  );
}

function SummaryCell({
  label,
  value,
  icon: Icon,
}: {
  label: string;
  value: number;
  icon: typeof Activity;
}) {
  return (
    <div className="bg-white px-4 py-3">
      <div className="flex items-center justify-between gap-3">
        <span className="text-xs font-medium text-[#77736a]">{label}</span>
        <Icon className="h-4 w-4 text-[#87867f]" aria-hidden="true" />
      </div>
      <div className="mt-2 font-mono text-2xl font-semibold text-[#141413]">
        {value}
      </div>
    </div>
  );
}

function claimReasonLabel(reason: string | null | undefined, t: ReturnType<typeof useTranslations>) {
  if (reason === "some_incidents_are_not_auto_repaired_verified") {
    return t("reasonSomeUnverified");
  }
  return reason || t("reasonUnknown");
}

function ProductionClaimBanner({
  loading,
  summary,
}: {
  loading: boolean;
  summary: AutomationQualitySummary | null;
}) {
  const t = useTranslations("awooop.workItems.claim");
  const canClaim = summary?.production_claim?.can_claim_full_auto_repair === true;
  const hasSummary = summary !== null;
  const Icon = canClaim ? ShieldCheck : TriangleAlert;
  const gateFailures = summary?.gate_failures?.length ?? 0;
  const statusLabel = loading && !hasSummary
    ? t("loading")
    : hasSummary
      ? canClaim ? t("ready") : t("notReady")
      : t("unavailable");
  const reasonLabel = loading && !hasSummary
    ? t("loadingDetail")
    : hasSummary
      ? claimReasonLabel(summary?.production_claim?.reason, t)
      : t("unavailableDetail");

  return (
    <section
      className={cn(
        "border px-4 py-4",
        canClaim
          ? "border-[#9bc7a4] bg-[#f0faf2]"
          : "border-[#d9b36f] bg-[#fff7e8]"
      )}
    >
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div className="flex min-w-0 items-start gap-3">
          <Icon
            className={cn(
              "mt-0.5 h-5 w-5 shrink-0",
              canClaim ? "text-[#17602a]" : "text-[#8a5a08]"
            )}
            aria-hidden="true"
          />
          <div className="min-w-0">
            <div className="text-sm font-semibold text-[#141413]">
              {statusLabel}
            </div>
            <div className="mt-1 text-xs leading-5 text-[#5f5b52]">
              {reasonLabel}
            </div>
          </div>
        </div>
        <div className="grid w-full min-w-0 gap-2 text-left font-mono text-xs text-[#5f5b52] sm:min-w-[280px] sm:grid-cols-3 sm:text-right">
          <span>{hasSummary ? t("verified", { count: summary.verified_auto_repair_total }) : t("verifiedUnknown")}</span>
          <span>{hasSummary ? t("evaluated", { count: summary.evaluated_total }) : t("evaluatedUnknown")}</span>
          <span>{hasSummary ? t("gateFailures", { count: gateFailures }) : t("gateFailuresUnknown")}</span>
        </div>
      </div>
    </section>
  );
}

function RepairCandidateDraftPanel({
  draft,
  chain,
}: {
  draft: RepairCandidateDraftFocus | null;
  chain: AwoooPStatusChain | null;
}) {
  const t = useTranslations("awooop.workItems.repairCandidateDraft");
  if (!draft) return null;

  const runsHref = draft.incidentId
    ? `/awooop/runs?project_id=${encodeURIComponent(draft.projectId)}&incident_id=${encodeURIComponent(draft.incidentId)}`
    : `/awooop/runs?project_id=${encodeURIComponent(draft.projectId)}`;
  const approvalsHref = draft.incidentId
    ? `/awooop/approvals?project_id=${encodeURIComponent(draft.projectId)}&incident_id=${encodeURIComponent(draft.incidentId)}`
    : `/awooop/approvals?project_id=${encodeURIComponent(draft.projectId)}`;
  const metrics = [
    [t("metrics.status"), t("statusValue")],
    [t("metrics.incident"), draft.incidentId ?? "--"],
    [t("metrics.lane"), draft.lane],
    [t("metrics.effect"), "none"],
  ];
  const chainRows = [
    [t("chain.stage"), chain?.current_stage ?? "--"],
    [t("chain.repair"), chain?.repair_state ?? "--"],
    [t("chain.next"), chain?.next_step ?? "--"],
    [t("chain.human"), String(chain?.needs_human ?? true)],
  ];

  return (
    <section className="border border-[#e0ddd4] bg-white">
      <div className="grid gap-px bg-[#e0ddd4] lg:grid-cols-[1.15fr_0.85fr]">
        <div className="min-w-0 bg-white p-4">
          <div className="flex flex-wrap items-start justify-between gap-3">
            <div className="flex min-w-0 items-start gap-3">
              <div className="flex h-9 w-9 shrink-0 items-center justify-center border border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]">
                <TriangleAlert className="h-5 w-5" aria-hidden="true" />
              </div>
              <div className="min-w-0">
                <p className="text-xs font-semibold uppercase tracking-[0.08em] text-[#9f2f25]">
                  {t("eyebrow")}
                </p>
                <h3 className="mt-1 text-lg font-semibold tracking-normal text-[#141413]">
                  {t("title")}
                </h3>
                <p className="mt-2 max-w-3xl text-sm leading-6 text-[#5f5b52]">
                  {t("subtitle")}
                </p>
              </div>
            </div>
            <span className="shrink-0 break-all border border-[#d9b36f] bg-[#fff7e8] px-2 py-1 font-mono text-xs font-semibold text-[#8a5a08]">
              {draft.workItemId}
            </span>
          </div>

          <div className="mt-4 grid gap-px bg-[#e0ddd4] md:grid-cols-4">
            {metrics.map(([label, value]) => (
              <div key={label} className="min-w-0 bg-[#faf9f3] px-3 py-2">
                <p className="text-xs font-semibold text-[#77736a]">{label}</p>
                <p className="mt-1 break-all font-mono text-sm font-semibold text-[#141413]">
                  {value}
                </p>
              </div>
            ))}
          </div>

          <div className="mt-4 grid gap-2 md:grid-cols-5">
            {["ingest", "evidence", "draft", "review", "approval"].map((step, index) => (
              <div key={step} className="min-w-0 border border-[#e0ddd4] bg-white px-3 py-2">
                <p className="font-mono text-[11px] font-semibold text-[#77736a]">
                  {String(index + 1).padStart(2, "0")}
                </p>
                <p className="mt-1 text-xs font-semibold text-[#141413]">
                  {t(`flow.${step}.title` as never)}
                </p>
                <p className="mt-1 text-[11px] leading-5 text-[#5f5b52]">
                  {t(`flow.${step}.detail` as never)}
                </p>
              </div>
            ))}
          </div>
        </div>

        <div className="min-w-0 bg-white p-4">
          <div className="flex items-center gap-2">
            <ListChecks className="h-4 w-4 text-brand-accent" aria-hidden="true" />
            <h4 className="text-sm font-semibold text-[#141413]">{t("requiredTitle")}</h4>
          </div>
          <div className="mt-3 grid gap-2">
            {REPAIR_CANDIDATE_DRAFT_REQUIRED_FIELDS.map((field) => (
              <div key={field} className="border border-[#e0ddd4] bg-[#faf9f3] px-3 py-2">
                <p className="font-mono text-xs font-semibold text-[#141413]">{field}</p>
                <p className="mt-1 text-[11px] leading-5 text-[#5f5b52]">
                  {t(`required.${field}` as never)}
                </p>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="grid gap-px border-t border-[#e0ddd4] bg-[#e0ddd4] lg:grid-cols-[0.95fr_1.05fr]">
        <div className="min-w-0 bg-[#fff7e8] p-4">
          <div className="flex items-center gap-2">
            <ShieldCheck className="h-4 w-4 text-[#8a5a08]" aria-hidden="true" />
            <h4 className="text-sm font-semibold text-[#141413]">{t("guardrailTitle")}</h4>
          </div>
          <p className="mt-2 text-xs leading-5 text-[#5f5b52]">{t("blocker")}</p>
          <div className="mt-3 flex flex-wrap gap-2">
            {REPAIR_CANDIDATE_DRAFT_BLOCKED_OPERATIONS.map((operation) => (
              <span
                key={operation}
                className="border border-[#d9b36f] bg-white px-2 py-0.5 font-mono text-[11px] font-semibold text-[#8a5a08]"
              >
                {operation}
              </span>
            ))}
          </div>
          <p className="mt-3 text-xs leading-5 text-[#5f5b52]">{t("nextStep")}</p>
        </div>

        <div className="min-w-0 bg-white p-4">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <div className="flex items-center gap-2">
              <GitBranch className="h-4 w-4 text-brand-accent" aria-hidden="true" />
              <h4 className="text-sm font-semibold text-[#141413]">{t("chainTitle")}</h4>
            </div>
            <div className="flex flex-wrap gap-2">
              <Link
                href={runsHref as never}
                className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
              >
                {t("openRuns")}
                <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
              </Link>
              <Link
                href={approvalsHref as never}
                className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
              >
                {t("openApprovals")}
                <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
              </Link>
            </div>
          </div>
          <div className="mt-3 grid gap-px bg-[#e0ddd4] sm:grid-cols-2">
            {chainRows.map(([label, value]) => (
              <div key={label} className="min-w-0 bg-[#faf9f3] px-3 py-2">
                <p className="text-xs font-semibold text-[#77736a]">{label}</p>
                <p className="mt-1 break-words font-mono text-xs text-[#141413]">
                  {value}
                </p>
              </div>
            ))}
          </div>
          <p className="mt-3 text-xs leading-5 text-[#77736a]">
            {t("chainHint")}
          </p>
        </div>
      </div>
    </section>
  );
}

function WorkItemIncidentAuditPanel({
  timeline,
  chain,
  focusedIncidentId,
  projectId,
  loading,
}: {
  timeline: IncidentTimelineResponse | null;
  chain: AwoooPStatusChain | null;
  focusedIncidentId: string | null;
  projectId: string;
  loading: boolean;
}) {
  const t = useTranslations("awooop.workItems.incidentAudit");
  const incidentId = focusedIncidentId ?? chain?.source_id ?? timeline?.incident_id ?? null;
  const stages = timeline?.timeline?.filter((stage) => stage.status !== "skipped") ?? [];
  const executor = timeline?.timeline?.find((stage) => stage.stage === "executor");
  const verifier = timeline?.timeline?.find((stage) => stage.stage === "verifier");
  const km = timeline?.timeline?.find((stage) => stage.stage === "km");
  const investigator = timeline?.timeline?.find((stage) => stage.stage === "investigator");
  const sourceCorrelation = chain?.source_refs?.correlation;
  const ansible = chain?.execution?.ansible;
  const timelineLoaded = Boolean(timeline);
  const importantEvents = (timeline?.events ?? [])
    .filter((event) => (
      event.source_table === "automation_operation_log" ||
      event.source_table === "knowledge_entries" ||
      event.source_table === "incident_evidence" ||
      event.source_table === "alert_operation_log" ||
      event.stage === "executor" ||
      event.stage === "verifier" ||
      event.stage === "km" ||
      event.stage === "ai_router"
    ))
    .slice(-5)
    .reverse();

  return (
    <section className="border border-[#e0ddd4] bg-white" aria-busy={loading && !timelineLoaded}>
      <div className="flex flex-wrap items-center justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex min-w-0 items-center gap-2">
          <SearchCheck className="h-4 w-4 text-brand-accent" aria-hidden="true" />
          <div className="min-w-0">
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 truncate font-mono text-xs text-[#77736a]">
              {incidentId ?? t("emptyIncident")}
            </p>
          </div>
        </div>
        <Link
          href={`/awooop/runs?project_id=${encodeURIComponent(projectId)}` as never}
          className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
        >
          {t("openRuns")}
          <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
        </Link>
      </div>

      {!incidentId ? (
        <div className="px-4 py-5 text-sm leading-6 text-[#77736a]">
          {t("empty")}
        </div>
      ) : (
        <>
          <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-4">
            <div className="min-w-0 bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{t("metrics.stages")}</p>
              <p className="mt-2 font-mono text-xl font-semibold text-[#141413]">
                {timelineLoaded ? stages.length : "--"}
              </p>
            </div>
            <div className="min-w-0 bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{t("metrics.events")}</p>
              <p className="mt-2 font-mono text-xl font-semibold text-[#141413]">
                {timelineLoaded ? timeline?.events?.length ?? 0 : "--"}
              </p>
            </div>
            <div className="min-w-0 bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{t("metrics.source")}</p>
              <p className="mt-2 truncate font-mono text-sm font-semibold text-[#141413]">
                {sourceCorrelation
                  ? `${sourceCorrelation.direct_ref_total ?? 0}/${sourceCorrelation.candidate_total ?? 0}/${sourceCorrelation.applied_link_total ?? 0}`
                  : "--"}
              </p>
            </div>
            <div className="min-w-0 bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{t("metrics.verification")}</p>
              <span className={cn("mt-2 inline-flex border px-2 py-0.5 text-xs font-semibold", auditStatusClass(verifier?.status ?? chain?.verification))}>
                {t(`statusLabels.${auditStatusLabelKey(verifier?.status ?? chain?.verification)}` as never)}
              </span>
            </div>
          </div>

          <div className="grid gap-px bg-[#e0ddd4] lg:grid-cols-[1.15fr_0.85fr]">
            <div className="min-w-0 bg-white p-4">
              <div className="flex items-center gap-2">
                <GitBranch className="h-4 w-4 text-brand-accent" aria-hidden="true" />
                <h4 className="text-sm font-semibold text-[#141413]">{t("flowTitle")}</h4>
              </div>
              {timeline?.ascii_timeline ? (
                <p className="mt-3 break-words border border-[#eee9dd] bg-[#faf9f3] px-3 py-2 font-mono text-xs leading-6 text-[#5f5b52]">
                  {timeline.ascii_timeline}
                </p>
              ) : (
                <p className="mt-3 text-sm text-[#77736a]">
                  {loading && !timelineLoaded ? t("loading") : t("timelineEmpty")}
                </p>
              )}
              {stages.length > 0 ? (
                <div className="mt-3 grid gap-2 md:grid-cols-2">
                  {stages.slice(0, 6).map((stage) => (
                    <div key={stage.stage} className="min-w-0 border border-[#eee9dd] bg-white px-3 py-2">
                      <div className="flex items-center justify-between gap-2">
                        <span className="truncate text-xs font-semibold text-[#77736a]">{stage.label}</span>
                        <span className={cn("shrink-0 border px-2 py-0.5 text-[11px] font-semibold", auditStatusClass(stage.status))}>
                          {t(`statusLabels.${auditStatusLabelKey(stage.status)}` as never)}
                        </span>
                      </div>
                      <p className="mt-1 truncate text-xs font-semibold text-[#141413]" title={stage.title}>
                        {stage.title}
                      </p>
                    </div>
                  ))}
                </div>
              ) : null}
            </div>

            <div className="min-w-0 bg-white p-4">
              <div className="flex items-center gap-2">
                <ListChecks className="h-4 w-4 text-brand-accent" aria-hidden="true" />
                <h4 className="text-sm font-semibold text-[#141413]">{t("evidenceTitle")}</h4>
              </div>
              <div className="mt-3 grid gap-px border border-[#e0ddd4] bg-[#e0ddd4]">
                {[
                  [t("executor"), executor?.title ?? chain?.execution?.latest_operation_type ?? "--"],
                  [t("ansible"), ansible?.latest_playbook_path ?? ansible?.latest_catalog_id ?? "--"],
                  [t("mcp"), investigator?.title ?? "--"],
                  [t("km"), km?.title ?? "--"],
                ].map(([label, value]) => (
                  <div key={label} className="min-w-0 bg-white px-3 py-2">
                    <p className="text-xs font-semibold text-[#77736a]">{label}</p>
                    <p className="mt-1 truncate font-mono text-xs text-[#141413]" title={value}>
                      {value}
                    </p>
                  </div>
                ))}
              </div>
              {importantEvents.length > 0 ? (
                <div className="mt-3 divide-y divide-[#eee9dd] border border-[#eee9dd]">
                  {importantEvents.map((event, index) => (
                    <div key={`${event.stage}-${event.timestamp}-${index}`} className="px-3 py-2">
                      <div className="flex flex-wrap items-center gap-2">
                        <span className={cn("border px-2 py-0.5 text-[11px] font-semibold", auditStatusClass(event.status))}>
                          {t(`statusLabels.${auditStatusLabelKey(event.status)}` as never)}
                        </span>
                        <span className="font-mono text-[11px] text-[#77736a]">{event.source_table ?? "--"}</span>
                      </div>
                      <p className="mt-1 truncate text-xs font-semibold text-[#141413]" title={event.title}>
                        {event.title}
                      </p>
                    </div>
                  ))}
                </div>
              ) : null}
            </div>
          </div>
        </>
      )}
    </section>
  );
}

function Adr100RemediationQueuePanel({
  queue,
  focusedWorkItemId,
  onRecorded,
}: {
  queue: RemediationQueue | null | undefined;
  focusedWorkItemId: string | null;
  onRecorded: () => void;
}) {
  const t = useTranslations("awooop.workItems.adr100Remediation");
  const [actionState, setActionState] = useState<Record<string, RecurrenceWorkItemActionState>>({});
  const items = queue?.items ?? [];
  const focusedItem = focusedWorkItemId
    ? items.find((item) => item.work_item_id === focusedWorkItemId)
    : null;
  const visibleItems = focusedItem
    ? [focusedItem, ...items.filter((item) => item !== focusedItem).slice(0, 5)]
    : items.slice(0, 6);

  const runAction = useCallback(async (
    item: RemediationQueueItem,
    action: "preview" | "dryRun" | "approval"
  ) => {
    const workItemId = item.work_item_id ?? "";
    if (!workItemId) return;
    setActionState((current) => ({
      ...current,
      [workItemId]: { ...current[workItemId], loading: action, error: null },
    }));

    const mode = item.remediation_status === "needs_playbook_ticket" ? "ticket" : "auto";
    try {
      const result = action === "preview"
        ? await fetchJson<RecurrenceWorkItemActionResult>(
            `${API_BASE}/api/v1/ai/slo/remediation/preview?work_item_id=${encodeURIComponent(workItemId)}&mode=${encodeURIComponent(mode)}`,
            12000
          )
        : action === "approval"
          ? await postJson<RecurrenceWorkItemActionResult>(
              `${API_BASE}/api/v1/ai/slo/remediation/approval-request`,
              { work_item_id: workItemId, mode: "approval" },
              15000
            )
          : await postJson<RecurrenceWorkItemActionResult>(
            `${API_BASE}/api/v1/ai/slo/remediation/dry-run`,
            { work_item_id: workItemId, mode },
            15000
          );

      setActionState((current) => ({
        ...current,
        [workItemId]: {
          loading: null,
          result,
          error: result ? null : t("actions.failed"),
        },
      }));
      if (result?.history?.recorded) {
        onRecorded();
      }
    } catch (error) {
      setActionState((current) => ({
        ...current,
        [workItemId]: {
          loading: null,
          result: null,
          error: error instanceof Error ? error.message : t("actions.failed"),
        },
      }));
    }
  }, [onRecorded, t]);

  return (
    <section className="border border-[#e0ddd4] bg-white">
      <div className="flex flex-wrap items-center justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex min-w-0 items-center gap-2">
          <ListChecks className="h-4 w-4 text-brand-accent" aria-hidden="true" />
          <div className="min-w-0">
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 text-xs leading-5 text-[#77736a]">
              {t("subtitle", {
                total: queue?.total ?? 0,
                ready: queue?.ready_for_ai ?? 0,
                human: queue?.needs_human ?? 0,
              })}
            </p>
          </div>
        </div>
        <Link
          href="/governance"
          className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
        >
          {t("openGovernance")}
          <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
        </Link>
      </div>

      {visibleItems.length === 0 ? (
        <div className="px-4 py-5 text-sm leading-6 text-[#77736a]">
          {t("empty")}
        </div>
      ) : (
        <div className="grid gap-px bg-[#e0ddd4] lg:grid-cols-2">
          {visibleItems.map((item) => {
            const workItemId = item.work_item_id ?? "";
            const state = workItemId ? actionState[workItemId] : undefined;
            const result = state?.result ?? null;
            const ticketPreview = result?.ticket_preview ?? null;
            const approval = result?.approval ?? null;
            const replayGate = result?.replay_gate ?? null;
            const canCreateApproval = item.remediation_status === "needs_playbook_ticket"
              || item.remediation_action === "promote_diagnostic_to_repair_playbook"
              || item.remediation_status === "ready_for_replay"
              || item.remediation_action === "replay_with_supported_executor";
            return (
              <article key={workItemId || item.incident_id || item.auto_repair_id} className="min-w-0 bg-white p-4">
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div className="min-w-0">
                    <p className="font-mono text-[11px] font-semibold text-[#77736a]">
                      {item.incident_id ?? "--"}
                    </p>
                    <h4 className="mt-1 truncate text-sm font-semibold text-[#141413]" title={item.alertname ?? undefined}>
                      {item.alertname ?? t("unknownAlert")}
                    </h4>
                  </div>
                  <span className={cn(
                    "inline-flex shrink-0 border px-2 py-0.5 text-[11px] font-semibold",
                    item.remediation_status === "needs_playbook_ticket"
                      ? "border-[#f4c7a1] bg-[#fff7ed] text-[#9a4c18]"
                      : item.remediation_status?.startsWith("ready")
                        ? "border-[#bbdfc5] bg-[#f1fbf3] text-[#24733d]"
                        : "border-[#ead5d5] bg-[#fff7f7] text-[#8b2f2f]"
                  )}>
                    {item.remediation_status ?? "--"}
                  </span>
                </div>

                <div className="mt-3 grid gap-2 text-xs leading-5 text-[#5f5b52] md:grid-cols-2">
                  <span className="min-w-0 truncate">
                    {t("fields.failure", { value: item.failure_class ?? "--" })}
                  </span>
                  <span className="min-w-0 truncate">
                    {t("fields.action", { value: item.remediation_action ?? "--" })}
                  </span>
                  <span className="min-w-0 truncate">
                    {t("fields.owner", { value: item.remediation_owner ?? "--" })}
                  </span>
                  <span className="min-w-0 truncate">
                    {t("fields.playbook", { value: item.playbook_id ?? "--" })}
                  </span>
                </div>

                <div className="mt-3 flex flex-wrap gap-2">
                  <button
                    type="button"
                    onClick={() => runAction(item, "preview")}
                    disabled={!workItemId || state?.loading === "preview"}
                    className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-[#faf9f3] px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#d97757] disabled:opacity-50"
                  >
                    <SearchCheck className="h-3.5 w-3.5" aria-hidden="true" />
                    {state?.loading === "preview" ? t("actions.loading") : t("actions.preview")}
                  </button>
                  <button
                    type="button"
                    onClick={() => runAction(item, "dryRun")}
                    disabled={!workItemId || state?.loading === "dryRun"}
                    className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#d97757] disabled:opacity-50"
                  >
                    <FileText className="h-3.5 w-3.5" aria-hidden="true" />
                    {state?.loading === "dryRun" ? t("actions.loading") : t("actions.dryRun")}
                  </button>
                  {canCreateApproval ? (
                    <button
                      type="button"
                      onClick={() => runAction(item, "approval")}
                      disabled={!workItemId || state?.loading === "approval"}
                      className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#d97757] disabled:opacity-50"
                    >
                      <ShieldCheck className="h-3.5 w-3.5" aria-hidden="true" />
                      {state?.loading === "approval" ? t("actions.loading") : t("actions.approval")}
                    </button>
                  ) : null}
                </div>

                {state?.error ? (
                  <p className="mt-3 border border-[#ead5d5] bg-[#fff7f7] px-3 py-2 text-xs leading-5 text-[#8b2f2f]">
                    {state.error}
                  </p>
                ) : null}

                {result ? (
                  <div className="mt-3 border border-[#eee9dd] bg-[#faf9f3] px-3 py-2 text-xs leading-5 text-[#5f5b52]">
                    <div className="flex flex-wrap gap-2">
                      <span className="font-mono">{t("result.mode", { value: result.mode ?? "--" })}</span>
                      <span className="font-mono">{t("result.allowed", { value: String(result.allowed ?? false) })}</span>
                      <span className="font-mono">{t("result.writes", {
                        incident: String(result.writes_incident_state ?? false),
                        autoRepair: String(result.writes_auto_repair_result ?? false),
                      })}</span>
                      {result.writes_approval_record ? (
                        <span className="font-mono">{t("result.approvalWrite")}</span>
                      ) : null}
                      {result.deduplicated ? (
                        <span className="font-mono">{t("result.deduplicated")}</span>
                      ) : null}
                    </div>
                    {approval ? (
                      <p className="mt-2 font-mono text-[11px] text-[#5f5b52]">
                        {t("result.approval", {
                          id: approval.id ?? result.approval_id ?? "--",
                          status: approval.status ?? "--",
                          risk: approval.risk_level ?? "--",
                        })}
                      </p>
                    ) : null}
                    {ticketPreview ? (
                      <div className="mt-2 border-t border-[#e0ddd4] pt-2">
                        <p className="font-semibold text-[#141413]">{ticketPreview.title ?? t("ticketFallback")}</p>
                        <p className="mt-1 line-clamp-3 whitespace-pre-line text-[#5f5b52]">
                          {ticketPreview.body_preview ?? "--"}
                        </p>
                      </div>
                    ) : null}
                    {replayGate ? (
                      <div className="mt-2 border-t border-[#e0ddd4] pt-2">
                        <p className="font-semibold text-[#141413]">{t("replayGate.title")}</p>
                        <div className="mt-1 grid gap-1 font-mono text-[11px] text-[#5f5b52] sm:grid-cols-2">
                          <span>{t("replayGate.status", { value: replayGate.status ?? "--" })}</span>
                          <span>{t("replayGate.next", { value: replayGate.next_step ?? "--" })}</span>
                          <span>{t("replayGate.routes", {
                            write: replayGate.supported_write_route_count ?? 0,
                            unsupported: replayGate.unsupported_step_count ?? 0,
                          })}</span>
                          <span>{t("replayGate.auth", {
                            authorized: String(replayGate.execution_authorized ?? false),
                            executed: String(replayGate.repair_executed ?? false),
                          })}</span>
                        </div>
                      </div>
                    ) : null}
                  </div>
                ) : null}
              </article>
            );
          })}
        </div>
      )}
    </section>
  );
}

function RecurrenceWorkQueuePanel({
  recurrence,
  focusedWorkItemId,
  focusedIncidentId,
  projectId,
  onRecorded,
}: {
  recurrence: RecurrenceResponse | null;
  focusedWorkItemId: string | null;
  focusedIncidentId: string | null;
  projectId: string;
  onRecorded: () => void;
}) {
  const t = useTranslations("awooop.workItems.recurrence");
  const [actionState, setActionState] = useState<Record<string, RecurrenceWorkItemActionState>>({});
  const allItems = recurrence?.items ?? [];
  const openItems = recurrenceOpenItems(recurrence);
  const focusedItem = focusedWorkItemId
    ? allItems.find((item) => item.work_item?.work_item_id === focusedWorkItemId)
    : null;
  const visibleItems = focusedItem
    ? [focusedItem, ...openItems.filter((item) => item !== focusedItem).slice(0, 5)]
    : openItems.slice(0, 6);
  const summary = recurrence?.summary;
  const runWorkItemAction = useCallback(async (
    workItemId: string,
    action:
      | "preview"
      | "dryRun"
      | "handoff"
      | "acceptSource"
      | "rejectSource"
      | "applySource",
    targetIncidentId?: string | null
  ) => {
    setActionState((current) => ({
      ...current,
      [workItemId]: { ...current[workItemId], loading: action, error: null },
    }));

    const encodedProjectId = encodeURIComponent(projectId);
    const encodedWorkItemId = encodeURIComponent(workItemId);
    let result: RecurrenceWorkItemActionResult | null = null;
    if (action === "preview") {
      result = await fetchJson<RecurrenceWorkItemActionResult>(
        `${API_BASE}/api/v1/platform/events/dossier/recurrence/work-item/preview?project_id=${encodedProjectId}&work_item_id=${encodedWorkItemId}`,
        12000
      );
    } else if (action === "dryRun") {
      result = await postJson<RecurrenceWorkItemActionResult>(
        `${API_BASE}/api/v1/platform/events/dossier/recurrence/work-item/dry-run`,
        {
          project_id: projectId,
          work_item_id: workItemId,
          mode: "auto",
          limit: 300,
        },
        15000
      );
    } else if (action === "handoff") {
      result = await postJson<RecurrenceWorkItemActionResult>(
        `${API_BASE}/api/v1/platform/events/dossier/recurrence/work-item/handoff`,
        {
          project_id: projectId,
          work_item_id: workItemId,
          mode: "auto",
          handoff_kind: "ticket_proposal",
          limit: 300,
        },
        15000
      );
    } else if (action === "applySource") {
      result = await postJson<RecurrenceWorkItemActionResult>(
        `${API_BASE}/api/v1/platform/events/dossier/recurrence/source-correlation/apply`,
        {
          project_id: projectId,
          work_item_id: workItemId,
          reviewer_id: "operator_console",
          operator_note: "operator_console_apply_source_match",
          limit: 300,
        },
        15000
      );
    } else {
      result = await postJson<RecurrenceWorkItemActionResult>(
        `${API_BASE}/api/v1/platform/events/dossier/recurrence/source-correlation/review`,
        {
          project_id: projectId,
          work_item_id: workItemId,
          decision: action === "acceptSource" ? "accepted" : "rejected",
          target_incident_id: action === "acceptSource" ? targetIncidentId : undefined,
          reviewer_id: "operator_console",
          operator_note: action === "acceptSource"
            ? "operator_console_source_match"
            : "operator_console_source_rejected",
          limit: 300,
        },
        15000
      );
    }

    setActionState((current) => ({
      ...current,
      [workItemId]: {
        loading: null,
        result,
        error: result ? null : t("actions.failed"),
      },
    }));
    if (
      result?.history?.recorded ||
      result?.review_record_status === "recorded" ||
      result?.apply_status === "applied" ||
      result?.apply_status === "partial"
    ) {
      onRecorded();
    }
  }, [onRecorded, projectId, t]);

  return (
    <section className="border border-[#e0ddd4] bg-white">
      <div className="flex flex-wrap items-center justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex items-center gap-2">
          <ListChecks className="h-4 w-4 text-[#8a5a08]" aria-hidden="true" />
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="text-xs text-[#77736a]">{t("subtitle")}</p>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2 font-mono text-xs text-[#5f5b52]">
          <span className="border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5">
            {t("open", { count: summary?.open_work_item_group_total ?? 0 })}
          </span>
          <span className="border border-[#d8d3c7] bg-white px-2 py-0.5">
            {t("automationGap", { count: summary?.automation_gap_group_total ?? 0 })}
          </span>
          <span className="border border-[#d8d3c7] bg-white px-2 py-0.5">
            {t("failed", { count: summary?.failed_repair_group_total ?? 0 })}
          </span>
          <span className="border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5">
            {t("sourceReview", {
              count: summary?.source_correlation_review_group_total ?? 0,
            })}
          </span>
          <span className="border border-[#9bc7a4] bg-[#f0faf2] px-2 py-0.5 text-[#17602a]">
            {t("sourceApplied", {
              count: summary?.source_correlation_applied_group_total ?? 0,
            })}
          </span>
        </div>
      </div>

      {recurrence === null ? (
        <div className="px-4 py-4 text-sm text-[#8a5a08]">
          {t("unavailable")}
        </div>
      ) : visibleItems.length === 0 ? (
        <div className="px-4 py-4 text-sm text-[#5f5b52]">
          {t("empty")}
        </div>
      ) : (
        <div className="grid gap-px bg-[#eee9dd] md:grid-cols-2 xl:grid-cols-3">
          {visibleItems.map((item) => {
            const workItem = item.work_item;
            const workItemId = workItem?.work_item_id ?? "";
            const isFocused = Boolean(
              focusedWorkItemId && workItemId === focusedWorkItemId
            );
            const repairStatusKey = recurrenceRepairStatusKey(item.repair_summary?.status);
            const runHref = item.latest_run_id
              ? `/awooop/runs/${item.latest_run_id}?project_id=${encodeURIComponent(projectId)}`
              : null;
            const currentAction = workItemId ? actionState[workItemId] : null;
            const actionResult = currentAction?.result;
            const actionAllowed = actionResult?.allowed === true;
            const actionModeKey = recurrenceActionModeKey(actionResult?.mode);
            const previewKey = recurrencePreviewKey(actionResult?.verification_result_preview);
            const handoffStatusKey = recurrenceHandoffStatusKey(actionResult?.handoff_status);
            const handoffKindKey = recurrenceHandoffKindKey(actionResult?.handoff_kind);
            const sourceReview = item.source_correlation_review;
            const sourceApply = item.source_correlation_apply;
            const isSourceReview = workItem?.kind === "source_correlation_review";
            const workItemOpen = workItem?.status === "open";
            const targetIncidentId = firstIncidentId(
              focusedIncidentId,
              workItem?.matched_incident_id,
              sourceReview?.target_incident_id,
              item.latest_incident_id,
              workItem?.incident_id
            );
            const sourceDecisionKey = sourceReviewDecisionKey(
              actionResult?.decision ?? sourceReview?.decision
            );
            const reviewRecordStatusKey = sourceReviewRecordStatusKey(
              actionResult?.review_record_status ??
                actionResult?.review_status ??
                sourceReview?.review_status
            );
            const sourceApplyStatus = actionResult?.apply_status ?? sourceApply?.apply_status;
            const sourceApplyStatusKeyValue = sourceApplyStatusKey(sourceApplyStatus);
            const sourceFlowStatus = recurrenceSourceFlowStatus({
              item,
              actionResult,
              sourceApplyStatus: sourceApplyStatusKeyValue,
              sourceDecision: sourceDecisionKey,
              reviewStatus: reviewRecordStatusKey,
            });
            const SourceFlowIcon = recurrenceSourceFlowIcon(sourceFlowStatus);
            const sourceFlowEvent =
              actionResult?.source_event_provider_event_id ??
              sourceApply?.source_event_provider_event_id ??
              item.latest_provider_event_id ??
              "--";
            const canApplySource =
              isSourceReview &&
              sourceReview?.decision === "accepted" &&
              Boolean(targetIncidentId) &&
              sourceApplyStatusKeyValue !== "applied";

            return (
              <article
                key={workItemId || item.recurrence_key}
                className={cn(
                  "bg-white px-4 py-3",
                  isFocused && "outline outline-2 outline-[#d97757]"
                )}
              >
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <p className="truncate font-mono text-xs font-semibold text-[#141413]">
                      {item.alertname || item.provider || item.recurrence_key}
                    </p>
                    <p className="mt-1 truncate text-xs text-[#77736a]">
                      {item.namespace || "--"} / {item.target_resource || "--"}
                    </p>
                  </div>
                  <span className="shrink-0 border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5 font-mono text-xs font-semibold text-[#8a5a08]">
                    {t("occurrences", { count: item.occurrence_total })}
                  </span>
                </div>
                <div className="mt-3 grid gap-1 text-xs leading-5 text-[#5f5b52]">
                  <p>{t("incident", { incident: item.latest_incident_id ?? "--" })}</p>
                  {isSourceReview ? (
                    <p>
                      {t("matchedIncident", {
                        incident: targetIncidentId ?? "--",
                      })}
                    </p>
                  ) : null}
                  <p>{t("stage", { stage: item.latest_stage ?? "--" })}</p>
                  <p className="truncate">
                    {t("sourceEvent", {
                      event: item.latest_provider_event_id ?? "--",
                    })}
                  </p>
                  <p>
                    {t("sourceRefs", {
                      refs: item.source_ref_total ?? 0,
                      sentry: item.sentry_ref_total ?? 0,
                      signoz: item.signoz_ref_total ?? 0,
                    })}
                  </p>
                  <div className="grid gap-1">
                    <span
                      className={cn(
                        "inline-flex w-fit items-center gap-1.5 border px-2 py-1 font-semibold",
                        recurrenceSourceFlowClass(sourceFlowStatus)
                      )}
                    >
                      <SourceFlowIcon className="h-3.5 w-3.5" aria-hidden="true" />
                      {t("sourceFlow.label", {
                        status: t(`sourceFlow.statuses.${sourceFlowStatus}` as never),
                      })}
                    </span>
                    <p
                      className="truncate font-mono text-xs text-[#77736a]"
                      title={t("sourceFlow.detail", {
                        refs: item.source_ref_total ?? 0,
                        sentry: item.sentry_ref_total ?? 0,
                        signoz: item.signoz_ref_total ?? 0,
                        event: sourceFlowEvent,
                      })}
                    >
                      {t("sourceFlow.detail", {
                        refs: item.source_ref_total ?? 0,
                        sentry: item.sentry_ref_total ?? 0,
                        signoz: item.signoz_ref_total ?? 0,
                        event: sourceFlowEvent,
                      })}
                    </p>
                  </div>
                  <p>{t("workItem", { id: workItem?.work_item_id ?? "--" })}</p>
                  <p>
                    {t("repair", {
                      status: t(`statuses.${repairStatusKey}` as never),
                    })}
                  </p>
                  <p>
                    {t("reason", {
                      reason: t(`reasons.${workItem?.reason ?? "unknown"}` as never),
                    })}
                  </p>
                  <p>
                    {t("nextStep", {
                      step: t(`nextSteps.${workItem?.next_step ?? "none"}` as never),
                    })}
                  </p>
                  {sourceReview ? (
                    <p>
                      {t("sourceReviewDecision", {
                        decision: t(`actions.sourceDecisions.${sourceDecisionKey}` as never),
                        status: t(
                          `actions.sourceRecordStatuses.${reviewRecordStatusKey}` as never
                        ),
                      })}
                    </p>
                  ) : null}
                  {sourceApply || actionResult?.apply_status ? (
                    <p>
                      {t("sourceApplyStatus", {
                        status: t(
                          `actions.sourceApplyStatuses.${sourceApplyStatusKeyValue}` as never
                        ),
                        event:
                          actionResult?.source_event_provider_event_id ??
                          sourceApply?.source_event_provider_event_id ??
                          "--",
                      })}
                    </p>
                  ) : null}
                </div>
                <div className="mt-3 flex flex-wrap items-center gap-2">
                  {workItemId ? (
                    <>
                      <button
                        type="button"
                        onClick={() => runWorkItemAction(workItemId, "preview")}
                        disabled={currentAction?.loading === "preview"}
                        className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#1f6feb] hover:bg-[#edf4ff] hover:text-[#0f4fa8] disabled:cursor-not-allowed disabled:opacity-60"
                      >
                        <SearchCheck className="h-3.5 w-3.5" aria-hidden="true" />
                        {currentAction?.loading === "preview"
                          ? t("actions.previewing")
                          : t("actions.preview")}
                      </button>
                      <button
                        type="button"
                        onClick={() => runWorkItemAction(workItemId, "dryRun")}
                        disabled={currentAction?.loading === "dryRun"}
                        className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#d97757] hover:bg-[#fff7e8] hover:text-[#8a5a08] disabled:cursor-not-allowed disabled:opacity-60"
                      >
                        <Gauge className="h-3.5 w-3.5" aria-hidden="true" />
                        {currentAction?.loading === "dryRun"
                          ? t("actions.dryRunning")
                          : t("actions.dryRun")}
                      </button>
                      <button
                        type="button"
                        onClick={() => runWorkItemAction(workItemId, "handoff")}
                        disabled={currentAction?.loading === "handoff"}
                        className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#9bc7a4] hover:bg-[#f0faf2] hover:text-[#17602a] disabled:cursor-not-allowed disabled:opacity-60"
                      >
                        <GitBranch className="h-3.5 w-3.5" aria-hidden="true" />
                        {currentAction?.loading === "handoff"
                          ? t("actions.handoffing")
                          : t("actions.handoff")}
                      </button>
                      {isSourceReview ? (
                        <>
                          <button
                            type="button"
                            onClick={() => runWorkItemAction(
                              workItemId,
                              "acceptSource",
                              targetIncidentId
                            )}
                            disabled={
                              currentAction?.loading === "acceptSource" ||
                              !targetIncidentId ||
                              !workItemOpen
                            }
                            className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#9bc7a4] hover:bg-[#f0faf2] hover:text-[#17602a] disabled:cursor-not-allowed disabled:opacity-60"
                          >
                            <ShieldCheck className="h-3.5 w-3.5" aria-hidden="true" />
                            {currentAction?.loading === "acceptSource"
                              ? t("actions.sourceAccepting")
                              : t("actions.sourceAccept")}
                          </button>
                          <button
                            type="button"
                            onClick={() => runWorkItemAction(workItemId, "rejectSource")}
                            disabled={
                              currentAction?.loading === "rejectSource" ||
                              !workItemOpen
                            }
                            className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#e2a29b] hover:bg-[#fff0ef] hover:text-[#9f2f25] disabled:cursor-not-allowed disabled:opacity-60"
                          >
                            <Archive className="h-3.5 w-3.5" aria-hidden="true" />
                            {currentAction?.loading === "rejectSource"
                              ? t("actions.sourceRejecting")
                              : t("actions.sourceReject")}
                          </button>
                          <button
                            type="button"
                            onClick={() => runWorkItemAction(workItemId, "applySource")}
                            disabled={
                              currentAction?.loading === "applySource" ||
                              !canApplySource
                            }
                            className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#1f6feb] hover:bg-[#edf4ff] hover:text-[#0f4fa8] disabled:cursor-not-allowed disabled:opacity-60"
                          >
                            <GitBranch className="h-3.5 w-3.5" aria-hidden="true" />
                            {currentAction?.loading === "applySource"
                              ? t("actions.sourceApplying")
                              : t("actions.sourceApply")}
                          </button>
                        </>
                      ) : null}
                    </>
                  ) : null}
                  {runHref ? (
                    <Link
                      href={runHref as never}
                      className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#1f6feb] hover:bg-[#edf4ff] hover:text-[#0f4fa8]"
                    >
                      <SearchCheck className="h-3.5 w-3.5" aria-hidden="true" />
                      {t("openRun")}
                    </Link>
                  ) : null}
                  <Link
                    href={`/awooop/runs?project_id=${encodeURIComponent(projectId)}` as never}
                    className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#1f6feb] hover:bg-[#edf4ff] hover:text-[#0f4fa8]"
                  >
                    <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
                    {t("openRuns")}
                  </Link>
                </div>
                {currentAction?.error ? (
                  <div className="mt-3 border border-[#e2a29b] bg-[#fff0ef] px-3 py-2 text-xs leading-5 text-[#9f2f25]">
                    {currentAction.error}
                  </div>
                ) : null}
                {actionResult ? (
                  <div
                    className={cn(
                      "mt-3 border px-3 py-2 text-xs leading-5",
                      actionAllowed
                        ? "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]"
                        : "border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]"
                    )}
                  >
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <span className="font-semibold">
                        {actionAllowed ? t("actions.allowed") : t("actions.blocked")}
                      </span>
                      <span className="font-mono">
                        {t("actions.mode", {
                          mode: t(`actions.modes.${actionModeKey}` as never),
                        })}
                      </span>
                    </div>
                    <div className="mt-1 grid gap-1 text-[#5f5b52]">
                      <p>
                        {t("actions.previewResult", {
                          result: t(`actions.previews.${previewKey}` as never),
                        })}
                      </p>
                      <p>
                        {t("actions.writes", {
                          incident: String(actionResult.writes_incident_state ?? false),
                          autoRepair: String(actionResult.writes_auto_repair_result ?? false),
                          ticket: String(actionResult.writes_ticket ?? false),
                        })}
                      </p>
                      {actionResult.writes_source_event !== undefined ? (
                        <p>
                          {t("actions.sourceWrites", {
                            source: String(actionResult.writes_source_event ?? false),
                          })}
                        </p>
                      ) : null}
                      <p>
                        {t("actions.history", {
                          recorded: String(actionResult.history?.recorded ?? false),
                        })}
                      </p>
                      {actionResult.decision ? (
                        <p>
                          {t("actions.sourceReviewResult", {
                            decision: t(`actions.sourceDecisions.${sourceDecisionKey}` as never),
                            status: t(
                              `actions.sourceRecordStatuses.${reviewRecordStatusKey}` as never
                            ),
                            incident: actionResult.target_incident_id ?? "--",
                          })}
                        </p>
                      ) : null}
                      {actionResult.apply_status ? (
                        <p>
                          {t("actions.sourceApplyResult", {
                            status: t(
                              `actions.sourceApplyStatuses.${sourceApplyStatusKeyValue}` as never
                            ),
                            event: actionResult.source_event_provider_event_id ?? "--",
                          })}
                        </p>
                      ) : null}
                      {actionResult.handoff_status ? (
                        <p>
                          {t("actions.handoffStatus", {
                            status: t(`actions.handoffStatuses.${handoffStatusKey}` as never),
                            kind: t(`actions.handoffKinds.${handoffKindKey}` as never),
                          })}
                        </p>
                      ) : null}
                      {actionResult.creates_external_ticket !== undefined ? (
                        <p>
                          {t("actions.externalTicket", {
                            created: String(actionResult.creates_external_ticket ?? false),
                          })}
                        </p>
                      ) : null}
                      {actionResult.ticket_preview?.title ? (
                        <p className="truncate">
                          {t("actions.ticket", {
                            title: actionResult.ticket_preview.title,
                          })}
                        </p>
                      ) : null}
                    </div>
                  </div>
                ) : null}
              </article>
            );
          })}
        </div>
      )}
    </section>
  );
}

function KnowledgeGovernancePanel({
  queue,
  reviewDrafts,
  dedupe,
  staleCandidates,
  ownerReviewInbox,
  burnDown,
  completionQueue,
  onArchived,
}: {
  queue: GovernanceQueueResponse | null;
  reviewDrafts: KnowledgeListResponse | null;
  dedupe: KnowledgeReviewDraftDedupeResponse | null;
  staleCandidates: KnowledgeStaleCandidatesResponse | null;
  ownerReviewInbox: KnowledgeStaleOwnerReviewInboxResponse | null;
  burnDown: KnowledgeStaleOwnerReviewBurnDownResponse | null;
  completionQueue: KnowledgeStaleOwnerReviewCompletionQueueResponse | null;
  onArchived: () => void;
}) {
  const t = useTranslations("awooop.workItems.knowledgeGovernance");
  const [archiveActions, setArchiveActions] = useState<Record<string, KnowledgeReviewDraftArchiveAction>>({});
  const [staleReviewActions, setStaleReviewActions] = useState<Record<string, KnowledgeStaleOwnerReviewAction>>({});
  const [staleBatchAction, setStaleBatchAction] = useState<KnowledgeStaleOwnerReviewBatchAction>({
    previewLoading: false,
    confirmLoading: false,
    previewResult: null,
    result: null,
    error: null,
  });
  const [staleReviewCompletionActions, setStaleReviewCompletionActions] =
    useState<Record<string, KnowledgeStaleOwnerReviewCompleteAction>>({});
  const [completionReadinessFilter, setCompletionReadinessFilter] =
    useState<"all" | "ready" | "blocked" | "completed" | "failed" | "pending">("ready");
  const [completionPriorityFilter, setCompletionPriorityFilter] =
    useState<"all" | "P0" | "P1" | "P2">("all");
  const [completionBatchPreviewAction, setCompletionBatchPreviewAction] =
    useState<KnowledgeStaleOwnerReviewCompletionBatchPreviewAction>({
      loading: false,
      result: null,
      error: null,
    });
  const items = queue?.items ?? [];
  const draftGroups = groupKnowledgeReviewDrafts(reviewDrafts, items);
  const dedupeGroups = dedupe?.groups ?? [];
  const duplicateDraftCount = (
    dedupe?.duplicate_draft_total
    ?? draftGroups.reduce((sum, group) => sum + group.duplicateCount, 0)
  );
  const staleCandidateItems = staleCandidates?.items ?? [];
  const ownerReviewItems = ownerReviewInbox?.items ?? [];
  const burnDownItems = burnDown?.items ?? [];
  const burnDownSnapshot = burnDown?.current_snapshot ?? null;
  const completionQueueItems = useMemo(
    () => (completionQueue?.items ?? []).filter((item) => {
      const readinessMatches =
        completionReadinessFilter === "all" ||
        (completionReadinessFilter === "pending"
          ? ["pending", "dispatched", "executing"].includes(item.dispatch_status)
          : item.readiness === completionReadinessFilter);
      const priorityMatches =
        completionPriorityFilter === "all" ||
        item.priority_tier === completionPriorityFilter;
      return readinessMatches && priorityMatches;
    }),
    [completionPriorityFilter, completionQueue?.items, completionReadinessFilter]
  );
  const draftTotal = dedupe?.total_review_drafts ?? reviewDrafts?.total ?? 0;
  const activeCount = items.filter((item) =>
    ["pending", "dispatched", "executing"].includes(item.dispatch_status)
  ).length;
  const reviewCount = items.filter((item) =>
    item.dispatch_status === "skipped" || item.workflow_stage === "waiting_owner_review"
  ).length;
  const ownerReviewOperation = useMemo(() => {
    const staleCount = burnDownSnapshot?.stale_count ?? staleCandidates?.total_stale ?? 0;
    const totalCount = burnDownSnapshot?.total_count ?? 0;
    const staleRatio = burnDownSnapshot
      ? formatStaleRatio(burnDownSnapshot.stale_ratio)
      : "--";
    const threshold = burnDownSnapshot
      ? formatStaleRatio(burnDownSnapshot.threshold)
      : "--";
    const pending = completionQueue?.pending_count ?? ownerReviewInbox?.total ?? 0;
    const ready = completionQueue?.ready_count ?? 0;
    const blocked = completionQueue?.blocked_count ?? 0;
    const completed = completionQueue?.completed_count ?? burnDown?.completed_owner_reviews ?? 0;
    const failed = completionQueue?.failed_count ?? 0;
    const auditTotal = burnDown?.completion_audit_total ?? completed;
    const recheckTotal = burnDown?.stale_ratio_recheck_total ?? 0;
    const remaining = burnDown?.entries_to_threshold ?? 0;
    const writesOnRead = Boolean(
      staleCandidates?.writes_on_read ||
      ownerReviewInbox?.writes_on_read ||
      completionQueue?.writes_on_read ||
      burnDown?.writes_on_read
    );
    const manualReviewRequired = Boolean(
      staleCandidates?.manual_review_required ??
      ownerReviewInbox?.manual_review_required ??
      completionQueue?.manual_review_required ??
      burnDown?.manual_review_required ??
      true
    );
    const batchWritesAllowed = Boolean(completionQueue?.batch_writes_allowed ?? false);
    const nextActionKey =
      completionQueue === null
        ? "waitData"
        : blocked > 0
          ? "clearBlocked"
          : ready > 0
            ? "previewReady"
            : pending > 0
              ? "waitOwner"
              : staleCount > 0
                ? "queueReview"
                : "stable";

    const nodeTone = (state: "warning" | "ready" | "waiting" | "done" | "blocked") => {
      switch (state) {
        case "warning":
          return "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]";
        case "ready":
          return "border-[#9bb6d9] bg-[#eef5ff] text-[#1f5b9b]";
        case "done":
          return "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]";
        case "blocked":
          return "border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]";
        default:
          return "border-[#d8d3c7] bg-white text-[#5f5b52]";
      }
    };

    const flowNodes = [
      {
        key: "detected",
        icon: TriangleAlert,
        value: staleCount,
        state: burnDown?.burn_down_status === "above_threshold" ? "warning" : "done",
        detail: t("staleCandidates.operationRail.flow.detail.detected", {
          ratio: staleRatio,
          threshold,
        }),
      },
      {
        key: "ownerReview",
        icon: ClipboardList,
        value: pending,
        state: pending > 0 ? "warning" : "done",
        detail: t("staleCandidates.operationRail.flow.detail.ownerReview", {
          count: pending,
        }),
      },
      {
        key: "dryRun",
        icon: SearchCheck,
        value: ready,
        state: blocked > 0 ? "blocked" : ready > 0 ? "ready" : "waiting",
        detail: t("staleCandidates.operationRail.flow.detail.dryRun", {
          ready,
          blocked,
        }),
      },
      {
        key: "ownerConfirm",
        icon: ShieldCheck,
        value: ready,
        state: ready > 0 ? "ready" : failed > 0 ? "blocked" : "waiting",
        detail: t("staleCandidates.operationRail.flow.detail.ownerConfirm"),
      },
      {
        key: "writeback",
        icon: Database,
        value: auditTotal,
        state: auditTotal > 0 ? "done" : "waiting",
        detail: t("staleCandidates.operationRail.flow.detail.writeback", {
          count: auditTotal,
        }),
      },
      {
        key: "recheck",
        icon: RefreshCw,
        value: recheckTotal,
        state: recheckTotal > 0 ? "done" : "waiting",
        detail: t("staleCandidates.operationRail.flow.detail.recheck", {
          count: recheckTotal,
          remaining,
        }),
      },
    ].map((node) => ({
      ...node,
      tone: nodeTone(node.state as "warning" | "ready" | "waiting" | "done" | "blocked"),
    }));

    return {
      staleCount,
      totalCount,
      staleRatio,
      threshold,
      pending,
      ready,
      blocked,
      completed,
      failed,
      remaining,
      writesOnRead,
      manualReviewRequired,
      batchWritesAllowed,
      nextActionKey,
      flowNodes,
    };
  }, [
    burnDown,
    burnDownSnapshot,
    completionQueue,
    ownerReviewInbox,
    staleCandidates,
    t,
  ]);
  const previewArchiveDuplicates = useCallback(async (group: KnowledgeReviewDraftDedupeGroup) => {
    setArchiveActions((current) => ({
      ...current,
      [group.governance_event_id]: {
        previewLoading: true,
        confirmLoading: false,
        previewResult: current[group.governance_event_id]?.previewResult ?? null,
        result: null,
        error: null,
      },
    }));
    const result = await postJson<KnowledgeReviewDraftArchiveResponse>(
      `${API_BASE}/api/v1/ai/governance/km-review-drafts/dedupe/${encodeURIComponent(group.governance_event_id)}/archive-duplicates`,
      {
        canonical_entry_id: group.canonical_entry_id,
        duplicate_entry_ids: group.duplicate_entry_ids,
        owner: "operator_console",
        owner_approved: false,
        dry_run: true,
      },
      15000
    );
    setArchiveActions((current) => ({
      ...current,
      [group.governance_event_id]: {
        previewLoading: false,
        confirmLoading: false,
        previewResult: result,
        result: null,
        error: result ? null : t("archiveActions.previewFailed"),
      },
    }));
  }, [t]);

  const confirmArchiveDuplicates = useCallback(async (group: KnowledgeReviewDraftDedupeGroup) => {
    const dryRunPlanFingerprint =
      archiveActions[group.governance_event_id]?.previewResult?.dry_run_plan_fingerprint;
    if (!dryRunPlanFingerprint) {
      setArchiveActions((current) => ({
        ...current,
        [group.governance_event_id]: {
          previewLoading: false,
          confirmLoading: false,
          previewResult: current[group.governance_event_id]?.previewResult ?? null,
          result: null,
          error: t("archiveActions.missingPreviewFingerprint"),
        },
      }));
      return;
    }

    setArchiveActions((current) => ({
      ...current,
      [group.governance_event_id]: {
        previewLoading: false,
        confirmLoading: true,
        previewResult: current[group.governance_event_id]?.previewResult ?? null,
        result: null,
        error: null,
      },
    }));
    const result = await postJson<KnowledgeReviewDraftArchiveResponse>(
      `${API_BASE}/api/v1/ai/governance/km-review-drafts/dedupe/${encodeURIComponent(group.governance_event_id)}/archive-duplicates`,
      {
        canonical_entry_id: group.canonical_entry_id,
        duplicate_entry_ids: group.duplicate_entry_ids,
        owner: "operator_console",
        owner_approved: true,
        dry_run: false,
        dry_run_plan_fingerprint: dryRunPlanFingerprint,
      },
      15000
    );
    setArchiveActions((current) => ({
      ...current,
      [group.governance_event_id]: {
        previewLoading: false,
        confirmLoading: false,
        previewResult: current[group.governance_event_id]?.previewResult ?? null,
        result,
        error: result ? null : t("archiveActions.confirmFailed"),
      },
    }));
    if (result?.status === "archived" || result?.status === "noop_already_archived") {
      onArchived();
    }
  }, [archiveActions, onArchived, t]);

  const previewStaleBatchQueue = useCallback(async () => {
    setStaleBatchAction((current) => ({
      previewLoading: true,
      confirmLoading: false,
      previewResult: current.previewResult,
      result: null,
      error: null,
    }));
    const result = await postJson<KnowledgeStaleOwnerReviewBatchResponse>(
      `${API_BASE}/api/v1/ai/governance/km-stale-candidates/batch-queue-review`,
      {
        project_id: staleCandidates?.project_id ?? "awoooi",
        priority_tiers: ["P0", "P1"],
        limit: 10,
        owner: "operator_console",
        owner_note: "p0_p1_stale_km_batch",
        dry_run: true,
      },
      15000
    );
    setStaleBatchAction({
      previewLoading: false,
      confirmLoading: false,
      previewResult: result,
      result: null,
      error: result ? null : t("staleCandidates.batchActions.previewFailed"),
    });
  }, [staleCandidates?.project_id, t]);

  const confirmStaleBatchQueue = useCallback(async () => {
    const fingerprint = staleBatchAction.previewResult?.dry_run_plan_fingerprint;
    if (!fingerprint) {
      setStaleBatchAction((current) => ({
        previewLoading: false,
        confirmLoading: false,
        previewResult: current.previewResult,
        result: current.result,
        error: t("staleCandidates.batchActions.missingPreviewFingerprint"),
      }));
      return;
    }
    setStaleBatchAction((current) => ({
      previewLoading: false,
      confirmLoading: true,
      previewResult: current.previewResult,
      result: null,
      error: null,
    }));
    const result = await postJson<KnowledgeStaleOwnerReviewBatchResponse>(
      `${API_BASE}/api/v1/ai/governance/km-stale-candidates/batch-queue-review`,
      {
        project_id: staleCandidates?.project_id ?? "awoooi",
        priority_tiers: ["P0", "P1"],
        limit: 10,
        owner: "operator_console",
        owner_note: "p0_p1_stale_km_batch",
        dry_run: false,
        dry_run_plan_fingerprint: fingerprint,
      },
      15000
    );
    setStaleBatchAction((current) => ({
      previewLoading: false,
      confirmLoading: false,
      previewResult: current.previewResult,
      result,
      error: result ? null : t("staleCandidates.batchActions.confirmFailed"),
    }));
    if (result?.status === "queued" || result?.status === "noop_already_queued") {
      onArchived();
    }
  }, [onArchived, staleBatchAction.previewResult, staleCandidates?.project_id, t]);

  const queueStaleOwnerReview = useCallback(async (candidate: KnowledgeStaleCandidate) => {
    setStaleReviewActions((current) => ({
      ...current,
      [candidate.entry_id]: {
        loading: true,
        result: current[candidate.entry_id]?.result ?? null,
        error: null,
      },
    }));
    const result = await postJson<KnowledgeStaleOwnerReviewResponse>(
      `${API_BASE}/api/v1/ai/governance/km-stale-candidates/${encodeURIComponent(candidate.entry_id)}/queue-review`,
      {
        owner: "operator_console",
        owner_note: candidate.priority_tier,
        dry_run: false,
      },
      15000
    );
    setStaleReviewActions((current) => ({
      ...current,
      [candidate.entry_id]: {
        loading: false,
        result,
        error: result ? null : t("staleCandidates.queueFailed"),
      },
    }));
    if (result?.status === "queued" || result?.status === "already_queued") {
      onArchived();
    }
  }, [onArchived, t]);

  const previewStaleReviewCompletion = useCallback(async (candidate: KnowledgeStaleCandidate) => {
    const queuedDispatchId = (
      candidate.owner_review_dispatch_id
      ?? staleReviewActions[candidate.entry_id]?.result?.dispatch_id
      ?? null
    );
    if (!queuedDispatchId) {
      setStaleReviewCompletionActions((current) => ({
        ...current,
        [candidate.entry_id]: {
          previewLoading: false,
          confirmLoading: false,
          previewResult: current[candidate.entry_id]?.previewResult ?? null,
          result: current[candidate.entry_id]?.result ?? null,
          error: t("staleCandidates.completeActions.missingDispatch"),
        },
      }));
      return;
    }
    setStaleReviewCompletionActions((current) => ({
      ...current,
      [candidate.entry_id]: {
        previewLoading: true,
        confirmLoading: false,
        previewResult: current[candidate.entry_id]?.previewResult ?? null,
        result: null,
        error: null,
      },
    }));
    const result = await postJson<KnowledgeStaleOwnerReviewCompleteResponse>(
      `${API_BASE}/api/v1/ai/governance/km-stale-candidates/${encodeURIComponent(candidate.entry_id)}/complete-review`,
      {
        dispatch_id: queuedDispatchId,
        owner: "operator_console",
        owner_approved: false,
        dry_run: true,
        review_outcome: kmStaleReviewOutcomeForCandidate(candidate),
        owner_note: `operator_console_review:${candidate.priority_tier}:${candidate.recommended_action}`,
      },
      15000
    );
    setStaleReviewCompletionActions((current) => ({
      ...current,
      [candidate.entry_id]: {
        previewLoading: false,
        confirmLoading: false,
        previewResult: result,
        result: null,
        error: result ? null : t("staleCandidates.completeActions.previewFailed"),
      },
    }));
  }, [staleReviewActions, t]);

  const confirmStaleReviewCompletion = useCallback(async (candidate: KnowledgeStaleCandidate) => {
    const action = staleReviewCompletionActions[candidate.entry_id];
    const queuedDispatchId = (
      candidate.owner_review_dispatch_id
      ?? staleReviewActions[candidate.entry_id]?.result?.dispatch_id
      ?? action?.previewResult?.dispatch_id
      ?? null
    );
    const fingerprint = action?.previewResult?.dry_run_plan_fingerprint;
    if (!queuedDispatchId || !fingerprint) {
      setStaleReviewCompletionActions((current) => ({
        ...current,
        [candidate.entry_id]: {
          previewLoading: false,
          confirmLoading: false,
          previewResult: current[candidate.entry_id]?.previewResult ?? null,
          result: current[candidate.entry_id]?.result ?? null,
          error: t("staleCandidates.completeActions.missingPreviewFingerprint"),
        },
      }));
      return;
    }
    setStaleReviewCompletionActions((current) => ({
      ...current,
      [candidate.entry_id]: {
        previewLoading: false,
        confirmLoading: true,
        previewResult: current[candidate.entry_id]?.previewResult ?? null,
        result: null,
        error: null,
      },
    }));
    const result = await postJson<KnowledgeStaleOwnerReviewCompleteResponse>(
      `${API_BASE}/api/v1/ai/governance/km-stale-candidates/${encodeURIComponent(candidate.entry_id)}/complete-review`,
      {
        dispatch_id: queuedDispatchId,
        owner: "operator_console",
        owner_approved: true,
        dry_run: false,
        review_outcome: kmStaleReviewOutcomeForCandidate(candidate),
        owner_note: `operator_console_review:${candidate.priority_tier}:${candidate.recommended_action}`,
        dry_run_plan_fingerprint: fingerprint,
      },
      15000
    );
    setStaleReviewCompletionActions((current) => ({
      ...current,
      [candidate.entry_id]: {
        previewLoading: false,
        confirmLoading: false,
        previewResult: current[candidate.entry_id]?.previewResult ?? null,
        result,
        error: result ? null : t("staleCandidates.completeActions.confirmFailed"),
      },
    }));
    if (result?.status === "completed" || result?.status === "already_completed") {
      onArchived();
    }
  }, [onArchived, staleReviewActions, staleReviewCompletionActions, t]);

  const previewCompletionBatch = useCallback(async () => {
    setCompletionBatchPreviewAction({
      loading: true,
      result: null,
      error: null,
    });
    const result = await postJson<KnowledgeStaleOwnerReviewCompletionBatchPreviewResponse>(
      `${API_BASE}/api/v1/ai/governance/km-stale-owner-review-completion-queue/batch-preview`,
      {
        project_id: completionQueue?.project_id ?? staleCandidates?.project_id ?? "awoooi",
        status_bucket: completionReadinessFilter,
        priority_tiers: completionPriorityFilter === "all"
          ? ["P0", "P1", "P2"]
          : [completionPriorityFilter],
        recommended_completion_outcome: "all",
        limit: 10,
        owner: "operator_console",
        owner_note: "completion_queue_batch_preview",
      },
      15000
    );
    setCompletionBatchPreviewAction({
      loading: false,
      result,
      error: result ? null : t("staleCandidates.completionQueue.batchPreview.previewFailed"),
    });
  }, [
    completionPriorityFilter,
    completionQueue?.project_id,
    completionReadinessFilter,
    staleCandidates?.project_id,
    t,
  ]);

  const staleBatchPreview = staleBatchAction.previewResult;
  const staleBatchResult = staleBatchAction.result;
  const staleBatchPreviewReady = Boolean(staleBatchPreview?.dry_run_plan_fingerprint);
  const staleBatchPreviewStatusKey = kmStaleBatchStatusKey(staleBatchPreview?.status);
  const staleBatchResultStatusKey = kmStaleBatchStatusKey(staleBatchResult?.status);
  const completionBatchPreview = completionBatchPreviewAction.result;

  return (
    <section className="border border-[#e0ddd4] bg-white">
      <div className="flex flex-wrap items-center justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex items-center gap-2">
          <ListChecks className="h-4 w-4 text-[#8a5a08]" aria-hidden="true" />
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="text-xs text-[#77736a]">{t("subtitle")}</p>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2 font-mono text-xs text-[#5f5b52]">
          <span className="border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5">
            {t("total", { count: queue?.total ?? 0 })}
          </span>
          <span className="border border-[#d8d3c7] bg-white px-2 py-0.5">
            {t("active", { count: activeCount })}
          </span>
          <span className="border border-[#d8d3c7] bg-white px-2 py-0.5">
            {t("review", { count: reviewCount })}
          </span>
          <span className="border border-[#d8d3c7] bg-white px-2 py-0.5">
            {t("drafts", { count: draftTotal })}
          </span>
          <span className="border border-[#d8d3c7] bg-white px-2 py-0.5">
            {t("duplicates", { count: duplicateDraftCount })}
          </span>
        </div>
      </div>

      {queue === null ? (
        <div className="px-4 py-4 text-sm text-[#8a5a08]">
          {t("unavailable")}
        </div>
      ) : queue.table_pending ? (
        <div className="px-4 py-4 text-sm text-[#8a5a08]">
          {t("tablePending")}
        </div>
      ) : items.length === 0 ? (
        <div className="px-4 py-4 text-sm text-[#5f5b52]">
          {t("empty")}
        </div>
      ) : (
        <div className="grid gap-px bg-[#eee9dd] md:grid-cols-2 xl:grid-cols-3">
          {items.slice(0, 6).map((item) => {
            const statusKey = governanceKmDispatchStatusKey(item.dispatch_status);
            const stageKey = governanceKmStageKey(item.workflow_stage);
            const steps = item.workflow_steps ?? [];
            const draftGroup = draftGroupForQueueItem(item, draftGroups);
            const dedupeGroup = draftDedupeGroupForQueueItem(item, dedupeGroups);
            const draftId = item.kb_draft_entry_id ?? draftGroup?.canonical.id ?? null;
            const workerStatus = item.worker_status ?? "--";
            const duplicateCount = dedupeGroup?.duplicate_count ?? draftGroup?.duplicateCount ?? 0;

            return (
              <article key={item.id} className="min-w-0 break-words bg-white px-4 py-3">
                <div className="flex min-w-0 flex-wrap items-start justify-between gap-3">
                  <div className="min-w-0">
                    <p className="break-all font-mono text-xs font-semibold text-[#141413]">
                      {item.governance_event_id}
                    </p>
                    <p className="mt-1 break-words text-xs text-[#77736a]">
                      {item.executor_type ?? "--"} / {item.decision_path ?? "--"}
                    </p>
                  </div>
                  <span className="max-w-full break-words border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5 text-xs font-semibold text-[#8a5a08]">
                    {t(`statuses.${statusKey}` as never)}
                  </span>
                </div>

                <div className="mt-3 grid min-w-0 gap-1 text-xs leading-5 text-[#5f5b52]">
                  <p className="break-words">
                    {t("stage", {
                      stage: t(`stages.${stageKey}` as never),
                    })}
                  </p>
                  <p className="break-words">{t("next", { action: item.next_action ?? item.proposed_action ?? "--" })}</p>
                  <p className="break-words">{t("lead", { agent: item.lead_agent ?? "--" })}</p>
                  <p className="break-words">{t("human", { owner: item.human_owner ?? "--" })}</p>
                  <p className="break-words">
                    {t("support", {
                      agents: item.support_agents?.length
                        ? item.support_agents.join(" / ")
                        : "--",
                    })}
                  </p>
                  <p className="break-words">{t("worker", { status: workerStatus })}</p>
                  <p className="break-all">{t("draft", { id: draftId ?? "--" })}</p>
                  {duplicateCount > 0 ? (
                    <p className="break-words text-[#9f2f25]">
                      {t("duplicateWarning", { count: duplicateCount })}
                    </p>
                  ) : null}
                </div>

                {steps.length > 0 ? (
                  <div className="mt-3 flex min-w-0 flex-wrap gap-1">
                    {steps.slice(0, 6).map((step) => (
                      <span
                        key={`${item.id}-${step}`}
                        className="max-w-full break-words border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5 font-mono text-[11px] leading-5 text-[#5f5b52]"
                      >
                        {t(`stages.${governanceKmStageKey(step)}` as never)}
                      </span>
                    ))}
                  </div>
                ) : null}
              </article>
            );
          })}
        </div>
      )}

      <div className="border-t border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
          <div className="flex items-center gap-2">
            <Database className="h-4 w-4 text-[#5f5b52]" aria-hidden="true" />
            <h4 className="text-xs font-semibold uppercase tracking-[0.08em] text-[#5f5b52]">
              {t("staleCandidates.title")}
            </h4>
          </div>
          <div className="flex flex-wrap items-center gap-2 font-mono text-[11px] text-[#5f5b52]">
            <span className="border border-[#d8d3c7] bg-white px-2 py-0.5">
              {t("staleCandidates.total", {
                count: staleCandidates?.total_stale ?? 0,
              })}
            </span>
            <span className="border border-[#d8d3c7] bg-white px-2 py-0.5">
              {t("staleCandidates.returned", {
                count: staleCandidates?.returned ?? 0,
              })}
            </span>
            <span className="border border-[#d8d3c7] bg-white px-2 py-0.5">
              {t("staleCandidates.threshold", {
                days: staleCandidates?.threshold_days ?? 7,
              })}
            </span>
          </div>
        </div>
        <div id="owner-review-rail" className="mb-3 scroll-mt-24 border border-[#e0ddd4] bg-white px-3 py-3 text-xs text-[#5f5b52]">
          <div className="flex flex-wrap items-start justify-between gap-3">
            <div className="min-w-0">
              <div className="flex items-center gap-2">
                <GitBranch className="h-4 w-4 text-[#5f5b52]" aria-hidden="true" />
                <p className="font-semibold text-[#141413]">
                  {t("staleCandidates.operationRail.title")}
                </p>
              </div>
              <p className="mt-1 text-[11px] leading-5 text-[#77736a]">
                {t("staleCandidates.operationRail.subtitle")}
              </p>
            </div>
            <div className="grid grid-cols-2 gap-1 font-mono text-[11px] text-[#5f5b52] sm:grid-cols-4">
              {[
                {
                  key: "ratio",
                  value: ownerReviewOperation.staleRatio,
                  detail: t("staleCandidates.operationRail.metric.threshold", {
                    threshold: ownerReviewOperation.threshold,
                  }),
                },
                {
                  key: "pending",
                  value: ownerReviewOperation.pending,
                  detail: t("staleCandidates.operationRail.metric.readyBlocked", {
                    ready: ownerReviewOperation.ready,
                    blocked: ownerReviewOperation.blocked,
                  }),
                },
                {
                  key: "completed",
                  value: ownerReviewOperation.completed,
                  detail: t("staleCandidates.operationRail.metric.failed", {
                    failed: ownerReviewOperation.failed,
                  }),
                },
                {
                  key: "remaining",
                  value: ownerReviewOperation.remaining,
                  detail: t("staleCandidates.operationRail.metric.total", {
                    stale: ownerReviewOperation.staleCount,
                    total: ownerReviewOperation.totalCount,
                  }),
                },
              ].map((metric) => (
                <div key={metric.key} className="border border-[#e0ddd4] bg-[#faf9f3] px-2 py-1.5">
                  <p className="text-[10px] uppercase tracking-[0.08em] text-[#77736a]">
                    {t(`staleCandidates.operationRail.metric.${metric.key}` as never)}
                  </p>
                  <p className="mt-1 text-sm font-semibold text-[#141413]">
                    {metric.value}
                  </p>
                  <p className="mt-0.5 break-words text-[10px] text-[#77736a]">
                    {metric.detail}
                  </p>
                </div>
              ))}
            </div>
          </div>
          <div className="mt-3 grid grid-cols-1 border border-[#e0ddd4] bg-[#e0ddd4] sm:grid-cols-2 xl:grid-cols-6">
            {ownerReviewOperation.flowNodes.map((node, index) => {
              const Icon = node.icon;
              return (
                <div key={node.key} className="relative min-w-0 bg-white px-3 py-2">
                  {index > 0 ? (
                    <ArrowRight className="absolute -left-2 top-5 hidden h-3.5 w-3.5 bg-white text-[#b7b0a1] xl:block" aria-hidden="true" />
                  ) : null}
                  <div className="flex items-start justify-between gap-2">
                    <div className={cn("flex h-7 w-7 shrink-0 items-center justify-center border", node.tone)}>
                      <Icon className="h-3.5 w-3.5" aria-hidden="true" />
                    </div>
                    <span className={cn("border px-2 py-0.5 text-[10px] font-semibold", node.tone)}>
                      {t(`staleCandidates.operationRail.state.${node.state}` as never)}
                    </span>
                  </div>
                  <p className="mt-2 truncate text-[10px] font-semibold uppercase tracking-[0.08em] text-[#77736a]">
                    {t(`staleCandidates.operationRail.flow.node.${node.key}` as never)}
                  </p>
                  <p className="mt-1 font-mono text-base font-semibold text-[#141413]">
                    {node.value}
                  </p>
                  <p className="mt-0.5 line-clamp-2 text-[11px] leading-5 text-[#5f5b52]">
                    {node.detail}
                  </p>
                </div>
              );
            })}
          </div>
          <div className="mt-3 grid gap-2 lg:grid-cols-[minmax(0,1fr)_minmax(240px,0.55fr)]">
            <div className="border border-[#d9b36f] bg-[#fff7e8] px-3 py-2">
              <p className="text-[10px] font-semibold uppercase tracking-[0.08em] text-[#8a5a08]">
                {t("staleCandidates.operationRail.nextAction")}
              </p>
              <p className="mt-1 text-sm font-semibold text-[#141413]">
                {t(`staleCandidates.operationRail.next.${ownerReviewOperation.nextActionKey}` as never)}
              </p>
              <p className="mt-1 text-[11px] leading-5 text-[#5f5b52]">
                {t(`staleCandidates.operationRail.nextDetail.${ownerReviewOperation.nextActionKey}` as never)}
              </p>
            </div>
            <div className="border border-[#d8d3c7] bg-[#faf9f3] px-3 py-2">
              <p className="text-[10px] font-semibold uppercase tracking-[0.08em] text-[#77736a]">
                {t("staleCandidates.operationRail.guardrailTitle")}
              </p>
              <div className="mt-1 grid gap-1 font-mono text-[11px] leading-5 text-[#5f5b52]">
                <p>{t("staleCandidates.operationRail.guardrail.writesOnRead", { value: String(ownerReviewOperation.writesOnRead) })}</p>
                <p>{t("staleCandidates.operationRail.guardrail.manualReview", { value: String(ownerReviewOperation.manualReviewRequired) })}</p>
                <p>{t("staleCandidates.operationRail.guardrail.batchWrites", { value: String(ownerReviewOperation.batchWritesAllowed) })}</p>
              </div>
            </div>
          </div>
        </div>
        <div className="mb-3 border border-[#e0ddd4] bg-white px-3 py-2 text-xs text-[#5f5b52]">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <div className="min-w-0">
              <p className="font-semibold text-[#141413]">
                {t("staleCandidates.batchActions.title")}
              </p>
              <p className="mt-1 text-[11px] leading-5 text-[#77736a]">
                {t("staleCandidates.batchActions.subtitle")}
              </p>
            </div>
            <div className="flex flex-wrap items-center gap-2">
              <button
                type="button"
                onClick={previewStaleBatchQueue}
                disabled={staleBatchAction.previewLoading || staleBatchAction.confirmLoading}
                className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#9bc7a4] hover:bg-[#f0faf2] hover:text-[#17602a] disabled:cursor-not-allowed disabled:opacity-60"
              >
                <SearchCheck className="h-3.5 w-3.5" aria-hidden="true" />
                {staleBatchAction.previewLoading
                  ? t("staleCandidates.batchActions.previewing")
                  : t("staleCandidates.batchActions.preview")}
              </button>
              <button
                type="button"
                onClick={confirmStaleBatchQueue}
                disabled={
                  !staleBatchPreviewReady ||
                  staleBatchAction.previewLoading ||
                  staleBatchAction.confirmLoading
                }
                className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#d9b36f] hover:bg-[#fff7e8] hover:text-[#8a5a08] disabled:cursor-not-allowed disabled:opacity-60"
              >
                <ClipboardList className="h-3.5 w-3.5" aria-hidden="true" />
                {staleBatchAction.confirmLoading
                  ? t("staleCandidates.batchActions.confirming")
                  : t("staleCandidates.batchActions.confirm")}
              </button>
            </div>
          </div>
          {staleBatchAction.error ? (
            <p className="mt-2 border border-[#e2a29b] bg-[#fff0ef] px-2 py-1 text-[11px] leading-5 text-[#9f2f25]">
              {staleBatchAction.error}
            </p>
          ) : null}
          {staleBatchPreview ? (
            <div className="mt-2 border border-[#d9b36f] bg-[#fff7e8] px-2 py-1.5 text-[11px] leading-5 text-[#8a5a08]">
              <p className="font-semibold">
                {t(
                  `staleCandidates.batchActions.statuses.${staleBatchPreviewStatusKey}` as never
                )}
              </p>
              <p className="mt-1 text-[#5f5b52]">
                {t("staleCandidates.batchActions.summary", {
                  candidates: staleBatchPreview.candidate_count,
                  queued: staleBatchPreview.queued_count,
                  already: staleBatchPreview.already_queued_count,
                  skipped: staleBatchPreview.skipped_count,
                  writesKm: String(staleBatchPreview.writes_km),
                  writesAudit: String(staleBatchPreview.writes_governance_audit),
                })}
              </p>
              <p className="mt-1 break-all font-mono text-[11px] text-[#5f5b52]">
                {t("staleCandidates.batchActions.planFingerprint", {
                  fingerprint: staleBatchPreview.dry_run_plan_fingerprint ?? "--",
                })}
              </p>
              {staleBatchPreview.stale_ratio_snapshot ? (
                <p className="mt-1 text-[#5f5b52]">
                  {t("staleCandidates.completeActions.snapshot", {
                    stale: staleBatchPreview.stale_ratio_snapshot.stale_count,
                    total: staleBatchPreview.stale_ratio_snapshot.total_count,
                    ratio: formatStaleRatio(staleBatchPreview.stale_ratio_snapshot.stale_ratio),
                    threshold: formatStaleRatio(staleBatchPreview.stale_ratio_snapshot.threshold),
                  })}
                </p>
              ) : null}
              <div className="mt-2 flex flex-wrap gap-1">
                {staleBatchPreview.items.slice(0, 5).map((item) => (
                  <span
                    key={`${item.entry_id}-${item.status}`}
                    className="border border-[#d8d3c7] bg-white px-2 py-0.5 font-mono text-[11px] leading-5 text-[#5f5b52]"
                  >
                    {item.priority_tier}:{t(
                      `staleCandidates.batchActions.itemStatuses.${kmStaleBatchItemStatusKey(item.status)}` as never
                    )}
                  </span>
                ))}
              </div>
            </div>
          ) : null}
          {staleBatchResult ? (
            <div className="mt-2 border border-[#9bc7a4] bg-[#f0faf2] px-2 py-1.5 text-[11px] leading-5 text-[#17602a]">
              <p className="font-semibold">
                {t(
                  `staleCandidates.batchActions.statuses.${staleBatchResultStatusKey}` as never
                )}
              </p>
              <p className="mt-1 text-[#5f5b52]">
                {t("staleCandidates.batchActions.result", {
                  batch: staleBatchResult.batch_dispatch_id ?? "--",
                  event: staleBatchResult.batch_governance_event_id ?? "--",
                  queued: staleBatchResult.queued_count,
                  already: staleBatchResult.already_queued_count,
                  skipped: staleBatchResult.skipped_count,
                })}
              </p>
            </div>
          ) : null}
        </div>
        <div className="mb-3 border border-[#e0ddd4] bg-white px-3 py-2 text-xs text-[#5f5b52]">
          <div className="mb-2 flex flex-wrap items-center justify-between gap-2">
            <div className="flex items-center gap-2">
              <Gauge className="h-4 w-4 text-[#5f5b52]" aria-hidden="true" />
              <div>
                <p className="font-semibold text-[#141413]">
                  {t("staleCandidates.burnDown.title")}
                </p>
                <p className="mt-1 text-[11px] leading-5 text-[#77736a]">
                  {t("staleCandidates.burnDown.subtitle")}
                </p>
              </div>
            </div>
            <div className="flex flex-wrap gap-2 font-mono text-[11px] text-[#5f5b52]">
              <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
                {t("staleCandidates.burnDown.statuses", {
                  status: burnDown
                    ? t(`staleCandidates.burnDown.status.${burnDown.burn_down_status}` as never)
                    : "--",
                })}
              </span>
              <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
                {t("staleCandidates.burnDown.remaining", {
                  count: burnDown?.entries_to_threshold ?? 0,
                })}
              </span>
            </div>
          </div>
          {burnDown === null ? (
            <p className="text-[11px] leading-5 text-[#8a5a08]">
              {t("staleCandidates.burnDown.unavailable")}
            </p>
          ) : (
            <>
              <div className="grid gap-px border border-[#e0ddd4] bg-[#e0ddd4] md:grid-cols-4">
                <div className="bg-[#faf9f3] px-3 py-2">
                  <p className="text-[11px] text-[#77736a]">
                    {t("staleCandidates.burnDown.currentRatio")}
                  </p>
                  <p className="mt-1 font-mono text-sm font-semibold text-[#141413]">
                    {burnDownSnapshot
                      ? formatStaleRatio(burnDownSnapshot.stale_ratio)
                      : "--"}
                  </p>
                </div>
                <div className="bg-[#faf9f3] px-3 py-2">
                  <p className="text-[11px] text-[#77736a]">
                    {t("staleCandidates.burnDown.currentCount")}
                  </p>
                  <p className="mt-1 font-mono text-sm font-semibold text-[#141413]">
                    {burnDownSnapshot
                      ? `${burnDownSnapshot.stale_count}/${burnDownSnapshot.total_count}`
                      : "--"}
                  </p>
                </div>
                <div className="bg-[#faf9f3] px-3 py-2">
                  <p className="text-[11px] text-[#77736a]">
                    {t("staleCandidates.burnDown.ownerReviews")}
                  </p>
                  <p className="mt-1 font-mono text-sm font-semibold text-[#141413]">
                    {t("staleCandidates.burnDown.ownerReviewCounts", {
                      pending: burnDown.pending_owner_reviews,
                      completed: burnDown.completed_owner_reviews,
                    })}
                  </p>
                </div>
                <div className="bg-[#faf9f3] px-3 py-2">
                  <p className="text-[11px] text-[#77736a]">
                    {t("staleCandidates.burnDown.latestDelta")}
                  </p>
                  <p className="mt-1 font-mono text-sm font-semibold text-[#141413]">
                    {t("staleCandidates.burnDown.delta", {
                      stale: formatSignedNumber(burnDown.latest_stale_count_delta),
                      ratio: formatSignedRatio(burnDown.latest_stale_ratio_delta),
                    })}
                  </p>
                </div>
              </div>
              <div className="mt-2 flex flex-wrap gap-2 font-mono text-[11px] text-[#5f5b52]">
                <span className="max-w-full break-words border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
                  {t("staleCandidates.burnDown.auditTotal", {
                    count: burnDown.completion_audit_total,
                  })}
                </span>
                <span className="max-w-full break-words border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
                  {t("staleCandidates.burnDown.recheckTotal", {
                    count: burnDown.stale_ratio_recheck_total,
                  })}
                </span>
                <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
                  {t("staleCandidates.burnDown.guardrail", {
                    writes: String(burnDown.writes_on_read),
                    review: String(burnDown.manual_review_required),
                  })}
                </span>
              </div>
              {burnDownItems.length === 0 ? (
                <p className="mt-2 text-[11px] leading-5 text-[#5f5b52]">
                  {t("staleCandidates.burnDown.empty")}
                </p>
              ) : (
                <div className="mt-2 grid gap-2 md:grid-cols-2">
                  {burnDownItems.slice(0, 4).map((item) => (
                    <article
                      key={item.completion_dispatch_id}
                      className="min-w-0 border border-[#e0ddd4] bg-[#faf9f3] px-3 py-2 text-[11px] leading-5 text-[#5f5b52]"
                    >
                      <div className="flex items-start justify-between gap-3">
                        <div className="min-w-0">
                          <p className="truncate font-mono font-semibold text-[#141413]">
                            {item.entry_id ?? "--"}
                          </p>
                          <p className="mt-1 truncate font-mono text-[#77736a]">
                            {item.completion_dispatch_id}
                          </p>
                        </div>
                        <span className="shrink-0 border border-[#9bc7a4] bg-[#f0faf2] px-2 py-0.5 font-mono font-semibold text-[#17602a]">
                          {formatSignedNumber(item.stale_count_delta)}
                        </span>
                      </div>
                      <p className="mt-2">
                        {t("staleCandidates.burnDown.itemState", {
                          stage: t(`stages.${governanceKmStageKey(item.workflow_stage)}` as never),
                          outcome: item.review_outcome
                            ? t(`staleCandidates.completeActions.outcomes.${item.review_outcome}` as never)
                            : "--",
                        })}
                      </p>
                      <p className="truncate">
                        {t("staleCandidates.burnDown.itemRefs", {
                          source: item.source_dispatch_id ?? "--",
                          recheck: item.recheck_dispatch_id ?? "--",
                        })}
                      </p>
                      {item.stale_ratio_snapshot ? (
                        <p>
                          {t("staleCandidates.completeActions.snapshot", {
                            stale: item.stale_ratio_snapshot.stale_count,
                            total: item.stale_ratio_snapshot.total_count,
                            ratio: formatStaleRatio(item.stale_ratio_snapshot.stale_ratio),
                            threshold: formatStaleRatio(item.stale_ratio_snapshot.threshold),
                          })}
                        </p>
                      ) : null}
                    </article>
                  ))}
                </div>
              )}
            </>
          )}
        </div>
        <div className="mb-3 border border-[#e0ddd4] bg-white px-3 py-2 text-xs text-[#5f5b52]">
          <div className="mb-2 flex flex-wrap items-center justify-between gap-2">
            <div className="flex items-center gap-2">
              <CheckCircle2 className="h-4 w-4 text-[#5f5b52]" aria-hidden="true" />
              <div>
                <p className="font-semibold text-[#141413]">
                  {t("staleCandidates.completionQueue.title")}
                </p>
                <p className="mt-1 text-[11px] leading-5 text-[#77736a]">
                  {t("staleCandidates.completionQueue.subtitle")}
                </p>
              </div>
            </div>
            <div className="flex flex-wrap gap-2 font-mono text-[11px] text-[#5f5b52]">
              <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
                {t("staleCandidates.completionQueue.ready", {
                  count: completionQueue?.ready_count ?? 0,
                })}
              </span>
              <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
                {t("staleCandidates.completionQueue.blocked", {
                  count: completionQueue?.blocked_count ?? 0,
                })}
              </span>
              <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
                {t("staleCandidates.completionQueue.completed", {
                  count: completionQueue?.completed_count ?? 0,
                })}
              </span>
              <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
                {t("staleCandidates.completionQueue.failed", {
                  count: completionQueue?.failed_count ?? 0,
                })}
              </span>
            </div>
          </div>
          <div className="mb-2 flex flex-wrap items-center justify-between gap-2 border border-[#e0ddd4] bg-[#faf9f3] px-2 py-2">
            <div className="flex flex-wrap gap-1">
              {(["ready", "blocked", "completed", "failed", "pending", "all"] as const).map((filter) => (
                <button
                  key={filter}
                  type="button"
                  onClick={() => setCompletionReadinessFilter(filter)}
                  className={cn(
                    "border px-2 py-1 text-[11px] font-semibold leading-4",
                    completionReadinessFilter === filter
                      ? "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]"
                      : "border-[#d8d3c7] bg-white text-[#5f5b52] hover:border-[#d9b36f]"
                  )}
                >
                  {t(`staleCandidates.completionQueue.filters.${filter}` as never)}
                </button>
              ))}
            </div>
            <div className="flex flex-wrap gap-1">
              {(["all", "P0", "P1", "P2"] as const).map((filter) => (
                <button
                  key={filter}
                  type="button"
                  onClick={() => setCompletionPriorityFilter(filter)}
                  className={cn(
                    "border px-2 py-1 font-mono text-[11px] font-semibold leading-4",
                    completionPriorityFilter === filter
                      ? "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]"
                      : "border-[#d8d3c7] bg-white text-[#5f5b52] hover:border-[#9bc7a4]"
                  )}
                >
                  {filter === "all"
                    ? t("staleCandidates.completionQueue.filters.priorityAll")
                    : filter}
                </button>
              ))}
            </div>
            <button
              type="button"
              onClick={previewCompletionBatch}
              disabled={completionBatchPreviewAction.loading}
              className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#1f6feb] hover:bg-[#edf4ff] hover:text-[#0f4fa8] disabled:cursor-not-allowed disabled:opacity-60"
            >
              <SearchCheck className="h-3.5 w-3.5" aria-hidden="true" />
              {completionBatchPreviewAction.loading
                ? t("staleCandidates.completionQueue.batchPreview.previewing")
                : t("staleCandidates.completionQueue.batchPreview.preview")}
            </button>
          </div>
          {completionBatchPreviewAction.error ? (
            <p className="mb-2 border border-[#e2a29b] bg-[#fff0ef] px-2 py-1 text-[11px] leading-5 text-[#9f2f25]">
              {completionBatchPreviewAction.error}
            </p>
          ) : null}
          {completionBatchPreview ? (
            <div className="mb-2 border border-[#1f6feb] bg-[#edf4ff] px-2 py-1.5 text-[11px] leading-5 text-[#0f4fa8]">
              <p className="font-semibold">
                {t("staleCandidates.completionQueue.batchPreview.summary", {
                  candidates: completionBatchPreview.candidate_count,
                  previewable: completionBatchPreview.previewable_count,
                  blocked: completionBatchPreview.blocked_count,
                  writesKm: String(completionBatchPreview.writes_km),
                  writesAudit: String(completionBatchPreview.writes_governance_audit),
                  batchWrites: String(completionBatchPreview.batch_writes_allowed),
                })}
              </p>
              <p className="mt-1 break-all font-mono text-[11px] text-[#5f5b52]">
                {t("staleCandidates.completionQueue.batchPreview.planFingerprint", {
                  fingerprint: completionBatchPreview.dry_run_plan_fingerprint,
                })}
              </p>
              <p className="mt-1 text-[#5f5b52]">
                {t("staleCandidates.completionQueue.batchPreview.next", {
                  action: completionBatchPreview.next_action,
                })}
              </p>
            </div>
          ) : null}
          {completionQueue === null ? (
            <p className="text-[11px] leading-5 text-[#8a5a08]">
              {t("staleCandidates.completionQueue.unavailable")}
            </p>
          ) : completionQueueItems.length === 0 ? (
            <p className="text-[11px] leading-5 text-[#5f5b52]">
              {t("staleCandidates.completionQueue.empty")}
            </p>
          ) : (
            <>
              <div className="mb-2 flex flex-wrap gap-2 font-mono text-[11px] text-[#5f5b52]">
                <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
                  {t("staleCandidates.completionQueue.pending", {
                    count: completionQueue.pending_count,
                  })}
                </span>
                <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
                  {t("staleCandidates.completionQueue.guardrail", {
                    writes: String(completionQueue.writes_on_read),
                    review: String(completionQueue.manual_review_required),
                    batch: String(completionQueue.batch_writes_allowed),
                  })}
                </span>
              </div>
              <div className="grid gap-2 md:grid-cols-2">
                {completionQueueItems.slice(0, 6).map((item) => {
                  const completionCandidate = staleCandidateFromOwnerReviewItem(item);
                  const completionAction = staleReviewCompletionActions[item.entry_id];
                  const readinessKey = kmStaleCompletionReadinessKey(item.readiness);
                  return (
                    <article
                      key={item.dispatch_id}
                      className="min-w-0 break-words border border-[#e0ddd4] bg-[#faf9f3] px-3 py-2 text-[11px] leading-5 text-[#5f5b52]"
                    >
                      <div className="flex items-start justify-between gap-3">
                        <div className="min-w-0">
                          <p className="break-words font-semibold text-[#141413] sm:line-clamp-2">
                            {item.title}
                          </p>
                          <p className="mt-1 break-all font-mono text-[#77736a]">
                            {item.entry_id}
                          </p>
                        </div>
                        <span className="shrink-0 border border-[#d8d3c7] bg-white px-2 py-0.5 font-mono font-semibold text-[#2e2b26]">
                          {item.priority_tier}
                        </span>
                      </div>
                      <p className="mt-2 break-words">
                        {t("staleCandidates.completionQueue.state", {
                          readiness: t(`staleCandidates.completionQueue.readiness.${readinessKey}` as never),
                          stage: t(`stages.${governanceKmStageKey(item.workflow_stage)}` as never),
                        })}
                      </p>
                      <p className="break-words">
                        {t("staleCandidates.completionQueue.next", {
                          action: item.next_action,
                          outcome: t(`staleCandidates.completeActions.outcomes.${item.recommended_completion_outcome}` as never),
                        })}
                      </p>
                      <p>
                        {t("staleCandidates.ownerReviewInbox.meta", {
                          days: item.stale_days,
                          score: item.priority_score,
                          views: item.view_count,
                        })}
                      </p>
                      <p className="break-words">
                        {t("staleCandidates.ownerReviewInbox.batch", {
                          batch: item.batch_dispatch_id ?? "--",
                        })}
                      </p>
                      <p className="break-words">
                        {t("staleCandidates.completionQueue.required", {
                          fields: item.required_owner_fields.length > 0
                            ? item.required_owner_fields.join(", ")
                            : "--",
                        })}
                      </p>
                      {item.blockers.length > 0 ? (
                        <p className="break-words text-[#9f2f25]">
                          {t("staleCandidates.completionQueue.blockers", {
                            blockers: item.blockers.join(", "),
                          })}
                        </p>
                      ) : null}
                      <KnowledgeOwnerReviewSingleItemRail
                        candidate={completionCandidate}
                        action={completionAction}
                        queuedDispatchId={item.dispatch_id}
                        canPreview={item.can_preview}
                        canConfirmAfterPreview={item.can_confirm_after_preview}
                        writesKmOnConfirm={item.writes_km_on_confirm}
                        requiredOwnerFields={item.required_owner_fields}
                        blockers={item.blockers}
                        onPreview={() => previewStaleReviewCompletion(completionCandidate)}
                        onConfirm={() => confirmStaleReviewCompletion(completionCandidate)}
                      />
                    </article>
                  );
                })}
              </div>
            </>
          )}
        </div>
        <div className="mb-3 border border-[#e0ddd4] bg-white px-3 py-2 text-xs text-[#5f5b52]">
          <div className="mb-2 flex flex-wrap items-center justify-between gap-2">
            <div className="flex items-center gap-2">
              <ClipboardList className="h-4 w-4 text-[#5f5b52]" aria-hidden="true" />
              <div>
                <p className="font-semibold text-[#141413]">
                  {t("staleCandidates.ownerReviewInbox.title")}
                </p>
                <p className="mt-1 text-[11px] leading-5 text-[#77736a]">
                  {t("staleCandidates.ownerReviewInbox.subtitle")}
                </p>
              </div>
            </div>
            <div className="flex flex-wrap gap-2 font-mono text-[11px] text-[#5f5b52]">
              <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
                {t("staleCandidates.ownerReviewInbox.total", {
                  count: ownerReviewInbox?.total ?? 0,
                })}
              </span>
              <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5">
                {t("staleCandidates.ownerReviewInbox.returned", {
                  count: ownerReviewInbox?.returned ?? 0,
                })}
              </span>
            </div>
          </div>
          {ownerReviewInbox === null ? (
            <p className="text-[11px] leading-5 text-[#8a5a08]">
              {t("staleCandidates.ownerReviewInbox.unavailable")}
            </p>
          ) : ownerReviewItems.length === 0 ? (
            <p className="text-[11px] leading-5 text-[#5f5b52]">
              {t("staleCandidates.ownerReviewInbox.empty")}
            </p>
          ) : (
            <div className="grid gap-2 md:grid-cols-2">
              {ownerReviewItems.slice(0, 6).map((item) => {
                const inboxCandidate = staleCandidateFromOwnerReviewItem(item);
                const completionAction = staleReviewCompletionActions[item.entry_id];
                return (
                  <article
                    key={item.dispatch_id}
                    className="min-w-0 break-words border border-[#e0ddd4] bg-[#faf9f3] px-3 py-2 text-[11px] leading-5 text-[#5f5b52]"
                  >
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <p className="break-words font-semibold text-[#141413] sm:line-clamp-2">
                          {item.title}
                        </p>
                        <p className="mt-1 break-all font-mono text-[#77736a]">
                          {item.dispatch_id}
                        </p>
                      </div>
                      <span className="shrink-0 border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5 font-mono font-semibold text-[#8a5a08]">
                        {item.priority_tier}
                      </span>
                    </div>
                    <div className="mt-2 grid gap-1">
                      <p className="break-words">
                        {t("staleCandidates.ownerReviewInbox.meta", {
                          days: item.stale_days,
                          score: item.priority_score,
                          views: item.view_count,
                        })}
                      </p>
                      <p className="break-words">
                        {t("staleCandidates.ownerReviewInbox.state", {
                          status: t(`statuses.${governanceKmDispatchStatusKey(item.dispatch_status)}` as never),
                          stage: t(`stages.${governanceKmStageKey(item.workflow_stage)}` as never),
                        })}
                      </p>
                      <p className="break-words">
                        {t("staleCandidates.ownerReviewInbox.batch", {
                          batch: item.batch_dispatch_id ?? "--",
                        })}
                      </p>
                      <p>
                        {t("staleCandidates.refs", {
                          incident: item.related_incident_id ?? "--",
                          playbook: item.related_playbook_id ?? "--",
                          approval: item.related_approval_id ?? "--",
                        })}
                      </p>
                    </div>
                    <KnowledgeOwnerReviewSingleItemRail
                      candidate={inboxCandidate}
                      action={completionAction}
                      queuedDispatchId={item.dispatch_id}
                      canPreview={true}
                      canConfirmAfterPreview={true}
                      writesKmOnConfirm={true}
                      onPreview={() => previewStaleReviewCompletion(inboxCandidate)}
                      onConfirm={() => confirmStaleReviewCompletion(inboxCandidate)}
                    />
                  </article>
                );
              })}
            </div>
          )}
        </div>
        {staleCandidates === null ? (
          <p className="text-xs text-[#8a5a08]">
            {t("staleCandidates.unavailable")}
          </p>
        ) : staleCandidateItems.length === 0 ? (
          <p className="text-xs text-[#5f5b52]">
            {t("staleCandidates.empty")}
          </p>
        ) : (
          <div className="grid gap-2 md:grid-cols-2">
            {staleCandidateItems.slice(0, 6).map((candidate) => {
              const reviewAction = staleReviewActions[candidate.entry_id];
              const reviewResult = reviewAction?.result ?? null;
              const reviewStatusKey = kmStaleReviewStatusKey(reviewResult?.status);
              const queuedDispatchId = candidate.owner_review_dispatch_id ?? reviewResult?.dispatch_id ?? null;
              const persistedReviewStatusKey = governanceKmDispatchStatusKey(candidate.owner_review_status);
              const persistedReviewStageKey = governanceKmStageKey(candidate.owner_review_stage);
              const completionAction = staleReviewCompletionActions[candidate.entry_id];
              return (
                <article
                  key={candidate.entry_id}
                  className="min-w-0 break-words border border-[#e0ddd4] bg-white px-3 py-2 text-xs text-[#5f5b52]"
                >
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="break-words font-semibold text-[#141413] sm:line-clamp-2">
                        {candidate.title}
                      </p>
                      <p className="mt-1 break-all font-mono text-[11px] text-[#77736a]">
                        {candidate.entry_id}
                      </p>
                    </div>
                    <span className="shrink-0 border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5 font-mono font-semibold text-[#8a5a08]">
                      {candidate.priority_tier}
                    </span>
                  </div>
                  <div className="mt-2 grid gap-1 leading-5">
                    <p className="break-words">
                      {t("staleCandidates.meta", {
                        days: candidate.stale_days,
                        score: candidate.priority_score,
                        views: candidate.view_count,
                      })}
                    </p>
                    <p>
                      {t("staleCandidates.action", {
                        action: t(
                          `staleCandidates.actions.${kmStaleActionKey(candidate.recommended_action)}` as never
                        ),
                      })}
                    </p>
                    <p>
                      {t("staleCandidates.sources", {
                        sources: candidate.correlation_sources.length
                          ? candidate.correlation_sources
                              .map((source) => t(
                                `staleCandidates.correlationSources.${kmCorrelationSourceKey(source)}` as never
                              ))
                              .join(" / ")
                          : t("staleCandidates.noSources"),
                      })}
                    </p>
                    <p>
                      {t("staleCandidates.refs", {
                        incident: candidate.related_incident_id ?? "--",
                        playbook: candidate.related_playbook_id ?? "--",
                        approval: candidate.related_approval_id ?? "--",
                      })}
                    </p>
                    {queuedDispatchId ? (
                      <p className="break-words">
                        {t("staleCandidates.ownerReviewState", {
                          status: t(`statuses.${persistedReviewStatusKey}` as never),
                          stage: t(`stages.${persistedReviewStageKey}` as never),
                          dispatch: queuedDispatchId,
                        })}
                      </p>
                    ) : null}
                  </div>
                  <div className="mt-2 flex flex-wrap gap-1">
                    {candidate.reasons.slice(0, 5).map((reason) => (
                      <span
                        key={`${candidate.entry_id}-${reason}`}
                        className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5 leading-5"
                      >
                        {t(`staleCandidates.reasons.${kmStaleReasonKey(reason)}` as never)}
                      </span>
                    ))}
                  </div>
                  <div className="mt-2 flex flex-wrap items-center gap-2">
                    <button
                      type="button"
                      onClick={() => queueStaleOwnerReview(candidate)}
                      disabled={Boolean(reviewAction?.loading)}
                      className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#9bc7a4] hover:bg-[#f0faf2] hover:text-[#17602a] disabled:cursor-not-allowed disabled:opacity-60"
                    >
                      <ClipboardList className="h-3.5 w-3.5" aria-hidden="true" />
                      {reviewAction?.loading
                        ? t("staleCandidates.queueingReview")
                        : t("staleCandidates.queueReview")}
                    </button>
                    <Link
                      href={`/knowledge-base?q=${encodeURIComponent(candidate.title)}`}
                      className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#1f6feb] hover:bg-[#edf4ff] hover:text-[#0f4fa8]"
                    >
                      <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
                      {t("staleCandidates.openKnowledge")}
                    </Link>
                  </div>
                  {reviewAction?.error ? (
                    <p className="mt-2 border border-[#e2a29b] bg-[#fff0ef] px-2 py-1 text-[11px] leading-5 text-[#9f2f25]">
                      {reviewAction.error}
                    </p>
                  ) : null}
                  {reviewResult ? (
                    <p className="mt-2 border border-[#9bc7a4] bg-[#f0faf2] px-2 py-1 text-[11px] leading-5 text-[#17602a]">
                      {t("staleCandidates.queueResult", {
                        status: t(`staleCandidates.queueStatuses.${reviewStatusKey}` as never),
                        dispatch: reviewResult.dispatch_id ?? "--",
                        event: reviewResult.governance_event_id ?? "--",
                      })}
                    </p>
                  ) : null}
                  <KnowledgeOwnerReviewSingleItemRail
                    candidate={candidate}
                    action={completionAction}
                    queuedDispatchId={queuedDispatchId}
                    canPreview={Boolean(queuedDispatchId)}
                    canConfirmAfterPreview={true}
                    writesKmOnConfirm={true}
                    onPreview={() => previewStaleReviewCompletion(candidate)}
                    onConfirm={() => confirmStaleReviewCompletion(candidate)}
                  />
                </article>
              );
            })}
          </div>
        )}
        <p className="mt-3 text-[11px] leading-5 text-[#77736a]">
          {t("staleCandidates.guardrail", {
            writes: String(staleCandidates?.writes_on_read ?? false),
            review: String(staleCandidates?.manual_review_required ?? true),
          })}
        </p>
      </div>

      {dedupe === null && reviewDrafts === null ? (
        <div className="border-t border-[#e0ddd4] px-4 py-3 text-xs text-[#8a5a08]">
          {t("draftsUnavailable")}
        </div>
      ) : dedupeGroups.length > 0 ? (
        <div className="border-t border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
          <div className="mb-3 flex items-center gap-2">
            <FileText className="h-4 w-4 text-[#5f5b52]" aria-hidden="true" />
            <h4 className="text-xs font-semibold uppercase tracking-[0.08em] text-[#5f5b52]">
              {t("draftSectionTitle")}
            </h4>
          </div>
          <div className="grid gap-2 md:grid-cols-2">
            {dedupeGroups.slice(0, 4).map((group) => {
              const archiveAction = archiveActions[group.governance_event_id];
              const previewResult = archiveAction?.previewResult ?? null;
              const finalResult = archiveAction?.result ?? null;
              const previewReady = (
                previewResult?.status === "dry_run" &&
                Boolean(previewResult.dry_run_plan_fingerprint)
              );
              const previewKey = groupArchiveStatusKey(previewResult?.status);
              const finalResultKey = groupArchiveStatusKey(finalResult?.status);
              const archiveTrace = kmArchiveTraceForDedupeGroup(group, items);
              return (
                <div
                  key={group.governance_event_id}
                  className="border border-[#e0ddd4] bg-white px-3 py-2 text-xs text-[#5f5b52]"
                >
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="truncate font-mono font-semibold text-[#141413]">
                        {group.governance_event_id}
                      </p>
                      <p className="mt-1 truncate text-[#77736a]">{group.canonical_title}</p>
                    </div>
                    <span className="shrink-0 border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5 font-mono">
                      {group.canonical_entry_id}
                    </span>
                  </div>
                  <div className="mt-2 grid gap-1 leading-5">
                    <p>
                      {t("draftGroup", {
                        count: group.total_entries,
                        duplicates: group.duplicate_count,
                      })}
                    </p>
                    <p>
                      {t("archiveProposal", {
                        count: group.duplicate_count,
                      })}
                    </p>
                    <p>
                      {t("ownerAction", {
                        action: t(
                          `ownerActions.${kmDedupeActionKey(group.owner_action)}` as never
                        ),
                      })}
                    </p>
                    <p>
                      {t("readOnlyPlan", {
                        writes: String(group.writes_on_read),
                        blocked: String(!group.can_archive_without_owner_approval),
                      })}
                    </p>
                  </div>
                  <div className="mt-2 border border-[#e0ddd4] bg-[#faf9f3] px-2 py-1.5">
                    <p className="font-semibold text-[#2e2b26]">
                      {t("archiveHistory.title")}
                    </p>
                    {archiveTrace.length === 0 ? (
                      <p className="mt-1 text-[#77736a]">
                        {t("archiveHistory.empty")}
                      </p>
                    ) : (
                      <div className="mt-1 grid gap-1">
                        {archiveTrace.map((trace) => (
                          <div
                            key={trace.id}
                            className="border border-[#d8d3c7] bg-white px-2 py-1 text-[#5f5b52]"
                          >
                            <p>
                              {t("archiveHistory.item", {
                                executor: t(
                                  `archiveHistory.executors.${kmArchiveExecutorKey(trace.executor_type)}` as never
                                ),
                                status: t(
                                  `statuses.${governanceKmDispatchStatusKey(trace.dispatch_status)}` as never
                                ),
                                stage: t(
                                  `stages.${governanceKmStageKey(trace.workflow_stage)}` as never
                                ),
                                archived: trace.archived_count ?? "--",
                              })}
                            </p>
                            {trace.dry_run_plan_fingerprint ? (
                              <p className="mt-1 break-all font-mono text-[11px]">
                                {t("archiveHistory.fingerprint", {
                                  fingerprint: trace.dry_run_plan_fingerprint,
                                })}
                              </p>
                            ) : null}
                            {trace.stale_ratio_snapshot ? (
                              <p className="mt-1">
                                {t("archiveHistory.snapshot", {
                                  stale: trace.stale_ratio_snapshot.stale_count ?? "--",
                                  total: trace.stale_ratio_snapshot.total_count ?? "--",
                                  ratio: typeof trace.stale_ratio_snapshot.stale_ratio === "number"
                                    ? formatStaleRatio(trace.stale_ratio_snapshot.stale_ratio)
                                    : "--",
                                  threshold: typeof trace.stale_ratio_snapshot.threshold === "number"
                                    ? formatStaleRatio(trace.stale_ratio_snapshot.threshold)
                                    : "--",
                                })}
                              </p>
                            ) : null}
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                  <div className="mt-3 flex flex-wrap items-center gap-2">
                    <Link
                      href={governanceEventHistoryHref(group.governance_event_id)}
                      className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#1f6feb] hover:bg-[#edf4ff] hover:text-[#0f4fa8]"
                    >
                      <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
                      {t("openEventHistory")}
                    </Link>
                    <button
                      type="button"
                      onClick={() => previewArchiveDuplicates(group)}
                      disabled={
                        group.duplicate_count === 0 ||
                        archiveAction?.previewLoading ||
                        archiveAction?.confirmLoading
                      }
                      className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#9bc7a4] hover:bg-[#f0faf2] hover:text-[#17602a] disabled:cursor-not-allowed disabled:opacity-60"
                    >
                      <SearchCheck className="h-3.5 w-3.5" aria-hidden="true" />
                      {archiveAction?.previewLoading
                        ? t("archiveActions.previewing")
                        : t("archiveActions.preview")}
                    </button>
                    <button
                      type="button"
                      onClick={() => confirmArchiveDuplicates(group)}
                      disabled={
                        group.duplicate_count === 0 ||
                        !previewReady ||
                        archiveAction?.previewLoading ||
                        archiveAction?.confirmLoading
                      }
                      className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#d9b36f] hover:bg-[#fff7e8] hover:text-[#8a5a08] disabled:cursor-not-allowed disabled:opacity-60"
                    >
                      <Archive className="h-3.5 w-3.5" aria-hidden="true" />
                      {archiveAction?.confirmLoading
                        ? t("archiveActions.confirming")
                        : t("archiveActions.confirm")}
                    </button>
                    <span className="text-[11px] leading-5 text-[#77736a]">
                      {t("archiveActions.requiresOwner")}
                    </span>
                  </div>
                  {archiveAction?.error ? (
                    <div className="mt-2 border border-[#e2a29b] bg-[#fff0ef] px-2 py-1.5 text-[#9f2f25]">
                      {archiveAction.error}
                    </div>
                  ) : null}
                  {previewResult ? (
                    <div className="mt-2 border border-[#d9b36f] bg-[#fff7e8] px-2 py-1.5 text-[#8a5a08]">
                      <p className="font-semibold">
                        {t(`archiveActions.statuses.${previewKey}` as never)}
                      </p>
                      <p className="mt-1 text-[#5f5b52]">
                        {t("archiveActions.previewResult", {
                          count: previewResult.would_archive_entry_ids.length,
                          writesKm: String(previewResult.writes_km),
                          writesAudit: String(previewResult.writes_governance_audit),
                        })}
                      </p>
                      <p className="mt-1 text-[#5f5b52]">
                        {t("archiveActions.previewNext")}
                      </p>
                      <p className="mt-1 break-all font-mono text-[11px] text-[#5f5b52]">
                        {t("archiveActions.planFingerprint", {
                          fingerprint: previewResult.dry_run_plan_fingerprint ?? "--",
                        })}
                      </p>
                      {previewResult.stale_ratio_snapshot ? (
                        <p className="mt-1 text-[#5f5b52]">
                          {t("archiveActions.snapshot", {
                            stale: previewResult.stale_ratio_snapshot.stale_count,
                            total: previewResult.stale_ratio_snapshot.total_count,
                            ratio: formatStaleRatio(previewResult.stale_ratio_snapshot.stale_ratio),
                            threshold: formatStaleRatio(previewResult.stale_ratio_snapshot.threshold),
                          })}
                        </p>
                      ) : null}
                    </div>
                  ) : null}
                  {finalResult ? (
                    <div className="mt-2 border border-[#9bc7a4] bg-[#f0faf2] px-2 py-1.5 text-[#17602a]">
                      <p className="font-semibold">
                        {t(`archiveActions.statuses.${finalResultKey}` as never)}
                      </p>
                      <p className="mt-1 text-[#5f5b52]">
                        {t("archiveActions.result", {
                          archived: finalResult.archived_entry_ids.length,
                          audit: finalResult.audit_dispatch_id ?? "--",
                        })}
                      </p>
                      <p className="mt-1 text-[#5f5b52]">
                        {t("archiveActions.recheck", {
                          status: t(
                            `archiveActions.recheckStatuses.${staleRatioRecheckStatusKey(
                              finalResult.stale_ratio_recheck_status
                            )}` as never
                          ),
                          dispatch: finalResult.stale_ratio_recheck_dispatch_id ?? "--",
                        })}
                      </p>
                      {finalResult.stale_ratio_snapshot ? (
                        <p className="mt-1 text-[#5f5b52]">
                          {t("archiveActions.snapshot", {
                            stale: finalResult.stale_ratio_snapshot.stale_count,
                            total: finalResult.stale_ratio_snapshot.total_count,
                            ratio: formatStaleRatio(finalResult.stale_ratio_snapshot.stale_ratio),
                            threshold: formatStaleRatio(finalResult.stale_ratio_snapshot.threshold),
                          })}
                        </p>
                      ) : null}
                    </div>
                  ) : null}
                </div>
              );
            })}
          </div>
        </div>
      ) : draftGroups.length > 0 ? (
        <div className="border-t border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
          <div className="mb-3 flex items-center gap-2">
            <FileText className="h-4 w-4 text-[#5f5b52]" aria-hidden="true" />
            <h4 className="text-xs font-semibold uppercase tracking-[0.08em] text-[#5f5b52]">
              {t("draftSectionTitle")}
            </h4>
          </div>
          <div className="grid gap-2 md:grid-cols-2">
            {draftGroups.slice(0, 4).map((group) => (
              <div
                key={group.eventId}
                className="border border-[#e0ddd4] bg-white px-3 py-2 text-xs text-[#5f5b52]"
              >
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <p className="truncate font-mono font-semibold text-[#141413]">
                      {group.eventId}
                    </p>
                    <p className="mt-1 truncate text-[#77736a]">{group.canonical.title}</p>
                  </div>
                  <span className="shrink-0 border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5 font-mono">
                    {group.canonical.id}
                  </span>
                </div>
                <p className="mt-2">
                  {t("draftGroup", {
                    count: group.entries.length,
                    duplicates: group.duplicateCount,
                  })}
                </p>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div className="border-t border-[#e0ddd4] px-4 py-3 text-xs text-[#5f5b52]">
          {t("draftsEmpty")}
        </div>
      )}
    </section>
  );
}

function DriftFingerprintPanel({
  state,
  onRecorded,
}: {
  state: DriftFingerprintState | null;
  onRecorded: () => void;
}) {
  const t = useTranslations("awooop.workItems.driftFingerprint");
  const [action, setAction] = useState<{
    loading: boolean;
    result: DriftFingerprintHandoffResult | null;
    error: string | null;
  }>({
    loading: false,
    result: null,
    error: null,
  });
  const fsmKey = driftFsmStateKey(state?.fsm_state);
  const nextKey = driftNextStepKey(state?.next_step);
  const remediationKindKey = driftRemediationKindKey(
    state?.latest_remediation?.remediation_kind
  );
  const remediationStatusKey = driftRemediationStatusKey(
    state?.latest_remediation?.remediation_status
  );
  const handoffKind = state?.open_pr?.is_zero_diff
    ? "zero_diff_pr_cleanup"
    : "open_pr_review";
  const prUrl = state?.open_pr?.html_url ?? state?.open_pr?.url ?? null;

  const recordHandoff = useCallback(async () => {
    if (!state?.latest_report_id) return;
    setAction({ loading: true, result: null, error: null });
    const result = await postJson<DriftFingerprintHandoffResult>(
      `${API_BASE}/api/v1/drift/fingerprints/handoff`,
      {
        report_id: state.latest_report_id,
        namespace: state.namespace ?? "awoooi-prod",
        handoff_kind: handoffKind,
        pr_url: prUrl,
      },
      12000
    );
    setAction({
      loading: false,
      result,
      error: result ? null : t("actions.failed"),
    });
    if (result?.history?.recorded) onRecorded();
  }, [handoffKind, onRecorded, prUrl, state?.latest_report_id, state?.namespace, t]);

  return (
    <section className="border border-[#e0ddd4] bg-white">
      <div className="flex flex-wrap items-center justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex items-center gap-2">
          <Fingerprint className="h-4 w-4 text-[#8a5a08]" aria-hidden="true" />
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="text-xs text-[#77736a]">{t("subtitle")}</p>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2 font-mono text-xs text-[#5f5b52]">
          <span className="border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5">
            {t("occurrences", { count: state?.occurrences_12h ?? 0 })}
          </span>
          <span className="border border-[#d8d3c7] bg-white px-2 py-0.5">
            {t("risk", {
              high: state?.high_count ?? 0,
              medium: state?.medium_count ?? 0,
              info: state?.info_count ?? 0,
            })}
          </span>
        </div>
      </div>

      {state === null ? (
        <div className="px-4 py-4 text-sm text-[#8a5a08]">
          {t("unavailable")}
        </div>
      ) : (
        <div className="grid gap-px bg-[#eee9dd] lg:grid-cols-[1.3fr_1fr]">
          <div className="bg-white px-4 py-4">
            <div className="flex flex-wrap items-start justify-between gap-3">
              <div className="min-w-0">
                <p className="font-mono text-xs font-semibold text-[#141413]">
                  {state.fingerprint ?? "--"}
                </p>
                <p className="mt-1 text-xs leading-5 text-[#77736a]">
                  {t("report", {
                    report: state.latest_report_id ?? "--",
                    namespace: state.namespace ?? "--",
                  })}
                </p>
              </div>
              <span className="border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5 text-xs font-semibold text-[#8a5a08]">
                {t(`fsmStates.${fsmKey}` as never)}
              </span>
            </div>
            <div className="mt-3 grid gap-1 text-xs leading-5 text-[#5f5b52]">
              <p>{t("summary", { summary: state.summary ?? "--" })}</p>
              <p>
                {t("next", {
                  step: t(`nextSteps.${nextKey}` as never),
                })}
              </p>
              <p>
                {t("p0Dedup", {
                  hours: state.p0_escalation?.dedup_window_hours ?? 24,
                  enabled: String(state.p0_escalation?.suppresses_repeated_p0 ?? false),
                })}
              </p>
              <p>
                {t("writes", {
                  drift: String(state.writes_drift_status ?? false),
                  incident: String(state.writes_incident_state ?? false),
                  repair: String(state.writes_auto_repair_result ?? false),
                  ticket: String(state.writes_ticket ?? false),
                })}
              </p>
            </div>
          </div>

          <div className="bg-white px-4 py-4">
            <div className="flex items-center gap-2">
              <GitPullRequest className="h-4 w-4 text-[#87867f]" aria-hidden="true" />
              <h4 className="text-sm font-semibold text-[#141413]">{t("pr.title")}</h4>
            </div>
            <div className="mt-3 grid gap-1 text-xs leading-5 text-[#5f5b52]">
              <p>{t("pr.number", { number: state.open_pr?.number ?? "--" })}</p>
              <p>
                {t("pr.zeroDiff", {
                  zeroDiff: String(state.open_pr?.is_zero_diff ?? false),
                  files: state.open_pr?.file_count ?? "--",
                  commits: state.open_pr?.commit_count ?? "--",
                })}
              </p>
              <p>{t("pr.status", { status: state.open_pr?.state ?? "--" })}</p>
              <p>
                {t("handoff.latest", {
                  status: state.latest_handoff?.handoff_status ?? "--",
                })}
              </p>
            </div>
            <div className="mt-4 border border-[#d8d3c7] bg-[#faf9f3] px-3 py-2">
              <div className="flex items-center gap-2">
                <ShieldCheck className="h-4 w-4 text-[#17602a]" aria-hidden="true" />
                <h4 className="text-sm font-semibold text-[#141413]">
                  {t("remediation.title")}
                </h4>
              </div>
              <div className="mt-2 grid gap-1 text-xs leading-5 text-[#5f5b52]">
                <p>
                  {t("remediation.latest", {
                    kind: t(`remediationKinds.${remediationKindKey}` as never),
                    status: t(`remediationStatuses.${remediationStatusKey}` as never),
                  })}
                </p>
                <p>
                  {t("remediation.verification", {
                    report: state.latest_remediation?.verification_report_id ?? "--",
                    summary:
                      state.latest_remediation?.verification_summary?.summary ?? "--",
                  })}
                </p>
                <p>
                  {t("remediation.note", {
                    note: state.latest_remediation?.note ?? "--",
                  })}
                </p>
              </div>
            </div>
            <div className="mt-3 flex flex-wrap gap-2">
              <button
                type="button"
                onClick={recordHandoff}
                disabled={!state.latest_report_id || action.loading}
                className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#9bc7a4] hover:bg-[#f0faf2] hover:text-[#17602a] disabled:cursor-not-allowed disabled:opacity-60"
              >
                <GitBranch className="h-3.5 w-3.5" aria-hidden="true" />
                {action.loading ? t("actions.recording") : t("actions.record")}
              </button>
              <Link
                href={"/drift" as never}
                className="inline-flex items-center gap-1.5 border border-[#d8d3c7] bg-white px-2 py-1 text-xs font-semibold text-[#2e2b26] hover:border-[#1f6feb] hover:bg-[#edf4ff] hover:text-[#0f4fa8]"
              >
                <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
                {t("actions.openDrift")}
              </Link>
            </div>
            {action.error ? (
              <div className="mt-3 border border-[#e2a29b] bg-[#fff0ef] px-3 py-2 text-xs leading-5 text-[#9f2f25]">
                {action.error}
              </div>
            ) : null}
            {action.result ? (
              <div className="mt-3 border border-[#9bc7a4] bg-[#f0faf2] px-3 py-2 text-xs leading-5 text-[#17602a]">
                <p className="font-semibold">
                  {t("actions.recorded", {
                    recorded: String(action.result.history?.recorded ?? false),
                  })}
                </p>
                <p className="mt-1 text-[#5f5b52]">
                  {t("actions.handoffStatus", {
                    status: action.result.handoff_status ?? "--",
                  })}
                </p>
              </div>
            ) : null}
          </div>
        </div>
      )}
    </section>
  );
}

export default function AwoooPWorkItemsPage() {
  const t = useTranslations("awooop.workItems");
  const locale = useLocale();
  const searchParams = useSearchParams();
  const projectId = searchParams.get("project_id") || "awoooi";
  const focusedWorkItemId = searchParams.get("work_item_id");
  const focusedIncidentId = searchParams.get("incident_id");
  const focusedRepairCandidateDraft = useMemo(
    () => parseRepairCandidateDraftWorkItemId(
      focusedWorkItemId,
      focusedIncidentId,
      projectId
    ),
    [focusedIncidentId, focusedWorkItemId, projectId]
  );
  const effectiveFocusedIncidentId =
    focusedIncidentId ?? focusedRepairCandidateDraft?.incidentId ?? null;
  const [telemetry, setTelemetry] = useState<Telemetry>({
    quality: null,
    governanceEvents: null,
    governanceQueue: null,
    governanceKnowledgeQueue: null,
    knowledgeReviewDrafts: null,
    knowledgeReviewDedupe: null,
    knowledgeStaleCandidates: null,
    knowledgeStaleOwnerReviews: null,
    knowledgeStaleOwnerReviewBurnDown: null,
    knowledgeStaleOwnerReviewCompletionQueue: null,
    channelEvents: null,
    eventRecurrence: null,
    slo: null,
    remediationHistory: null,
    driftFingerprintState: null,
    callbackReplies: null,
    statusChain: null,
    incidentTimeline: null,
    aiRouteStatus: null,
  });
  const [loading, setLoading] = useState(true);
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);

  const fetchTelemetry = useCallback(async () => {
    setLoading(true);
    const encodedProjectId = encodeURIComponent(projectId);
    const qualityUrl = `${API_BASE}/api/v1/platform/truth-chain/quality/summary?project_id=${encodedProjectId}&hours=24&limit=30`;
    const governanceEventsUrl = `${API_BASE}/api/v1/ai/governance/events?event_type=knowledge_degradation&event_type=governance_slo_data_gap&status=unresolved&size=10`;
    const governanceQueueUrl = `${API_BASE}/api/v1/ai/governance/queue?dispatch_status=pending&size=10`;
    const governanceKnowledgeQueueUrl = `${API_BASE}/api/v1/ai/governance/queue?dispatch_status=all&event_type=knowledge_degradation&size=20`;
    const knowledgeReviewDraftsUrl = `${API_BASE}/api/v1/knowledge?entry_type=auto_runbook&status=review&q=${encodeURIComponent("KM healthcheck")}&limit=100`;
    const knowledgeReviewDedupeUrl = `${API_BASE}/api/v1/ai/governance/km-review-drafts/dedupe?limit=100`;
    const knowledgeStaleCandidatesUrl = `${API_BASE}/api/v1/ai/governance/km-stale-candidates?project_id=${encodedProjectId}&limit=20`;
    const knowledgeStaleOwnerReviewsUrl = `${API_BASE}/api/v1/ai/governance/km-stale-owner-reviews?project_id=${encodedProjectId}&dispatch_status=pending&limit=30`;
    const knowledgeStaleOwnerReviewBurnDownUrl = `${API_BASE}/api/v1/ai/governance/km-stale-owner-review-burndown?project_id=${encodedProjectId}&limit=20`;
    const knowledgeStaleOwnerReviewCompletionQueueUrl = `${API_BASE}/api/v1/ai/governance/km-stale-owner-review-completion-queue?project_id=${encodedProjectId}&status_bucket=all&limit=30`;
    const channelEventsUrl = `${API_BASE}/api/v1/platform/events/recent?project_id=${encodedProjectId}&provider_prefix=alertmanager&limit=20`;
    const recurrenceUrl = `${API_BASE}/api/v1/platform/events/dossier/recurrence?project_id=${encodedProjectId}&limit=100`;
    const sloUrl = `${API_BASE}/api/v1/ai/slo`;
    const remediationHistoryUrl = `${API_BASE}/api/v1/ai/slo/remediation/history?limit=80`;
    const driftFingerprintUrl = `${API_BASE}/api/v1/drift/fingerprints/state?namespace=awoooi-prod`;
    const callbackRepliesUrl = `${API_BASE}/api/v1/platform/runs/callback-replies?project_id=${encodedProjectId}&per_page=100`;
    const aiRouteStatusUrl = `${API_BASE}/api/v1/platform/ai-route-status?workload_type=deep_rca`;

    const [
      quality,
      governanceEvents,
      governanceQueue,
      governanceKnowledgeQueue,
      knowledgeReviewDrafts,
      knowledgeReviewDedupe,
      knowledgeStaleCandidates,
      knowledgeStaleOwnerReviews,
      knowledgeStaleOwnerReviewBurnDown,
      knowledgeStaleOwnerReviewCompletionQueue,
      channelEvents,
      eventRecurrence,
      slo,
      remediationHistory,
      driftFingerprintState,
      callbackReplies,
      aiRouteStatus,
    ] = await Promise.all([
      fetchJson<AutomationQualitySummary>(qualityUrl, 15000),
      fetchJson<GovernanceEventsResponse>(governanceEventsUrl),
      fetchJson<GovernanceQueueResponse>(governanceQueueUrl),
      fetchJson<GovernanceQueueResponse>(governanceKnowledgeQueueUrl),
      fetchJson<KnowledgeListResponse>(knowledgeReviewDraftsUrl),
      fetchJson<KnowledgeReviewDraftDedupeResponse>(knowledgeReviewDedupeUrl),
      fetchJson<KnowledgeStaleCandidatesResponse>(knowledgeStaleCandidatesUrl),
      fetchJson<KnowledgeStaleOwnerReviewInboxResponse>(knowledgeStaleOwnerReviewsUrl),
      fetchJson<KnowledgeStaleOwnerReviewBurnDownResponse>(knowledgeStaleOwnerReviewBurnDownUrl),
      fetchJson<KnowledgeStaleOwnerReviewCompletionQueueResponse>(knowledgeStaleOwnerReviewCompletionQueueUrl),
      fetchJson<RecentEventsResponse>(channelEventsUrl),
      fetchJson<RecurrenceResponse>(recurrenceUrl),
      fetchJson<SloResponse>(sloUrl),
      fetchJson<RemediationHistoryResponse>(remediationHistoryUrl),
      fetchJson<DriftFingerprintState>(driftFingerprintUrl, 12000),
      fetchJson<CallbackRepliesWorkItemResponse>(callbackRepliesUrl, 12000),
      fetchJson<AiRouteStatusResponse>(aiRouteStatusUrl, 12000),
    ]);

    const statusChainIncidentId = selectStatusChainIncidentId(
      effectiveFocusedIncidentId,
      remediationHistory,
      eventRecurrence
    );
    let statusChain: AwoooPStatusChain | null = null;
    if (statusChainIncidentId) {
      const statusChainParams = new URLSearchParams({ project_id: projectId });
      statusChainParams.append("incident_id", statusChainIncidentId);
      statusChain = await fetchJson<AwoooPStatusChain>(
        `${API_BASE}/api/v1/platform/status-chain?${statusChainParams.toString()}`,
        12000
      );
    }
    const timelineIncidentId = statusChain?.source_id ?? statusChainIncidentId;
    const incidentTimeline = timelineIncidentId
      ? await fetchJson<IncidentTimelineResponse>(
          `${API_BASE}/api/v1/incidents/${encodeURIComponent(timelineIncidentId)}/timeline`,
          12000
        )
      : null;

    setTelemetry({
      quality,
      governanceEvents,
      governanceQueue,
      governanceKnowledgeQueue,
      knowledgeReviewDrafts,
      knowledgeReviewDedupe,
      knowledgeStaleCandidates,
      knowledgeStaleOwnerReviews,
      knowledgeStaleOwnerReviewBurnDown,
      knowledgeStaleOwnerReviewCompletionQueue,
      channelEvents,
      eventRecurrence,
      slo,
      remediationHistory,
      driftFingerprintState,
      callbackReplies,
      statusChain,
      incidentTimeline,
      aiRouteStatus,
    });
    setLastUpdated(new Date());
    setLoading(false);
  }, [effectiveFocusedIncidentId, projectId]);

  useEffect(() => {
    fetchTelemetry();
  }, [fetchTelemetry]);

  const workItems = useMemo(() => buildWorkItems(telemetry, t), [telemetry, t]);
  const latestRemediationHistory = telemetry.remediationHistory?.items?.[0] ?? null;
  const remediationIncidentIds = useMemo(
    () => Array.from(
      new Set(
        (telemetry.remediationHistory?.items ?? [])
          .map((item) => item.incident_id)
          .filter(Boolean)
      )
    ),
    [telemetry.remediationHistory?.items]
  );
  const recurrenceIncidentIds = useMemo(
    () => recurrenceOpenItems(telemetry.eventRecurrence)
      .map((item) => item.latest_incident_id ?? item.work_item?.incident_id)
      .filter(Boolean),
    [telemetry.eventRecurrence]
  );
  const visibleIncidentIds = useMemo(
    () => Array.from(
      new Set([
        ...remediationIncidentIds,
        ...recurrenceIncidentIds,
        effectiveFocusedIncidentId,
      ].filter(Boolean))
    ),
    [effectiveFocusedIncidentId, recurrenceIncidentIds, remediationIncidentIds]
  );
  const summary = useMemo(
    () => [
      { label: t("summary.live"), value: workItems.filter((item) => item.status === "live").length, icon: Activity },
      { label: t("summary.inProgress"), value: workItems.filter((item) => item.status === "in_progress").length, icon: GitBranch },
      { label: t("summary.watching"), value: workItems.filter((item) => item.status === "watching").length, icon: Gauge },
      { label: t("summary.blocked"), value: workItems.filter((item) => item.status === "blocked").length, icon: ShieldCheck },
    ],
    [t, workItems]
  );

  const formattedUpdated = lastUpdated
    ? lastUpdated.toLocaleTimeString(locale === "zh-TW" ? "zh-TW" : "en-US", {
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
      })
    : "--";

  return (
    <div className="space-y-5">
      <section className="border border-[#e0ddd4] bg-white">
        <div className="flex flex-wrap items-center justify-between gap-4 px-4 py-4">
          <div className="flex items-center gap-3">
            <ClipboardList className="h-5 w-5 text-[#d97757]" aria-hidden="true" />
            <div>
              <h2 className="text-lg font-semibold tracking-normal text-[#141413]">
                {t("title")}
              </h2>
              <p className="mt-1 text-xs leading-5 text-[#77736a]">
                {t("subtitle", { count: workItems.length })}
              </p>
            </div>
          </div>
          <div className="flex flex-wrap items-center gap-3">
            <span className="font-mono text-xs text-[#77736a]">
              {t("lastUpdated", { time: formattedUpdated })}
            </span>
            <button
              type="button"
              onClick={fetchTelemetry}
              className="inline-flex items-center gap-2 border border-[#d8d3c7] bg-[#faf9f3] px-3 py-2 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
            >
              <RefreshCw
                className={cn("h-4 w-4", loading && "animate-spin")}
                aria-hidden="true"
              />
              {t("refresh")}
            </button>
          </div>
        </div>
      </section>

      <ProductionClaimBanner loading={loading} summary={telemetry.quality} />

      <div className="grid gap-px border border-[#e0ddd4] bg-[#e0ddd4] md:grid-cols-4">
        {summary.map((item) => (
          <SummaryCell key={item.label} label={item.label} value={item.value} icon={item.icon} />
        ))}
      </div>

      <IncidentEvidenceHeader
        projectId={projectId}
        incidentIds={visibleIncidentIds}
        dryRunCount={telemetry.remediationHistory?.total}
        latestRoute={routeLabel(latestRemediationHistory)}
        writesIncidentState={latestRemediationHistory?.writes_incident_state}
        writesAutoRepairResult={latestRemediationHistory?.writes_auto_repair_result}
      />

      <Adr100RemediationQueuePanel
        queue={telemetry.slo?.adr100?.verification_coverage?.remediation_queue}
        focusedWorkItemId={focusedWorkItemId}
        onRecorded={fetchTelemetry}
      />

      <RepairCandidateDraftPanel
        draft={focusedRepairCandidateDraft}
        chain={telemetry.statusChain}
      />

      <AwoooPStatusChainPanel chain={telemetry.statusChain} />

      <WorkItemIncidentAuditPanel
        timeline={telemetry.incidentTimeline}
        chain={telemetry.statusChain}
        focusedIncidentId={effectiveFocusedIncidentId}
        projectId={projectId}
        loading={loading}
      />

      <RecurrenceWorkQueuePanel
        recurrence={telemetry.eventRecurrence}
        focusedWorkItemId={focusedWorkItemId}
        focusedIncidentId={effectiveFocusedIncidentId}
        projectId={projectId}
        onRecorded={fetchTelemetry}
      />

      <KnowledgeGovernancePanel
        queue={telemetry.governanceKnowledgeQueue}
        reviewDrafts={telemetry.knowledgeReviewDrafts}
        dedupe={telemetry.knowledgeReviewDedupe}
        staleCandidates={telemetry.knowledgeStaleCandidates}
        ownerReviewInbox={telemetry.knowledgeStaleOwnerReviews}
        burnDown={telemetry.knowledgeStaleOwnerReviewBurnDown}
        completionQueue={telemetry.knowledgeStaleOwnerReviewCompletionQueue}
        onArchived={fetchTelemetry}
      />

      <DriftFingerprintPanel
        state={telemetry.driftFingerprintState}
        onRecorded={fetchTelemetry}
      />

      <div className="overflow-hidden border border-[#e0ddd4] bg-white">
        <div className="overflow-x-auto">
          <table className="w-full" role="table" aria-label={t("tableLabel")}>
            <thead>
              <tr className="border-b border-[#e0ddd4] bg-[#faf9f3]">
                <th className="px-4 py-3 text-left text-xs font-semibold text-[#77736a]">
                  {t("columns.phase")}
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-[#77736a]">
                  {t("columns.work")}
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-[#77736a]">
                  {t("columns.status")}
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-[#77736a]">
                  {t("columns.surface")}
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-[#77736a]">
                  {t("columns.source")}
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-[#77736a]">
                  {t("columns.evidence")}
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-[#77736a]">
                  {t("columns.gate")}
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-[#77736a]">
                  {t("columns.link")}
                </th>
              </tr>
            </thead>
            <tbody>
              {workItems.map((item) => (
                <tr key={item.id} className="border-b border-[#eee9dd] last:border-b-0">
                  <td className="px-4 py-3 font-mono text-xs font-semibold text-[#141413]">
                    {item.phase}
                  </td>
                  <td className="min-w-[240px] px-4 py-3 text-sm font-medium text-[#141413]">
                    {t(`items.${item.id}.title` as never)}
                  </td>
                  <td className="px-4 py-3">
                    <StatusBadge status={item.status} />
                  </td>
                  <td className="px-4 py-3 text-sm text-[#5f5b52]">
                    {t(`surfaces.${item.surfaceKey}` as never)}
                  </td>
                  <td className="min-w-[220px] px-4 py-3">
                    <span className="inline-flex items-center gap-1.5 font-mono text-xs text-[#5f5b52]">
                      <Database className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
                      {item.source}
                    </span>
                  </td>
                  <td className="min-w-[220px] px-4 py-3 text-sm leading-5 text-[#5f5b52]">
                    {item.evidence}
                    {item.evidenceDetails && item.evidenceDetails.length > 0 && (
                      <div className="mt-2 flex flex-col gap-1">
                        {item.evidenceDetails.map((detail) => (
                          <span
                            key={detail}
                            className="inline-flex w-fit max-w-full border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5 font-mono text-[11px] leading-5 text-[#5f5b52]"
                          >
                            {detail}
                          </span>
                        ))}
                      </div>
                    )}
                  </td>
                  <td className="min-w-[240px] px-4 py-3">
                    <span className="inline-flex items-start gap-1.5 text-sm leading-5 text-[#5f5b52]">
                      <Network className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden="true" />
                      {t(`gates.${item.gateKey}` as never)}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <Link
                      href={item.href as never}
                      className="inline-flex items-center gap-1.5 border border-[#d8d3c7] px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
                    >
                      {t("open")}
                      <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
                    </Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
