"use client";

import { Activity, BookOpenCheck, CheckCircle2, Link2, RadioTower, Route, ShieldAlert, ShieldCheck, TriangleAlert, Wrench } from "lucide-react";
import { useTranslations } from "next-intl";

import { Link } from "@/i18n/routing";
import { cn } from "@/lib/utils";

export interface AwoooPStatusChain {
  schema_version?: string;
  source?: string;
  source_id?: string | null;
  incident_ids?: string[];
  current_stage?: string | null;
  stage_status?: string | null;
  verdict?: string | null;
  repair_state?: string | null;
  verification?: string | null;
  needs_human?: boolean | null;
  next_step?: string | null;
  operator_outcome?: {
    schema_version?: string;
    state?: string | null;
    severity?: string | null;
    summary_zh?: string | null;
    needs_human?: boolean | null;
    human_action_required?: boolean | null;
    human_action_reason?: string | null;
    next_action?: string | null;
    execution_result?: {
      approval_status?: string | null;
      completion_status?: string | null;
      command_status?: string | null;
      repair_status?: string | null;
      failure_status?: string | null;
      terminal?: boolean | null;
      summary_zh?: string | null;
    };
    notification?: {
      mode?: string | null;
      channels?: string[];
      telegram?: string | null;
      awooop?: string | null;
    };
  } | null;
  blockers?: string[];
  fetch_error?: string | null;
  evidence?: {
    auto_repair_records?: number | null;
    operation_records?: number | null;
    mcp_gateway_total?: number | null;
    knowledge_entries?: number | null;
    remediation_total?: number | null;
    remediation_state?: string | null;
    latest_route?: string | null;
    latest_mode?: string | null;
    latest_at?: string | null;
    latest_preview?: string | null;
    ansible_dry_run_only?: boolean | null;
  };
  writes?: {
    incident?: boolean | null;
    auto_repair?: boolean | null;
  };
  mcp?: {
    gateway?: {
      total?: number | null;
      success?: number | null;
      failed?: number | null;
      blocked?: number | null;
      first_class_total?: number | null;
      legacy_bridge_total?: number | null;
      policy_enforced_total?: number | null;
      stage?: string | null;
      stage_status?: string | null;
    };
    legacy?: {
      total?: number | null;
      success?: number | null;
      failed?: number | null;
    };
    top_tools?: Array<{
      source?: string | null;
      tool_name?: string | null;
      total?: number | null;
      success?: number | null;
      failed?: number | null;
      blocked?: number | null;
      last_error?: string | null;
    }>;
  };
  execution?: {
    operation_total?: number | null;
    latest_operation_type?: string | null;
    latest_status?: string | null;
    latest_actor?: string | null;
    latest_action?: string | null;
    latest_executor?: string | null;
    playbook_ids?: string[];
    playbook_paths?: string[];
    ansible?: {
      considered?: boolean | null;
      record_total?: number | null;
      candidate_count?: number | null;
      not_used_reason?: string | null;
      check_mode_total?: number | null;
      apply_total?: number | null;
      rollback_total?: number | null;
      pending_check_mode_total?: number | null;
      applied_success_total?: number | null;
      applied?: boolean | null;
      controlled_apply?: boolean | null;
      latest_operation_type?: string | null;
      latest_status?: string | null;
      latest_catalog_id?: string | null;
      latest_playbook_path?: string | null;
      latest_execution_mode?: string | null;
      latest_check_mode?: string | null | boolean;
      latest_returncode?: string | number | null;
      latest_apply_executed?: boolean | null;
      approval_source?: string | null;
      candidate_playbooks?: Array<{
        catalog_id?: string | null;
        playbook_path?: string | null;
        risk_level?: string | null;
        match_score?: number | null;
      }>;
    };
  };
  automation_handoff?: {
    schema_version?: string;
    kind?: string | null;
    status?: string | null;
    source_id?: string | null;
    work_item_id?: string | null;
    decision_effect?: string | null;
    runtime_execution_authorized?: boolean | null;
    writes_runtime_state?: boolean | null;
    owner_review_gate?: string | null;
    next_action?: string | null;
    asset_ids?: {
      dry_run?: string | null;
      apply_candidate?: string | null;
      verifier?: string | null;
    };
    closure_readiness?: {
      schema_version?: string;
      status?: string | null;
      completion_percent?: number | null;
      ready_count?: number | null;
      total_count?: number | null;
      blocked_count?: number | null;
      runtime_execution_authorized?: boolean | null;
      writes_runtime_state?: boolean | null;
      next_action?: string | null;
      blocked_reason?: string | null;
      gates?: Array<{
        key?: string | null;
        status?: string | null;
        detail?: string | null;
        asset_id?: string | null;
      }>;
      required_owner_fields?: string[];
      readback_assets?: Array<{
        key?: string | null;
        asset_id?: string | null;
        status?: string | null;
      }>;
      owner_release_package?: {
        schema_version?: string | null;
        status?: string | null;
        source_schema_version?: string | null;
        source_task_id?: string | null;
        runtime_authority?: string | null;
        packet_count?: number | null;
        approval_required_count?: number | null;
        blocked_count?: number | null;
        owner_release_approved_count?: number | null;
        maintenance_window_approved_count?: number | null;
        rollback_owner_confirmed_count?: number | null;
        operator_action_count?: number | null;
        packets?: Array<{
          id?: string | null;
          display_name?: string | null;
          owner_agent?: string | null;
          status?: string | null;
          summary?: string | null;
          runtime_write_allowed?: boolean | null;
        }>;
        operator_actions?: Array<{
          id?: string | null;
          owner_agent?: string | null;
          status?: string | null;
          summary?: string | null;
          runtime_write_allowed?: boolean | null;
        }>;
      };
      release_verifier_package?: {
        schema_version?: string | null;
        status?: string | null;
        source_schema_version?: string | null;
        source_task_id?: string | null;
        runtime_authority?: string | null;
        verifier_count?: number | null;
        rollback_count?: number | null;
        maintenance_hold_count?: number | null;
        live_apply_hold_count?: number | null;
        owner_release_authorized_count?: number | null;
        post_release_verifier_ready_count?: number | null;
        live_apply_release_pass_count?: number | null;
        operator_action_count?: number | null;
        verifier_gates?: Array<{
          id?: string | null;
          display_name?: string | null;
          owner_agent?: string | null;
          status?: string | null;
          summary?: string | null;
          runtime_write_allowed?: boolean | null;
        }>;
        operator_actions?: Array<{
          id?: string | null;
          owner_agent?: string | null;
          status?: string | null;
          summary?: string | null;
          runtime_write_allowed?: boolean | null;
        }>;
      };
      closure_tasks?: Array<{
        key?: string | null;
        status?: string | null;
        owner_agent?: string | null;
        source_asset_id?: string | null;
        work_item_id?: string | null;
        summary?: string | null;
        next_step?: string | null;
        runtime_write_allowed?: boolean | null;
      }>;
      controlled_execution_preflight?: {
        schema_version?: string | null;
        status?: string | null;
        source_id?: string | null;
        work_item_id?: string | null;
        runtime_execution_authorized?: boolean | null;
        runtime_write_allowed?: boolean | null;
        allowed_route_count?: number | null;
        candidate_route_count?: number | null;
        ready_count?: number | null;
        total_count?: number | null;
        blocked_count?: number | null;
        next_action?: string | null;
        blocked_reason?: string | null;
        routes?: Array<{
          route_id?: string | null;
          transport?: string | null;
          status?: string | null;
          source_asset_id?: string | null;
          check_mode_playbook_path?: string | null;
          apply_playbook_path?: string | null;
          allowed?: boolean | null;
          blocker?: string | null;
        }>;
        prerequisites?: Array<{
          key?: string | null;
          status?: string | null;
          detail?: string | null;
          required?: boolean | null;
        }>;
        forbidden_until_released?: string[];
      };
      execution_release_contract?: {
        schema_version?: string | null;
        status?: string | null;
        source_id?: string | null;
        work_item_id?: string | null;
        route_id?: string | null;
        runtime_execution_authorized?: boolean | null;
        runtime_write_allowed?: boolean | null;
        ready_count?: number | null;
        total_count?: number | null;
        blocked_count?: number | null;
        blocked_reason?: string | null;
        check_mode_playbook_path?: string | null;
        apply_playbook_path?: string | null;
        controlled_preflight_work_item_id?: string | null;
        fields?: Array<{
          key?: string | null;
          status?: string | null;
          value?: string | null;
          required?: boolean | null;
          next_step?: string | null;
        }>;
        owner_release_draft?: {
          schema_version?: string | null;
          status?: string | null;
          source_id?: string | null;
          work_item_id?: string | null;
          ai_prefilled_count?: number | null;
          human_decision_count?: number | null;
          runtime_execution_authorized?: boolean | null;
          runtime_write_allowed?: boolean | null;
          human_only_fields?: string[];
          draft_fields?: Array<{
            key?: string | null;
            status?: string | null;
            value?: string | null;
            reason?: string | null;
          }>;
          next_action?: string | null;
        };
        next_steps?: Array<{
          key?: string | null;
          owner_agent?: string | null;
          work_item_id?: string | null;
          summary?: string | null;
          runtime_write_allowed?: boolean | null;
        }>;
        forbidden_until_contract_complete?: string[];
      };
    };
    candidate?: {
      catalog_id?: string | null;
      check_mode_playbook_path?: string | null;
      apply_playbook_path?: string | null;
      risk_level?: string | null;
      match_score?: number | null;
    };
    gates?: Array<{
      key?: string | null;
      status?: string | null;
      detail?: string | null;
    }>;
    owner_review_checklist?: string[];
    forbidden_actions?: string[];
  } | null;
  repair_candidate_promotion?: {
    schema_version?: string | null;
    status?: string | null;
    source?: string | null;
    available?: boolean | null;
    reason?: string | null;
    approval_id?: string | null;
    work_item_id?: string | null;
    work_item_url?: string | null;
    summary?: string | null;
    runtime_execution_authorized?: boolean | null;
    runtime_write_allowed?: boolean | null;
    contract?: {
      schema_version?: string | null;
      status?: string | null;
      lane?: string | null;
      incident_id?: string | null;
      project_id?: string | null;
      source_work_item_id?: string | null;
      source_work_item_url?: string | null;
      route_id?: string | null;
      repair_command_template?: string | null;
      rollback_command_template?: string | null;
      verifier_plan_template?: string[];
      ready_count?: number | null;
      total_count?: number | null;
      blocked_count?: number | null;
      ready_fields?: string[];
      blocked_fields?: string[];
      fields?: Array<{
        field?: string | null;
        label?: string | null;
        status?: string | null;
        source?: string | null;
        value?: unknown;
        runtime_execution_authorized?: boolean | null;
      }>;
      blockers?: string[];
      runtime_write_allowed?: boolean | null;
      runtime_execution_authorized?: boolean | null;
      approval_required_before_execution?: boolean | null;
      owner_review_required?: boolean | null;
      forbidden_until_promoted?: string[];
      next_steps?: string[];
      controlled_automation_closure?: {
        schema_version?: string | null;
        status?: string | null;
        runtime_write_gate?: string | null;
        no_write_rehearsal?: {
          rehearsal_id?: string | null;
          status?: string | null;
          route_id?: string | null;
          planned_steps?: string[];
          writes_runtime_state?: boolean | null;
          executes_command?: boolean | null;
        } | null;
        verifier_writeback_plan?: {
          verifier_id?: string | null;
          status?: string | null;
          checks?: string[];
          result_states?: string[];
          writes_after_execution?: string[];
          writes_runtime_state?: boolean | null;
        } | null;
        automation_asset_ledger?: Array<{
          asset_type?: string | null;
          asset_id?: string | null;
          owner?: string | null;
          status?: string | null;
          next_action?: string | null;
        }>;
        operator_next_actions?: string[];
      } | null;
    } | null;
  } | null;
  source_refs?: {
    inbound_total?: number | null;
    outbound_total?: number | null;
    inbound_channels?: string[];
    refs?: {
      alert_ids?: string[];
      sentry_issue_ids?: string[];
      signoz_alerts?: string[];
      fingerprints?: string[];
      incident_ids?: string[];
    };
    correlation?: {
      schema_version?: string;
      status?: string | null;
      missing_reason?: string | null;
      verification_status?: string | null;
      direct_ref_total?: number | null;
      candidate_total?: number | null;
      applied_link_total?: number | null;
      provider_event_total?: number | null;
      latest_applied_link_at?: string | null;
      providers?: Record<string, {
        direct_ref_total?: number | null;
        candidate_total?: number | null;
        applied_link_total?: number | null;
        latest_event_at?: string | null;
        latest_heartbeat_at?: string | null;
        latest_applied_link_at?: string | null;
      }>;
      top_candidates?: Array<{
        provider?: string | null;
        provider_event_id?: string | null;
        stage?: string | null;
        score?: number | null;
        match_type?: string | null;
        link_state?: string | null;
        verification_status?: string | null;
        reasons?: string[];
        received_at?: string | null;
      }>;
    };
    latest_inbound?: {
      channel_type?: string | null;
      provider_event_id?: string | null;
      content_type?: string | null;
      is_duplicate?: boolean | null;
      received_at?: string | null;
    };
    latest_outbound?: {
      channel_type?: string | null;
      message_type?: string | null;
      send_status?: string | null;
      sent_at?: string | null;
    };
  };
}

function toneClass(chain?: AwoooPStatusChain | null) {
  if (!chain) return "border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]";
  if (chain.repair_state === "auto_repaired_verified") {
    return "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]";
  }
  if (chain.repair_state === "executed" || chain.stage_status === "success") {
    return "border-[#9bb6d9] bg-[#eef5ff] text-[#1f5b9b]";
  }
  return "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]";
}

function chainIcon(chain?: AwoooPStatusChain | null) {
  if (!chain) return Route;
  if (chain.repair_state === "auto_repaired_verified") return CheckCircle2;
  if (chain.needs_human || chain.repair_state === "blocked_manual_required") return ShieldCheck;
  return Activity;
}

function boolValue(value: boolean | null | undefined, emptyLabel: string) {
  if (value === true) return "true";
  if (value === false) return "false";
  return emptyLabel;
}

function valueOrEmpty(value: unknown, emptyLabel: string) {
  if (value === null || value === undefined || value === "") return emptyLabel;
  return String(value);
}

type SourceFlowTone = "success" | "warning" | "blocked" | "neutral";

function sourceFlowToneClass(tone: SourceFlowTone) {
  if (tone === "success") return "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]";
  if (tone === "blocked") return "border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]";
  if (tone === "warning") return "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]";
  return "border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]";
}

export function AwoooPStatusChainPanel({
  chain,
  compact = false,
  className,
}: {
  chain?: AwoooPStatusChain | null;
  compact?: boolean;
  className?: string;
}) {
  const t = useTranslations("awooop.statusChain");
  const Icon = chainIcon(chain);
  const tone = toneClass(chain);
  const emptyLabel = t("emptyValue");
  const evidence = chain?.evidence ?? {};
  const outcome = chain?.operator_outcome;
  const outcomeExecution = outcome?.execution_result;
  const automationHandoff = chain?.automation_handoff;
  const closureReadiness = automationHandoff?.closure_readiness;
  const blockers = chain?.blockers ?? [];
  const sourceCorrelation = chain?.source_refs?.correlation;
  const nextActionLabel = (value: unknown) => {
    const key = String(value ?? "");
    const labels: Record<string, string> = {
      open_apply_gate_work_item_review_verifier_and_km: t("nextActions.openApplyGateWorkItem"),
      owner_review_apply_gate_or_create_verifier_plan: t("nextActions.openApplyGateWorkItem"),
      manual_review_no_action_decision: t("nextActions.manualReviewNoActionDecision"),
      owner_review_repair_candidate_draft: t("nextActions.ownerReviewRepairCandidateDraft"),
      review_owner_release_packet_before_apply: t("nextActions.reviewOwnerReleasePacket"),
      manual_review_or_collect_repair_evidence: t("nextActions.collectRepairEvidence"),
      manual_investigation: t("nextActions.manualInvestigation"),
      auto_generate_repair_candidate_from_diagnostic_evidence: t("nextActions.autoGenerateRepairCandidate"),
      auto_verify_or_rollback_observed_write: t("nextActions.autoVerifyOrRollback"),
      auto_repair_blocker_or_connector_then_retry: t("nextActions.autoRepairBlockerConnector"),
      auto_generate_repair_or_break_glass_packet: t("nextActions.autoGenerateRepairOrBreakGlass"),
      run_verifier_or_rollback_candidate: t("nextActions.autoVerifyOrRollback"),
      run_post_execution_verifier_or_rollback: t("nextActions.autoVerifyOrRollback"),
      run_or_review_post_execution_verification: t("nextActions.reviewVerifier"),
      monitor_for_regression: t("nextActions.monitorRegression"),
      collect_evidence_or_wait: t("nextActions.collectEvidenceOrWait"),
      review_owner_release_packet_and_evidence_refs: t("nextActions.reviewOwnerReleasePacket"),
      collect_maintenance_window_and_rollback_owner: t("nextActions.collectMaintenanceRollback"),
      owner_release_required_before_controlled_apply: t("nextActions.ownerReleaseBeforeApply"),
      review_post_apply_verifier_before_any_apply: t("nextActions.reviewPostApplyVerifier"),
      prepare_km_and_playbook_writeback_after_verified_execution: t("nextActions.prepareKmPlaybookWriteback"),
      verify_incident_still_firing_or_recurring: t("nextActions.collectEvidenceOrWait"),
      confirm_route_scope_matches_target: t("nextActions.ownerReleaseBeforeApply"),
      rerun_check_mode_if_evidence_is_stale: t("nextActions.openApplyGateWorkItem"),
      collect_fresh_mcp_evidence_refs: t("nextActions.collectRepairEvidence"),
      collect_owner_approval_receipt: t("nextActions.reviewOwnerReleasePacket"),
      collect_maintenance_window: t("nextActions.collectMaintenanceRollback"),
      confirm_rollback_owner_and_disable_plan: t("nextActions.collectMaintenanceRollback"),
      define_blast_radius_before_apply: t("nextActions.collectMaintenanceRollback"),
      approve_post_apply_verifier_plan: t("nextActions.reviewPostApplyVerifier"),
      assign_km_writeback_owner_after_verified_execution: t("nextActions.prepareKmPlaybookWriteback"),
      assign_playbook_trust_owner_after_verified_execution: t("nextActions.prepareKmPlaybookWriteback"),
    };
    return labels[key] ?? valueOrEmpty(value, emptyLabel);
  };

  if (!chain) {
    return (
      <section className={cn("border border-[#e0ddd4] bg-white", compact ? "p-3" : "", className)}>
        <div className={cn("flex items-start gap-3", !compact && "px-4 py-3")}>
          <span className="flex h-8 w-8 shrink-0 items-center justify-center border border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]">
            <Route className="h-4 w-4" aria-hidden="true" />
          </span>
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 text-xs leading-5 text-[#77736a]">{t("empty")}</p>
          </div>
        </div>
      </section>
    );
  }

  const metrics = [
    { label: t("fields.stage"), value: `${valueOrEmpty(chain.current_stage, emptyLabel)} / ${valueOrEmpty(chain.stage_status, emptyLabel)}` },
    { label: t("fields.repair"), value: valueOrEmpty(chain.repair_state, emptyLabel) },
    { label: t("fields.verification"), value: valueOrEmpty(chain.verification, emptyLabel) },
    { label: t("fields.nextStep"), value: nextActionLabel(outcome?.next_action ?? chain.next_step) },
  ];
  const evidenceMetrics = [
    { label: t("evidence.autoRepair"), value: evidence.auto_repair_records ?? 0 },
    { label: t("evidence.ops"), value: evidence.operation_records ?? 0 },
    { label: t("evidence.mcp"), value: evidence.mcp_gateway_total ?? 0 },
    { label: t("evidence.km"), value: evidence.knowledge_entries ?? 0 },
  ];
  const sourceStatusLabels: Record<string, string> = {
    linked: t("source.statuses.linked"),
    candidate_found: t("source.statuses.candidateFound"),
    provider_fresh_no_match: t("source.statuses.providerFreshNoMatch"),
    missing: t("source.statuses.missing"),
    no_incident_context: t("source.statuses.noIncidentContext"),
    fetch_failed: t("source.statuses.fetchFailed"),
  };
  const sourceVerificationLabels: Record<string, string> = {
    applied_link_verified: t("source.verificationStatuses.appliedLinkVerified"),
    direct_ref_verified: t("source.verificationStatuses.directRefVerified"),
    candidate_only: t("source.verificationStatuses.candidateOnly"),
    provider_fresh_no_match: t("source.verificationStatuses.providerFreshNoMatch"),
    missing: t("source.verificationStatuses.missing"),
    no_incident_context: t("source.verificationStatuses.noIncidentContext"),
    fetch_failed: t("source.verificationStatuses.fetchFailed"),
  };
  const sourceReasonLabels: Record<string, string> = {
    provider_heartbeat_present_but_no_incident_match: t("source.reasons.providerHeartbeatNoMatch"),
    no_matching_provider_source_event: t("source.reasons.noMatchingProviderSourceEvent"),
    no_incident_ids: t("source.reasons.noIncidentIds"),
    incident_not_found: t("source.reasons.incidentNotFound"),
    source_correlation_fetch_failed: t("source.reasons.fetchFailed"),
  };
  const sourceStatus = String(sourceCorrelation?.status ?? "missing");
  const sourceVerificationStatus = String(sourceCorrelation?.verification_status ?? sourceStatus);
  const sourceMissingReason = String(sourceCorrelation?.missing_reason ?? "");
  const sourceStatusLabel = sourceStatusLabels[sourceStatus] ?? valueOrEmpty(sourceStatus, emptyLabel);
  const sourceReasonLabel = sourceReasonLabels[sourceMissingReason] ?? valueOrEmpty(sourceMissingReason, emptyLabel);
  const topAppliedLink = sourceCorrelation?.top_candidates?.find(
    (item) => item.link_state === "applied"
  );
  const latestAppliedLabel = valueOrEmpty(
    topAppliedLink?.provider_event_id ?? sourceCorrelation?.latest_applied_link_at,
    emptyLabel
  );
  const sourceProviderSummary = ["sentry", "signoz"].map((provider) => {
    const providerItem = sourceCorrelation?.providers?.[provider];
    return `${provider} ${providerItem?.direct_ref_total ?? 0}/${providerItem?.candidate_total ?? 0}/${providerItem?.applied_link_total ?? 0}`;
  }).join(" · ");
  const sourceProviderEntries = Object.entries(sourceCorrelation?.providers ?? {});
  const sourceProviderReadyTotal = sourceProviderEntries.filter(([, provider]) => (
    Boolean(provider.latest_event_at)
    || Boolean(provider.latest_heartbeat_at)
    || (provider.direct_ref_total ?? 0) > 0
    || (provider.candidate_total ?? 0) > 0
    || (provider.applied_link_total ?? 0) > 0
  )).length;
  const providerEventTotal = sourceCorrelation?.provider_event_total ?? 0;
  const directRefTotal = sourceCorrelation?.direct_ref_total ?? 0;
  const candidateTotal = sourceCorrelation?.candidate_total ?? 0;
  const appliedLinkTotal = sourceCorrelation?.applied_link_total ?? 0;
  const providerIngressReady = providerEventTotal > 0 || sourceProviderReadyTotal > 0;
  const sourceEvidenceFound = directRefTotal > 0 || candidateTotal > 0 || appliedLinkTotal > 0;
  const sourceLinkVerified = sourceVerificationStatus === "applied_link_verified"
    || sourceVerificationStatus === "direct_ref_verified";
  const sourceVerificationBlocked = sourceVerificationStatus === "missing"
    || sourceVerificationStatus === "fetch_failed"
    || sourceVerificationStatus === "no_incident_context";
  const sourceEvidenceFlow = sourceCorrelation ? [
    {
      key: "provider-ingress",
      Icon: RadioTower,
      tone: (providerIngressReady ? "success" : "warning") as SourceFlowTone,
      label: t("source.flow.providerIngress"),
      status: providerIngressReady ? t("source.flow.status.ready") : t("source.flow.status.waiting"),
      detail: t("source.flow.providerDetail", {
        providerEvents: providerEventTotal,
        readyProviders: sourceProviderReadyTotal,
      }),
    },
    {
      key: "source-evidence",
      Icon: Link2,
      tone: (appliedLinkTotal > 0 ? "success" : (sourceEvidenceFound ? "warning" : "blocked")) as SourceFlowTone,
      label: t("source.flow.sourceEvidence"),
      status: appliedLinkTotal > 0
        ? t("source.flow.status.applied")
        : (sourceEvidenceFound ? t("source.flow.status.needsReview") : t("source.flow.status.waiting")),
      detail: t("source.directCandidateValue", {
        direct: directRefTotal,
        candidate: candidateTotal,
        applied: appliedLinkTotal,
      }),
    },
    {
      key: "applied-verification",
      Icon: CheckCircle2,
      tone: (sourceLinkVerified ? "success" : (sourceVerificationBlocked ? "blocked" : "warning")) as SourceFlowTone,
      label: t("source.flow.appliedVerification"),
      status: sourceVerificationLabels[sourceVerificationStatus] ?? valueOrEmpty(sourceVerificationStatus, emptyLabel),
      detail: t("source.flow.verificationDetail", {
        latest: latestAppliedLabel,
      }),
    },
  ] : [];
  const mcpGateway = chain.mcp?.gateway ?? {};
  const legacyMcp = chain.mcp?.legacy ?? {};
  const topTool = chain.mcp?.top_tools?.[0];
  const topToolNames = chain.mcp?.top_tools
    ?.slice(0, 3)
    .map((item) => item.tool_name)
    .filter(Boolean)
    .join(" / ") || emptyLabel;
  const execution = chain.execution ?? {};
  const ansible = execution.ansible ?? {};
  const candidatePlaybook = ansible.candidate_playbooks?.[0];
  const selectedPlaybook = execution.playbook_paths?.[0]
    ?? execution.playbook_ids?.[0]
    ?? ansible.latest_catalog_id
    ?? ansible.latest_playbook_path
    ?? candidatePlaybook?.playbook_path
    ?? candidatePlaybook?.catalog_id
    ?? emptyLabel;
  const mcpGatewayTotal = mcpGateway.total ?? 0;
  const mcpGatewayProblemTotal = (mcpGateway.failed ?? 0) + (mcpGateway.blocked ?? 0);
  const executionTotal = execution.operation_total ?? 0;
  const handoffCandidate = automationHandoff?.candidate;
  const handoffAssets = automationHandoff?.asset_ids;
  const closureGates = closureReadiness?.gates ?? [];
  const closureReadbackAssets = closureReadiness?.readback_assets ?? [];
  const closureOwnerFields = closureReadiness?.required_owner_fields ?? [];
  const closureOwnerPackage = closureReadiness?.owner_release_package;
  const closureVerifierPackage = closureReadiness?.release_verifier_package;
  const closureTasks = closureReadiness?.closure_tasks ?? [];
  const controlledExecutionPreflight = closureReadiness?.controlled_execution_preflight;
  const controlledExecutionRoutes = controlledExecutionPreflight?.routes ?? [];
  const controlledExecutionPrerequisites =
    controlledExecutionPreflight?.prerequisites ?? [];
  const executionReleaseContract = closureReadiness?.execution_release_contract;
  const executionReleaseFields = executionReleaseContract?.fields ?? [];
  const executionReleaseNextSteps = executionReleaseContract?.next_steps ?? [];
  const ownerReleaseDraft = executionReleaseContract?.owner_release_draft;
  const ownerReleaseDraftFields = ownerReleaseDraft?.draft_fields ?? [];
  const ownerReleaseHumanFields = ownerReleaseDraft?.human_only_fields ?? [];
  const ownerReviewChecklist = automationHandoff?.owner_review_checklist ?? [];
  const forbiddenActions = automationHandoff?.forbidden_actions ?? [];
  const sourceToolchainTone: SourceFlowTone = sourceCorrelation
    ? (sourceLinkVerified ? "success" : (sourceVerificationBlocked ? "blocked" : "warning"))
    : "neutral";
  const toolchainItems = [
    {
      key: "mcp",
      Icon: RadioTower,
      tone: (mcpGatewayTotal > 0
        ? (mcpGatewayProblemTotal > 0 ? "warning" : "success")
        : "neutral") as SourceFlowTone,
      label: t("toolchain.mcp"),
      value: t("toolchain.mcpValue", {
        success: mcpGateway.success ?? 0,
        total: mcpGatewayTotal,
        failed: mcpGateway.failed ?? 0,
        blocked: mcpGateway.blocked ?? 0,
      }),
      detail: t("toolchain.mcpDetail", {
        topTool: topTool?.tool_name ?? emptyLabel,
        firstClass: mcpGateway.first_class_total ?? 0,
        legacy: legacyMcp.total ?? 0,
        policy: mcpGateway.policy_enforced_total ?? 0,
      }),
    },
    {
      key: "source",
      Icon: Link2,
      tone: sourceToolchainTone,
      label: t("toolchain.source"),
      value: t("toolchain.sourceValue", {
        status: sourceStatusLabel,
        direct: directRefTotal,
        candidate: candidateTotal,
        applied: appliedLinkTotal,
      }),
      detail: t("toolchain.sourceDetail", {
        providers: sourceProviderSummary || emptyLabel,
        reason: sourceReasonLabel,
      }),
    },
    {
      key: "execution",
      Icon: Activity,
      tone: (executionTotal > 0
        ? (String(execution.latest_status ?? "").toLowerCase().includes("fail") ? "blocked" : "success")
        : "neutral") as SourceFlowTone,
      label: t("toolchain.execution"),
      value: t("toolchain.executionValue", {
        executor: execution.latest_executor ?? emptyLabel,
        status: execution.latest_status ?? emptyLabel,
      }),
      detail: t("toolchain.executionDetail", {
        operation: execution.latest_operation_type ?? emptyLabel,
        action: execution.latest_action ?? emptyLabel,
        ops: executionTotal,
      }),
    },
    {
      key: "playbook",
      Icon: Wrench,
      tone: (ansible.considered || (ansible.candidate_count ?? 0) > 0
        ? (ansible.applied || (ansible.apply_total ?? 0) > 0 ? "success" : "warning")
        : "neutral") as SourceFlowTone,
      label: t("toolchain.playbook"),
      value: selectedPlaybook,
      detail: t("toolchain.playbookDetail", {
        ansible: boolValue(ansible.considered, emptyLabel),
        candidates: ansible.candidate_count ?? 0,
        check: ansible.check_mode_total ?? 0,
        apply: ansible.apply_total ?? 0,
        mode: valueOrEmpty(ansible.latest_execution_mode, emptyLabel),
        rc: valueOrEmpty(ansible.latest_returncode, emptyLabel),
        approval: valueOrEmpty(ansible.approval_source, emptyLabel),
        catalog: valueOrEmpty(ansible.latest_catalog_id, emptyLabel),
        checkMode: valueOrEmpty(ansible.latest_check_mode, emptyLabel),
        status: ansible.latest_status ?? emptyLabel,
      }),
    },
    {
      key: "learning",
      Icon: BookOpenCheck,
      tone: ((evidence.knowledge_entries ?? 0) > 0
        ? ((evidence.auto_repair_records ?? 0) > 0 ? "success" : "warning")
        : "neutral") as SourceFlowTone,
      label: t("toolchain.learning"),
      value: t("toolchain.learningValue", {
        km: evidence.knowledge_entries ?? 0,
        autoRepair: evidence.auto_repair_records ?? 0,
        ops: evidence.operation_records ?? 0,
      }),
      detail: t("toolchain.learningDetail", {
        verification: valueOrEmpty(chain.verification, emptyLabel),
        nextStep: nextActionLabel(chain.next_step),
      }),
    },
  ];
  const handoffGates = automationHandoff?.gates ?? [];
  const handoffCandidateCards = [
    { key: "catalog", label: t("applyGate.catalog"), value: handoffCandidate?.catalog_id },
    { key: "risk", label: t("applyGate.risk"), value: handoffCandidate?.risk_level },
    { key: "matchScore", label: t("applyGate.matchScore"), value: handoffCandidate?.match_score },
    { key: "checkPlaybook", label: t("applyGate.checkPlaybook"), value: handoffCandidate?.check_mode_playbook_path },
    { key: "applyPlaybook", label: t("applyGate.applyPlaybook"), value: handoffCandidate?.apply_playbook_path },
  ];
  const handoffAssetCards = [
    { key: "dryRunAsset", label: t("applyGate.dryRunAsset"), value: handoffAssets?.dry_run },
    { key: "applyAsset", label: t("applyGate.applyAsset"), value: handoffAssets?.apply_candidate },
    { key: "verifierAsset", label: t("applyGate.verifierAsset"), value: handoffAssets?.verifier },
  ];
  const closureGateLabel = (key: string | null | undefined) => {
    const labels: Record<string, string> = {
      mcp_evidence: t("applyGate.closureGates.mcpEvidence"),
      dry_run: t("applyGate.closureGates.dryRun"),
      apply_candidate: t("applyGate.closureGates.applyCandidate"),
      owner_release: t("applyGate.closureGates.ownerRelease"),
      controlled_execution: t("applyGate.closureGates.controlledExecution"),
      post_apply_verifier: t("applyGate.closureGates.postApplyVerifier"),
      km_writeback: t("applyGate.closureGates.kmWriteback"),
      playbook_trust: t("applyGate.closureGates.playbookTrust"),
    };
    return labels[String(key ?? "")] ?? valueOrEmpty(key, emptyLabel);
  };
  const closureAssetLabel = (key: string | null | undefined) => {
    const labels: Record<string, string> = {
      owner_execution_rehearsal: t("applyGate.closureAssets.ownerExecutionRehearsal"),
      final_candidate_readback: t("applyGate.closureAssets.finalCandidateReadback"),
      release_verifier_preflight: t("applyGate.closureAssets.releaseVerifierPreflight"),
    };
    return labels[String(key ?? "")] ?? valueOrEmpty(key, emptyLabel);
  };
  const closureStatusLabel = (status: string | null | undefined) => {
    const labels: Record<string, string> = {
      blocked_before_owner_release: t("applyGate.closureStatuses.blockedBeforeOwnerRelease"),
      no_write_rehearsal: t("applyGate.closureStatuses.noWriteRehearsal"),
      read_only: t("applyGate.closureStatuses.readOnly"),
      owner_review_required: t("applyGate.closureStatuses.ownerReviewRequired"),
      preflight_review_required: t("applyGate.closureStatuses.preflightReviewRequired"),
      ready_for_owner_review: t("applyGate.closureStatuses.readyForOwnerReview"),
      approval_required: t("applyGate.closureStatuses.approvalRequired"),
      blocked_by_policy: t("applyGate.closureStatuses.blockedByPolicy"),
      blocked_before_runtime_gate: t("applyGate.closureStatuses.blockedBeforeRuntimeGate"),
      blocked_until_verifier_passes: t("applyGate.closureStatuses.blockedUntilVerifierPasses"),
      snapshot_unavailable: t("applyGate.closureStatuses.snapshotUnavailable"),
      candidate_ready_no_runtime_authority: t("applyGate.closureStatuses.candidateReadyNoRuntimeAuthority"),
      route_missing: t("applyGate.closureStatuses.routeMissing"),
      blocked_missing_dry_run: t("applyGate.closureStatuses.blockedMissingDryRun"),
      blocked_missing_owner_release: t("applyGate.closureStatuses.blockedMissingOwnerRelease"),
      blocked_missing_maintenance_window: t("applyGate.closureStatuses.blockedMissingMaintenanceWindow"),
      blocked_missing_rollback_owner: t("applyGate.closureStatuses.blockedMissingRollbackOwner"),
      blocked_missing_post_apply_verifier: t("applyGate.closureStatuses.blockedMissingPostApplyVerifier"),
      blocked_until_verified_execution: t("applyGate.closureStatuses.blockedUntilVerifiedExecution"),
      draft_prefilled_needs_owner_release: t("applyGate.closureStatuses.draftPrefilledNeedsOwnerRelease"),
      ai_prefilled_needs_owner_decision: t("applyGate.closureStatuses.aiPrefilledNeedsOwnerDecision"),
      ai_suggested_owner_review_required: t("applyGate.closureStatuses.aiSuggestedOwnerReviewRequired"),
      ai_prefilled_owner_review_required: t("applyGate.closureStatuses.aiPrefilledOwnerReviewRequired"),
      ai_prefilled_after_verified_execution: t("applyGate.closureStatuses.aiPrefilledAfterVerifiedExecution"),
      prefilled: t("applyGate.closureStatuses.prefilled"),
      blocked_missing_mcp_evidence: t("applyGate.closureStatuses.blockedMissingMcpEvidence"),
      blocked_missing_blast_radius: t("applyGate.closureStatuses.blockedMissingBlastRadius"),
    };
    return labels[String(status ?? "")] ?? handoffStatusLabel(status);
  };
  const closureTaskLabel = (key: string | null | undefined) => {
    const labels: Record<string, string> = {
      owner_release_packet_review: t("applyGate.closureTasks.ownerReleasePacketReview"),
      maintenance_window_rollback_owner: t("applyGate.closureTasks.maintenanceRollbackOwner"),
      controlled_execution_authorization: t("applyGate.closureTasks.controlledExecutionAuthorization"),
      post_apply_verifier_preflight: t("applyGate.closureTasks.postApplyVerifierPreflight"),
      km_playbook_trust_writeback_plan: t("applyGate.closureTasks.kmPlaybookTrustWritebackPlan"),
    };
    return labels[String(key ?? "")] ?? valueOrEmpty(key, emptyLabel);
  };
  const executionReleaseFieldLabel = (key: string | null | undefined) => {
    const labels: Record<string, string> = {
      incident_ref: t("applyGate.releaseFields.incidentRef"),
      route_id: t("applyGate.releaseFields.routeId"),
      dry_run_evidence: t("applyGate.releaseFields.dryRunEvidence"),
      mcp_evidence_refs: t("applyGate.releaseFields.mcpEvidenceRefs"),
      owner_approval_receipt: t("applyGate.releaseFields.ownerApprovalReceipt"),
      maintenance_window: t("applyGate.releaseFields.maintenanceWindow"),
      rollback_owner: t("applyGate.releaseFields.rollbackOwner"),
      blast_radius: t("applyGate.releaseFields.blastRadius"),
      post_apply_verifier: t("applyGate.releaseFields.postApplyVerifier"),
      km_writeback_owner: t("applyGate.releaseFields.kmWritebackOwner"),
      playbook_trust_owner: t("applyGate.releaseFields.playbookTrustOwner"),
    };
    return labels[String(key ?? "")] ?? valueOrEmpty(key, emptyLabel);
  };
  const executionReleaseStepLabel = (key: string | null | undefined) => {
    const labels: Record<string, string> = {
      owner_release: t("applyGate.releaseSteps.ownerRelease"),
      maintenance_rollback: t("applyGate.releaseSteps.maintenanceRollback"),
      verifier_release: t("applyGate.releaseSteps.verifierRelease"),
      learning_writeback: t("applyGate.releaseSteps.learningWriteback"),
    };
    return labels[String(key ?? "")] ?? valueOrEmpty(key, emptyLabel);
  };
  const controlledExecutionPrerequisiteLabel = (key: string | null | undefined) => {
    const labels: Record<string, string> = {
      dry_run_passed: t("applyGate.controlledPrerequisites.dryRunPassed"),
      allowlisted_route_candidate: t("applyGate.controlledPrerequisites.allowlistedRouteCandidate"),
      owner_release_receipt: t("applyGate.controlledPrerequisites.ownerReleaseReceipt"),
      maintenance_window: t("applyGate.controlledPrerequisites.maintenanceWindow"),
      rollback_owner: t("applyGate.controlledPrerequisites.rollbackOwner"),
      post_apply_verifier: t("applyGate.controlledPrerequisites.postApplyVerifier"),
      km_playbook_writeback: t("applyGate.controlledPrerequisites.kmPlaybookWriteback"),
    };
    return labels[String(key ?? "")] ?? valueOrEmpty(key, emptyLabel);
  };
  const handoffWorkItemHref = automationHandoff?.work_item_id
    ? `/awooop/work-items?project_id=awoooi&work_item_id=${encodeURIComponent(automationHandoff.work_item_id)}${automationHandoff.source_id ? `&incident_id=${encodeURIComponent(automationHandoff.source_id)}` : ""}`
    : null;
  const handoffGateLabel = (key: string | null | undefined) => {
    const labels: Record<string, string> = {
      dry_run: t("applyGate.gates.dryRun"),
      apply_gate: t("applyGate.gates.applyGate"),
      verifier: t("applyGate.gates.verifier"),
    };
    return labels[String(key ?? "")] ?? valueOrEmpty(key, emptyLabel);
  };
  const handoffStatusLabel = (status: string | null | undefined) => {
    const labels: Record<string, string> = {
      passed: t("applyGate.statuses.passed"),
      blocked: t("applyGate.statuses.blocked"),
      warning: t("applyGate.statuses.warning"),
      pending: t("applyGate.statuses.pending"),
    };
    return labels[String(status ?? "")] ?? valueOrEmpty(status, emptyLabel);
  };
  const handoffTone = (status: string | null | undefined): SourceFlowTone => {
    const normalized = String(status ?? "");
    if (normalized === "passed") return "success";
    if (normalized === "warning" || normalized.includes("candidate_ready")) return "warning";
    if (normalized === "blocked" || normalized.startsWith("blocked") || normalized === "route_missing") return "blocked";
    return "neutral";
  };
  const drilldownItems = [
    {
      key: "signal",
      Icon: Link2,
      tone: (sourceCorrelation ? (providerIngressReady ? "success" : "warning") : "neutral") as SourceFlowTone,
      title: t("drilldown.signal"),
      value: valueOrEmpty(chain.source_id ?? chain.incident_ids?.[0], emptyLabel),
      detail: t("drilldown.signalDetail", {
        inbound: chain.source_refs?.inbound_total ?? 0,
        outbound: chain.source_refs?.outbound_total ?? 0,
        status: sourceStatusLabel,
        reason: sourceReasonLabel,
      }),
    },
    {
      key: "investigation",
      Icon: RadioTower,
      tone: (mcpGatewayTotal > 0
        ? (mcpGatewayProblemTotal > 0 ? "warning" : "success")
        : "neutral") as SourceFlowTone,
      title: t("drilldown.investigation"),
      value: t("drilldown.investigationValue", {
        success: mcpGateway.success ?? 0,
        total: mcpGatewayTotal,
      }),
      detail: t("drilldown.investigationDetail", {
        tools: topToolNames,
        failed: mcpGateway.failed ?? 0,
        blocked: mcpGateway.blocked ?? 0,
      }),
    },
    {
      key: "playbook",
      Icon: Wrench,
      tone: (ansible.considered || (ansible.candidate_count ?? 0) > 0
        ? (ansible.applied || (ansible.apply_total ?? 0) > 0 ? "success" : "warning")
        : "neutral") as SourceFlowTone,
      title: t("drilldown.playbook"),
      value: selectedPlaybook,
      detail: t("drilldown.playbookDetail", {
        candidates: ansible.candidate_count ?? 0,
        check: ansible.check_mode_total ?? 0,
        apply: ansible.apply_total ?? 0,
        approval: valueOrEmpty(ansible.approval_source, emptyLabel),
      }),
    },
    {
      key: "execution",
      Icon: Activity,
      tone: (executionTotal > 0
        ? (String(execution.latest_status ?? "").toLowerCase().includes("fail") ? "blocked" : "success")
        : "neutral") as SourceFlowTone,
      title: t("drilldown.execution"),
      value: t("drilldown.executionValue", {
        executor: execution.latest_executor ?? emptyLabel,
        status: execution.latest_status ?? emptyLabel,
      }),
      detail: t("drilldown.executionDetail", {
        operation: execution.latest_operation_type ?? emptyLabel,
        rc: valueOrEmpty(ansible.latest_returncode, emptyLabel),
        mode: valueOrEmpty(ansible.latest_execution_mode, emptyLabel),
      }),
    },
    {
      key: "learning",
      Icon: BookOpenCheck,
      tone: ((evidence.knowledge_entries ?? 0) > 0 ? "success" : "neutral") as SourceFlowTone,
      title: t("drilldown.learning"),
      value: t("drilldown.learningValue", {
        km: evidence.knowledge_entries ?? 0,
        autoRepair: evidence.auto_repair_records ?? 0,
      }),
      detail: t("drilldown.learningDetail", {
        verification: valueOrEmpty(chain.verification, emptyLabel),
        nextStep: nextActionLabel(chain.next_step),
      }),
    },
    {
      key: "handoff",
      Icon: chain.needs_human ? ShieldCheck : CheckCircle2,
      tone: (chain.needs_human ? "warning" : "success") as SourceFlowTone,
      title: t("drilldown.handoff"),
      value: chain.needs_human ? t("human.yes") : t("human.no"),
      detail: t("drilldown.handoffDetail", {
        reason: valueOrEmpty(outcome?.human_action_reason, emptyLabel),
        nextAction: nextActionLabel(outcome?.next_action ?? chain.next_step),
      }),
    },
  ];

  return (
    <section className={cn("border border-[#e0ddd4] bg-white", className)}>
      <div className={cn(
        "flex flex-wrap items-start justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3]",
        compact ? "px-3 py-3" : "px-4 py-3"
      )}>
        <div className="flex min-w-0 items-start gap-3">
          <span className={cn("flex h-9 w-9 shrink-0 items-center justify-center border", tone)}>
            <Icon className="h-4 w-4" aria-hidden="true" />
          </span>
          <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", {
                source: valueOrEmpty(chain.source, emptyLabel),
                sourceId: valueOrEmpty(chain.source_id, emptyLabel),
              })}
            </p>
          </div>
        </div>
        <span className={cn("shrink-0 border px-2 py-0.5 text-xs font-semibold", tone)}>
          {chain.needs_human ? t("human.yes") : t("human.no")}
        </span>
      </div>

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

      {outcome && (
        <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-5">
          <div className="min-w-0 bg-white px-4 py-3 md:col-span-2">
            <p className="text-xs font-semibold text-[#77736a]">{t("outcome.summary")}</p>
            <p className="mt-2 truncate text-sm font-semibold text-[#141413]" title={valueOrEmpty(outcome.summary_zh, emptyLabel)}>
              {valueOrEmpty(outcome.summary_zh, emptyLabel)}
            </p>
          </div>
          <div className="min-w-0 bg-white px-4 py-3">
            <p className="text-xs font-semibold text-[#77736a]">{t("outcome.execution")}</p>
            <p
              className="mt-2 truncate font-mono text-sm text-[#141413]"
              title={valueOrEmpty(outcomeExecution?.summary_zh, emptyLabel)}
            >
              {valueOrEmpty(outcomeExecution?.completion_status, emptyLabel)}
            </p>
            <p className="mt-1 truncate font-mono text-xs text-[#77736a]">
              {valueOrEmpty(outcomeExecution?.command_status, emptyLabel)}
              {" / "}
              {valueOrEmpty(outcomeExecution?.repair_status, emptyLabel)}
            </p>
          </div>
          <div className="min-w-0 bg-white px-4 py-3">
            <p className="text-xs font-semibold text-[#77736a]">{t("outcome.notification")}</p>
            <p className="mt-2 truncate font-mono text-sm text-[#141413]" title={(outcome.notification?.channels ?? []).join(", ") || emptyLabel}>
              {(outcome.notification?.channels ?? []).join(", ") || emptyLabel}
            </p>
          </div>
          <div className="min-w-0 bg-white px-4 py-3">
            <p className="text-xs font-semibold text-[#77736a]">{t("outcome.reason")}</p>
            <p className="mt-2 truncate font-mono text-sm text-[#141413]" title={valueOrEmpty(outcome.human_action_reason, emptyLabel)}>
              {valueOrEmpty(outcome.human_action_reason, emptyLabel)}
            </p>
          </div>
        </div>
      )}

      {!compact && (
        <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-5">
          {evidenceMetrics.map((item) => (
            <div key={item.label} className="bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{item.label}</p>
              <p className="mt-2 font-mono text-xl font-semibold text-[#141413]">{item.value}</p>
            </div>
          ))}
          <div className="min-w-0 bg-white px-4 py-3">
            <p className="text-xs font-semibold text-[#77736a]">{t("evidence.adr100")}</p>
            <p className="mt-2 truncate font-mono text-sm text-[#141413]" title={valueOrEmpty(evidence.latest_route, emptyLabel)}>
              {valueOrEmpty(evidence.latest_route, emptyLabel)}
            </p>
          </div>
        </div>
      )}

      <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-2">
        <div className="min-w-0 bg-white px-4 py-3">
          <p className="text-xs font-semibold text-[#77736a]">{t("fields.writes")}</p>
          <p className="mt-2 font-mono text-sm text-[#141413]">
            {t("writeFlags", {
              incident: boolValue(chain.writes?.incident, emptyLabel),
              autoRepair: boolValue(chain.writes?.auto_repair, emptyLabel),
            })}
          </p>
        </div>
        <div className="min-w-0 bg-white px-4 py-3">
          <p className="text-xs font-semibold text-[#77736a]">{t("fields.verdict")}</p>
          <p className="mt-2 truncate font-mono text-sm text-[#141413]" title={valueOrEmpty(chain.verdict, emptyLabel)}>
            {valueOrEmpty(chain.verdict, emptyLabel)}
          </p>
        </div>
      </div>

      {automationHandoff && (
        <div>
          <div className="border-t border-[#e0ddd4] bg-[#faf9f3] px-4 py-2">
            <div className="flex flex-wrap items-center justify-between gap-2">
              <p className="text-xs font-semibold text-[#141413]">{t("applyGate.title")}</p>
              <span className="border border-[#e2a29b] bg-[#fff0ef] px-2 py-0.5 font-mono text-[11px] font-semibold text-[#9f2f25]">
                {t("applyGate.runtime", {
                  value: boolValue(automationHandoff.runtime_execution_authorized, emptyLabel),
                })}
              </span>
            </div>
          </div>
          <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-3">
            {handoffGates.map((gate) => (
              <div key={`${gate.key}-${gate.status}`} className="min-w-0 bg-white px-4 py-3">
                <div className="flex min-w-0 items-start gap-3">
                  <span className={cn(
                    "flex h-8 w-8 shrink-0 items-center justify-center border",
                    sourceFlowToneClass(handoffTone(gate.status))
                  )}>
                    <ShieldAlert className="h-4 w-4" aria-hidden="true" />
                  </span>
                  <div className="min-w-0">
                    <p className="text-xs font-semibold text-[#77736a]">{handoffGateLabel(gate.key)}</p>
                    <p className="mt-1 truncate font-mono text-sm font-semibold text-[#141413]" title={handoffStatusLabel(gate.status)}>
                      {handoffStatusLabel(gate.status)}
                    </p>
                  </div>
                </div>
                <p className="mt-2 truncate font-mono text-xs text-[#5f5b52]" title={valueOrEmpty(gate.detail, emptyLabel)}>
                  {valueOrEmpty(gate.detail, emptyLabel)}
                </p>
              </div>
            ))}
          </div>
          {closureReadiness && (
            <div>
              <div className="border-t border-[#e0ddd4] bg-[#f5f8f2] px-4 py-2">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <div className="min-w-0">
                    <p className="text-xs font-semibold text-[#141413]">{t("applyGate.closureTitle")}</p>
                    <p className="mt-1 truncate text-xs text-[#5f5b52]" title={valueOrEmpty(closureReadiness.blocked_reason, emptyLabel)}>
                      {t("applyGate.closureBlockedReason", {
                        reason: valueOrEmpty(closureReadiness.blocked_reason, emptyLabel),
                      })}
                    </p>
                  </div>
                  <div className="flex flex-wrap items-center gap-2">
                    <span className="border border-[#9fcbab] bg-[#f1fbf2] px-2 py-0.5 font-mono text-[11px] font-semibold text-[#17602a]">
                      {t("applyGate.closureProgress", {
                        ready: closureReadiness.ready_count ?? 0,
                        total: closureReadiness.total_count ?? closureGates.length,
                        percent: closureReadiness.completion_percent ?? 0,
                      })}
                    </span>
                    <span className="border border-[#e2a29b] bg-[#fff0ef] px-2 py-0.5 font-mono text-[11px] font-semibold text-[#9f2f25]">
                      {closureStatusLabel(closureReadiness.status)}
                    </span>
                  </div>
                </div>
              </div>
              <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-4">
                {closureGates.map((gate) => (
                  <div key={`${gate.key}-${gate.status}`} className="min-w-0 bg-white px-4 py-3">
                    <div className="flex min-w-0 items-start gap-3">
                      <span className={cn(
                        "flex h-8 w-8 shrink-0 items-center justify-center border",
                        sourceFlowToneClass(handoffTone(gate.status))
                      )}>
                        <CheckCircle2 className="h-4 w-4" aria-hidden="true" />
                      </span>
                      <div className="min-w-0">
                        <p className="text-xs font-semibold text-[#77736a]">{closureGateLabel(gate.key)}</p>
                        <p className="mt-1 truncate font-mono text-sm font-semibold text-[#141413]" title={closureStatusLabel(gate.status)}>
                          {closureStatusLabel(gate.status)}
                        </p>
                      </div>
                    </div>
                    <p className="mt-2 truncate font-mono text-xs text-[#5f5b52]" title={valueOrEmpty(gate.detail, emptyLabel)}>
                      {valueOrEmpty(gate.detail, emptyLabel)}
                    </p>
                    <p className="mt-1 truncate font-mono text-[11px] text-[#77736a]" title={valueOrEmpty(gate.asset_id, emptyLabel)}>
                      {valueOrEmpty(gate.asset_id, emptyLabel)}
                    </p>
                  </div>
                ))}
              </div>
              <div className="grid gap-px bg-[#e0ddd4] lg:grid-cols-2">
                <div className="min-w-0 bg-white px-4 py-3">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="text-xs font-semibold text-[#77736a]">{t("applyGate.ownerReleasePackageTitle")}</p>
                      <p className="mt-1 truncate font-mono text-sm font-semibold text-[#141413]" title={valueOrEmpty(closureOwnerPackage?.runtime_authority, emptyLabel)}>
                        {valueOrEmpty(closureOwnerPackage?.source_task_id, emptyLabel)}
                      </p>
                    </div>
                    <span className="shrink-0 border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5 font-mono text-[11px] text-[#5f5b52]">
                      {closureStatusLabel(closureOwnerPackage?.status)}
                    </span>
                  </div>
                  <div className="mt-3 grid gap-2 sm:grid-cols-3">
                    <span className="border border-[#ece8dd] bg-[#faf9f3] px-2 py-1 font-mono text-[11px] text-[#141413]">
                      {t("applyGate.ownerReleasePacketValue", {
                        packets: closureOwnerPackage?.packet_count ?? 0,
                        approved: closureOwnerPackage?.owner_release_approved_count ?? 0,
                      })}
                    </span>
                    <span className="border border-[#ece8dd] bg-[#faf9f3] px-2 py-1 font-mono text-[11px] text-[#141413]">
                      {t("applyGate.maintenanceRollbackValue", {
                        maintenance: closureOwnerPackage?.maintenance_window_approved_count ?? 0,
                        rollback: closureOwnerPackage?.rollback_owner_confirmed_count ?? 0,
                      })}
                    </span>
                    <span className="border border-[#ece8dd] bg-[#faf9f3] px-2 py-1 font-mono text-[11px] text-[#141413]">
                      {t("applyGate.operatorActionValue", {
                        actions: closureOwnerPackage?.operator_action_count ?? 0,
                      })}
                    </span>
                  </div>
                </div>
                <div className="min-w-0 bg-white px-4 py-3">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="text-xs font-semibold text-[#77736a]">{t("applyGate.releaseVerifierPackageTitle")}</p>
                      <p className="mt-1 truncate font-mono text-sm font-semibold text-[#141413]" title={valueOrEmpty(closureVerifierPackage?.runtime_authority, emptyLabel)}>
                        {valueOrEmpty(closureVerifierPackage?.source_task_id, emptyLabel)}
                      </p>
                    </div>
                    <span className="shrink-0 border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5 font-mono text-[11px] text-[#5f5b52]">
                      {closureStatusLabel(closureVerifierPackage?.status)}
                    </span>
                  </div>
                  <div className="mt-3 grid gap-2 sm:grid-cols-3">
                    <span className="border border-[#ece8dd] bg-[#faf9f3] px-2 py-1 font-mono text-[11px] text-[#141413]">
                      {t("applyGate.verifierPackageValue", {
                        verifier: closureVerifierPackage?.verifier_count ?? 0,
                        ready: closureVerifierPackage?.post_release_verifier_ready_count ?? 0,
                      })}
                    </span>
                    <span className="border border-[#ece8dd] bg-[#faf9f3] px-2 py-1 font-mono text-[11px] text-[#141413]">
                      {t("applyGate.liveApplyHoldValue", {
                        holds: closureVerifierPackage?.live_apply_hold_count ?? 0,
                        passed: closureVerifierPackage?.live_apply_release_pass_count ?? 0,
                      })}
                    </span>
                    <span className="border border-[#ece8dd] bg-[#faf9f3] px-2 py-1 font-mono text-[11px] text-[#141413]">
                      {t("applyGate.ownerAuthorizedValue", {
                        authorized: closureVerifierPackage?.owner_release_authorized_count ?? 0,
                      })}
                    </span>
                  </div>
                </div>
              </div>
              <div className="border-t border-[#e0ddd4] bg-[#fbfaf5] px-4 py-2">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <p className="text-xs font-semibold text-[#141413]">{t("applyGate.closureTaskBoardTitle")}</p>
                  <span className="border border-[#d8d3c7] bg-white px-2 py-0.5 font-mono text-[11px] text-[#5f5b52]">
                    {closureTasks.length}
                  </span>
                </div>
              </div>
              <div className="grid gap-px bg-[#e0ddd4] lg:grid-cols-5">
                {(closureTasks.length ? closureTasks : [{ key: emptyLabel, status: emptyLabel, owner_agent: emptyLabel, summary: emptyLabel, source_asset_id: emptyLabel, next_step: emptyLabel, runtime_write_allowed: false }]).map((task, index) => (
                  <div key={`${task.key}-${index}`} className="min-w-0 bg-white px-4 py-3">
                    <div className="flex min-w-0 items-start gap-3">
                      <span className={cn(
                        "flex h-8 w-8 shrink-0 items-center justify-center border",
                        sourceFlowToneClass(handoffTone(task.status))
                      )}>
                        <Route className="h-4 w-4" aria-hidden="true" />
                      </span>
                      <div className="min-w-0">
                        <p className="text-xs font-semibold text-[#77736a]">{closureTaskLabel(task.key)}</p>
                        <p className="mt-1 truncate font-mono text-sm font-semibold text-[#141413]" title={closureStatusLabel(task.status)}>
                          {closureStatusLabel(task.status)}
                        </p>
                      </div>
                    </div>
                    <p className="mt-2 truncate font-mono text-xs text-[#5f5b52]" title={valueOrEmpty(task.owner_agent, emptyLabel)}>
                      {t("applyGate.closureTaskOwner", { owner: valueOrEmpty(task.owner_agent, emptyLabel) })}
                    </p>
                    <p className="mt-1 truncate font-mono text-xs text-[#141413]" title={valueOrEmpty(task.summary, emptyLabel)}>
                      {valueOrEmpty(task.summary, emptyLabel)}
                    </p>
                    <p className="mt-1 break-all font-mono text-[11px] text-[#77736a]" title={valueOrEmpty(task.source_asset_id, emptyLabel)}>
                      {valueOrEmpty(task.source_asset_id, emptyLabel)}
                    </p>
                    <p className="mt-2 text-[11px] leading-4 text-[#5f5b52]" title={valueOrEmpty(task.next_step, emptyLabel)}>
                      {nextActionLabel(task.next_step)}
                    </p>
                    <span className="mt-2 inline-flex border border-[#e2a29b] bg-[#fff0ef] px-2 py-0.5 font-mono text-[11px] text-[#9f2f25]">
                      {t("applyGate.runtimeWrite", {
                        value: boolValue(task.runtime_write_allowed, emptyLabel),
                      })}
                    </span>
                  </div>
                ))}
              </div>
              {controlledExecutionPreflight ? (
                <>
                  <div className="border-t border-[#e0ddd4] bg-[#fbfaf5] px-4 py-2">
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <div className="min-w-0">
                        <p className="text-xs font-semibold text-[#141413]">{t("applyGate.controlledExecutionPreflightTitle")}</p>
                        <p className="mt-1 truncate font-mono text-[11px] text-[#77736a]" title={valueOrEmpty(controlledExecutionPreflight.blocked_reason, emptyLabel)}>
                          {valueOrEmpty(controlledExecutionPreflight.blocked_reason, emptyLabel)}
                        </p>
                      </div>
                      <span className="border border-[#e2a29b] bg-[#fff0ef] px-2 py-0.5 font-mono text-[11px] font-semibold text-[#9f2f25]">
                        {closureStatusLabel(controlledExecutionPreflight.status)}
                      </span>
                    </div>
                  </div>
                  <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-4">
                    {[
                      {
                        key: "candidate",
                        label: t("applyGate.controlledCandidateRoutes"),
                        value: controlledExecutionPreflight.candidate_route_count ?? 0,
                      },
                      {
                        key: "allowed",
                        label: t("applyGate.controlledAllowedRoutes"),
                        value: controlledExecutionPreflight.allowed_route_count ?? 0,
                      },
                      {
                        key: "blocked",
                        label: t("applyGate.controlledBlockedCount"),
                        value: controlledExecutionPreflight.blocked_count ?? 0,
                      },
                      {
                        key: "runtime",
                        label: t("applyGate.runtimeWrite", {
                          value: boolValue(controlledExecutionPreflight.runtime_write_allowed, emptyLabel),
                        }),
                        value: boolValue(controlledExecutionPreflight.runtime_execution_authorized, emptyLabel),
                      },
                    ].map((item) => (
                      <div key={item.key} className="min-w-0 bg-white px-4 py-3">
                        <p className="text-xs font-semibold text-[#77736a]">{item.label}</p>
                        <p className="mt-1 truncate font-mono text-lg font-semibold text-[#141413]" title={String(item.value)}>
                          {item.value}
                        </p>
                      </div>
                    ))}
                  </div>
                  <div className="grid gap-px bg-[#e0ddd4] lg:grid-cols-7">
                    {(controlledExecutionPrerequisites.length ? controlledExecutionPrerequisites : [{ key: emptyLabel, status: emptyLabel, detail: emptyLabel, required: true }]).map((item, index) => (
                      <div key={`${item.key}-${index}`} className="min-w-0 bg-white px-4 py-3">
                        <div className="flex min-w-0 items-start gap-3">
                          <span className={cn(
                            "flex h-8 w-8 shrink-0 items-center justify-center border",
                            sourceFlowToneClass(handoffTone(item.status))
                          )}>
                            <ShieldCheck className="h-4 w-4" aria-hidden="true" />
                          </span>
                          <div className="min-w-0">
                            <p className="text-xs font-semibold text-[#77736a]">{controlledExecutionPrerequisiteLabel(item.key)}</p>
                            <p className="mt-1 truncate font-mono text-sm font-semibold text-[#141413]" title={closureStatusLabel(item.status)}>
                              {closureStatusLabel(item.status)}
                            </p>
                          </div>
                        </div>
                        <p className="mt-2 truncate font-mono text-xs text-[#5f5b52]" title={valueOrEmpty(item.detail, emptyLabel)}>
                          {valueOrEmpty(item.detail, emptyLabel)}
                        </p>
                      </div>
                    ))}
                  </div>
                  <div className="grid gap-px bg-[#e0ddd4]">
                    {(controlledExecutionRoutes.length ? controlledExecutionRoutes : [{ route_id: emptyLabel, transport: emptyLabel, status: emptyLabel, source_asset_id: emptyLabel, check_mode_playbook_path: emptyLabel, apply_playbook_path: emptyLabel, allowed: false, blocker: emptyLabel }]).map((route, index) => (
                      <div key={`${route.route_id}-${index}`} className="min-w-0 bg-white px-4 py-3">
                        <div className="flex flex-wrap items-start justify-between gap-3">
                          <div className="min-w-0">
                            <p className="text-xs font-semibold text-[#77736a]">{t("applyGate.controlledRouteTitle")}</p>
                            <p className="mt-1 break-all font-mono text-sm font-semibold text-[#141413]" title={valueOrEmpty(route.route_id, emptyLabel)}>
                              {valueOrEmpty(route.route_id, emptyLabel)}
                            </p>
                          </div>
                          <span className="shrink-0 border border-[#e2a29b] bg-[#fff0ef] px-2 py-0.5 font-mono text-[11px] text-[#9f2f25]">
                            {t("applyGate.controlledAllowed", {
                              value: boolValue(route.allowed, emptyLabel),
                            })}
                          </span>
                        </div>
                        <div className="mt-3 grid gap-2 lg:grid-cols-3">
                          <span className="min-w-0 border border-[#ece8dd] bg-[#faf9f3] px-2 py-1 font-mono text-[11px] text-[#141413]">
                            {valueOrEmpty(route.transport, emptyLabel)} · {closureStatusLabel(route.status)}
                          </span>
                          <span className="min-w-0 break-all border border-[#ece8dd] bg-[#faf9f3] px-2 py-1 font-mono text-[11px] text-[#141413]">
                            {valueOrEmpty(route.apply_playbook_path, emptyLabel)}
                          </span>
                          <span className="min-w-0 break-all border border-[#ece8dd] bg-[#faf9f3] px-2 py-1 font-mono text-[11px] text-[#141413]">
                            {valueOrEmpty(route.blocker, emptyLabel)}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                </>
              ) : null}
              {executionReleaseContract ? (
                <>
                  <div className="border-t border-[#e0ddd4] bg-[#fbfaf5] px-4 py-2">
                    <div className="flex flex-wrap items-start justify-between gap-2">
                      <div className="min-w-0">
                        <p className="text-xs font-semibold text-[#141413]">{t("applyGate.executionReleaseContractTitle")}</p>
                        <p className="mt-1 break-all font-mono text-[11px] text-[#77736a]" title={valueOrEmpty(executionReleaseContract.route_id, emptyLabel)}>
                          {valueOrEmpty(executionReleaseContract.route_id, emptyLabel)}
                        </p>
                      </div>
                      <span className="border border-[#e2a29b] bg-[#fff0ef] px-2 py-0.5 font-mono text-[11px] font-semibold text-[#9f2f25]">
                        {closureStatusLabel(executionReleaseContract.status)}
                      </span>
                    </div>
                  </div>
                  <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-4">
                    {[
                      {
                        key: "ready",
                        label: t("applyGate.releaseContractReady"),
                        value: `${executionReleaseContract.ready_count ?? 0}/${executionReleaseContract.total_count ?? 0}`,
                      },
                      {
                        key: "blocked",
                        label: t("applyGate.releaseContractBlocked"),
                        value: executionReleaseContract.blocked_count ?? 0,
                      },
                      {
                        key: "workItem",
                        label: t("applyGate.workItem"),
                        value: valueOrEmpty(executionReleaseContract.work_item_id, emptyLabel),
                      },
                      {
                        key: "runtime",
                        label: t("applyGate.runtimeWrite", {
                          value: boolValue(executionReleaseContract.runtime_write_allowed, emptyLabel),
                        }),
                        value: boolValue(executionReleaseContract.runtime_execution_authorized, emptyLabel),
                      },
                    ].map((item) => (
                      <div key={item.key} className="min-w-0 bg-white px-4 py-3">
                        <p className="text-xs font-semibold text-[#77736a]">{item.label}</p>
                        <p className="mt-1 break-all font-mono text-sm font-semibold text-[#141413]" title={String(item.value)}>
                          {item.value}
                        </p>
                      </div>
                    ))}
                  </div>
                  {ownerReleaseDraft ? (
                    <>
                      <div className="border-t border-[#e0ddd4] bg-[#fffaf0] px-4 py-2">
                        <div className="flex flex-wrap items-start justify-between gap-2">
                          <div className="min-w-0">
                            <p className="text-xs font-semibold text-[#141413]">{t("applyGate.ownerReleaseDraftTitle")}</p>
                            <p className="mt-1 break-all font-mono text-[11px] text-[#77736a]" title={valueOrEmpty(ownerReleaseDraft.work_item_id, emptyLabel)}>
                              {valueOrEmpty(ownerReleaseDraft.work_item_id, emptyLabel)}
                            </p>
                          </div>
                          <span className="border border-[#d8d3c7] bg-white px-2 py-0.5 font-mono text-[11px] font-semibold text-[#5f5b52]">
                            {closureStatusLabel(ownerReleaseDraft.status)}
                          </span>
                        </div>
                      </div>
                      <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-4">
                        {[
                          {
                            key: "aiPrefilled",
                            label: t("applyGate.ownerReleaseDraftAiPrefilled"),
                            value: ownerReleaseDraft.ai_prefilled_count ?? ownerReleaseDraftFields.length,
                          },
                          {
                            key: "humanDecision",
                            label: t("applyGate.ownerReleaseDraftHumanDecision"),
                            value: ownerReleaseDraft.human_decision_count ?? ownerReleaseHumanFields.length,
                          },
                          {
                            key: "humanOnly",
                            label: t("applyGate.ownerReleaseDraftHumanOnly"),
                            value: ownerReleaseHumanFields.length,
                          },
                          {
                            key: "runtime",
                            label: t("applyGate.runtimeWrite", {
                              value: boolValue(ownerReleaseDraft.runtime_write_allowed, emptyLabel),
                            }),
                            value: boolValue(ownerReleaseDraft.runtime_execution_authorized, emptyLabel),
                          },
                        ].map((item) => (
                          <div key={item.key} className="min-w-0 bg-white px-4 py-3">
                            <p className="text-xs font-semibold text-[#77736a]">{item.label}</p>
                            <p className="mt-1 truncate font-mono text-lg font-semibold text-[#141413]" title={String(item.value)}>
                              {item.value}
                            </p>
                          </div>
                        ))}
                      </div>
                      <div className="grid gap-px bg-[#e0ddd4] lg:grid-cols-3">
                        {(ownerReleaseDraftFields.length ? ownerReleaseDraftFields : [{ key: emptyLabel, status: emptyLabel, value: emptyLabel, reason: emptyLabel }]).map((field, index) => (
                          <div key={`${field.key}-${index}`} className="min-w-0 bg-white px-4 py-3">
                            <div className="flex min-w-0 items-start gap-3">
                              <span className={cn(
                                "flex h-8 w-8 shrink-0 items-center justify-center border",
                                sourceFlowToneClass(handoffTone(field.status))
                              )}>
                                <ShieldCheck className="h-4 w-4" aria-hidden="true" />
                              </span>
                              <div className="min-w-0">
                                <p className="text-xs font-semibold text-[#77736a]">{executionReleaseFieldLabel(field.key)}</p>
                                <p className="mt-1 truncate font-mono text-sm font-semibold text-[#141413]" title={closureStatusLabel(field.status)}>
                                  {closureStatusLabel(field.status)}
                                </p>
                              </div>
                            </div>
                            <p className="mt-2 break-all font-mono text-[11px] text-[#141413]" title={valueOrEmpty(field.value, emptyLabel)}>
                              {valueOrEmpty(field.value, emptyLabel)}
                            </p>
                            <p className="mt-1 text-[11px] leading-4 text-[#5f5b52]" title={valueOrEmpty(field.reason, emptyLabel)}>
                              {valueOrEmpty(field.reason, emptyLabel)}
                            </p>
                          </div>
                        ))}
                      </div>
                      <div className="border-t border-[#e0ddd4] bg-white px-4 py-3">
                        <div className="flex flex-wrap items-start gap-2">
                          <span className="shrink-0 border border-[#e2a29b] bg-[#fff0ef] px-2 py-0.5 text-[11px] font-semibold text-[#9f2f25]">
                            {t("applyGate.ownerReleaseDraftStillHuman")}
                          </span>
                          <p className="min-w-0 flex-1 break-words text-xs text-[#5f5b52]">
                            {ownerReleaseHumanFields.length ? ownerReleaseHumanFields.join(" / ") : emptyLabel}
                          </p>
                        </div>
                      </div>
                    </>
                  ) : null}
                  <div className="grid gap-px bg-[#e0ddd4] lg:grid-cols-4">
                    {(executionReleaseFields.length ? executionReleaseFields : [{ key: emptyLabel, status: emptyLabel, value: emptyLabel, next_step: emptyLabel, required: true }]).map((field, index) => (
                      <div key={`${field.key}-${index}`} className="min-w-0 bg-white px-4 py-3">
                        <div className="flex min-w-0 items-start gap-3">
                          <span className={cn(
                            "flex h-8 w-8 shrink-0 items-center justify-center border",
                            sourceFlowToneClass(handoffTone(field.status))
                          )}>
                            <ShieldAlert className="h-4 w-4" aria-hidden="true" />
                          </span>
                          <div className="min-w-0">
                            <p className="text-xs font-semibold text-[#77736a]">{executionReleaseFieldLabel(field.key)}</p>
                            <p className="mt-1 truncate font-mono text-sm font-semibold text-[#141413]" title={closureStatusLabel(field.status)}>
                              {closureStatusLabel(field.status)}
                            </p>
                          </div>
                        </div>
                        <p className="mt-2 break-all font-mono text-[11px] text-[#141413]" title={valueOrEmpty(field.value, emptyLabel)}>
                          {valueOrEmpty(field.value, emptyLabel)}
                        </p>
                        <p className="mt-1 text-[11px] leading-4 text-[#5f5b52]" title={valueOrEmpty(field.next_step, emptyLabel)}>
                          {nextActionLabel(field.next_step)}
                        </p>
                      </div>
                    ))}
                  </div>
                  <div className="border-t border-[#e0ddd4] bg-[#fbfaf5] px-4 py-2">
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <p className="text-xs font-semibold text-[#141413]">{t("applyGate.releaseContractNextStepsTitle")}</p>
                      <span className="border border-[#d8d3c7] bg-white px-2 py-0.5 font-mono text-[11px] text-[#5f5b52]">
                        {executionReleaseNextSteps.length}
                      </span>
                    </div>
                  </div>
                  <div className="grid gap-px bg-[#e0ddd4] lg:grid-cols-4">
                    {(executionReleaseNextSteps.length ? executionReleaseNextSteps : [{ key: emptyLabel, owner_agent: emptyLabel, work_item_id: emptyLabel, summary: emptyLabel, runtime_write_allowed: false }]).map((step, index) => (
                      <div key={`${step.key}-${index}`} className="min-w-0 bg-white px-4 py-3">
                        <p className="text-xs font-semibold text-[#77736a]">{executionReleaseStepLabel(step.key)}</p>
                        <p className="mt-1 truncate font-mono text-sm font-semibold text-[#141413]" title={valueOrEmpty(step.owner_agent, emptyLabel)}>
                          {valueOrEmpty(step.owner_agent, emptyLabel)}
                        </p>
                        <p className="mt-2 break-all font-mono text-[11px] text-[#5f5b52]" title={valueOrEmpty(step.work_item_id, emptyLabel)}>
                          {valueOrEmpty(step.work_item_id, emptyLabel)}
                        </p>
                        <p className="mt-2 text-[11px] leading-4 text-[#5f5b52]" title={valueOrEmpty(step.summary, emptyLabel)}>
                          {valueOrEmpty(step.summary, emptyLabel)}
                        </p>
                        <span className="mt-2 inline-flex border border-[#e2a29b] bg-[#fff0ef] px-2 py-0.5 font-mono text-[11px] text-[#9f2f25]">
                          {t("applyGate.runtimeWrite", {
                            value: boolValue(step.runtime_write_allowed, emptyLabel),
                          })}
                        </span>
                      </div>
                    ))}
                  </div>
                </>
              ) : null}
              <div className="grid gap-px bg-[#e0ddd4] lg:grid-cols-2">
                <div className="min-w-0 bg-white px-4 py-3">
                  <div className="flex items-center justify-between gap-3">
                    <p className="text-xs font-semibold text-[#77736a]">{t("applyGate.closureOwnerFields")}</p>
                    <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5 font-mono text-[11px] text-[#5f5b52]">
                      {closureOwnerFields.length}
                    </span>
                  </div>
                  <div className="mt-3 grid gap-2 sm:grid-cols-2">
                    {(closureOwnerFields.length ? closureOwnerFields : [emptyLabel]).map((item, index) => (
                      <span key={`${item}-${index}`} className="min-w-0 border border-[#ece8dd] bg-[#faf9f3] px-2 py-1 font-mono text-[11px] text-[#141413]">
                        {item}
                      </span>
                    ))}
                  </div>
                </div>
                <div className="min-w-0 bg-white px-4 py-3">
                  <div className="flex items-center justify-between gap-3">
                    <p className="text-xs font-semibold text-[#77736a]">{t("applyGate.closureReadbackAssets")}</p>
                    <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5 font-mono text-[11px] text-[#5f5b52]">
                      {closureReadbackAssets.length}
                    </span>
                  </div>
                  <div className="mt-3 space-y-2">
                    {(closureReadbackAssets.length ? closureReadbackAssets : [{ key: emptyLabel, asset_id: emptyLabel, status: emptyLabel }]).map((item, index) => (
                      <div key={`${item.key}-${index}`} className="min-w-0 border border-[#ece8dd] bg-[#faf9f3] px-2 py-2">
                        <div className="flex flex-wrap items-center justify-between gap-2">
                          <p className="text-xs font-semibold text-[#141413]">{closureAssetLabel(item.key)}</p>
                          <span className="border border-[#d8d3c7] bg-white px-2 py-0.5 font-mono text-[11px] text-[#5f5b52]">
                            {closureStatusLabel(item.status)}
                          </span>
                        </div>
                        <p className="mt-1 break-all font-mono text-[11px] text-[#5f5b52]" title={valueOrEmpty(item.asset_id, emptyLabel)}>
                          {valueOrEmpty(item.asset_id, emptyLabel)}
                        </p>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          )}
          <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-3">
            <div className="min-w-0 bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{t("applyGate.workItem")}</p>
              <p className="mt-2 break-all font-mono text-sm text-[#141413]" title={valueOrEmpty(automationHandoff.work_item_id, emptyLabel)}>
                {valueOrEmpty(automationHandoff.work_item_id, emptyLabel)}
              </p>
              {handoffWorkItemHref && (
                <Link
                  href={handoffWorkItemHref as never}
                  className="mt-3 inline-flex items-center gap-2 border border-[#d8d3c7] bg-[#faf9f3] px-2.5 py-1 text-xs font-semibold text-[#141413] hover:border-[#bdb6a8]"
                >
                  <Link2 className="h-3.5 w-3.5" aria-hidden="true" />
                  {t("applyGate.openWorkItem")}
                </Link>
              )}
            </div>
            <div className="min-w-0 bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{t("applyGate.ownerGate")}</p>
              <p className="mt-2 break-words font-mono text-sm text-[#141413]" title={valueOrEmpty(automationHandoff.owner_review_gate, emptyLabel)}>
                {valueOrEmpty(automationHandoff.owner_review_gate, emptyLabel)}
              </p>
            </div>
            <div className="min-w-0 bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{t("applyGate.nextAction")}</p>
              <p className="mt-2 break-words text-sm text-[#141413]" title={valueOrEmpty(automationHandoff.next_action, emptyLabel)}>
                {nextActionLabel(automationHandoff.next_action)}
              </p>
            </div>
          </div>
          <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-5">
            {handoffCandidateCards.map((item) => (
              <div key={item.key} className="min-w-0 bg-white px-4 py-3">
                <p className="text-xs font-semibold text-[#77736a]">{item.label}</p>
                <p className="mt-2 break-all font-mono text-sm text-[#141413]" title={valueOrEmpty(item.value, emptyLabel)}>
                  {valueOrEmpty(item.value, emptyLabel)}
                </p>
              </div>
            ))}
          </div>
          <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-3">
            {handoffAssetCards.map((item) => (
              <div key={item.key} className="min-w-0 bg-white px-4 py-3">
                <p className="text-xs font-semibold text-[#77736a]">{item.label}</p>
                <p className="mt-2 break-all font-mono text-sm text-[#141413]" title={valueOrEmpty(item.value, emptyLabel)}>
                  {valueOrEmpty(item.value, emptyLabel)}
                </p>
              </div>
            ))}
          </div>
          <div className="grid gap-px bg-[#e0ddd4] lg:grid-cols-2">
            <div className="min-w-0 bg-white px-4 py-3">
              <div className="flex items-center justify-between gap-3">
                <p className="text-xs font-semibold text-[#77736a]">{t("applyGate.checklistTitle")}</p>
                <span className="border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5 font-mono text-[11px] text-[#5f5b52]">
                  {ownerReviewChecklist.length}
                </span>
              </div>
              <ul className="mt-3 space-y-2">
                {(ownerReviewChecklist.length ? ownerReviewChecklist : [emptyLabel]).map((item, index) => (
                  <li key={`${item}-${index}`} className="flex min-w-0 items-start gap-2 text-xs leading-5 text-[#141413]">
                    <CheckCircle2 className="mt-0.5 h-3.5 w-3.5 shrink-0 text-[#17602a]" aria-hidden="true" />
                    <span className="min-w-0 break-words font-mono">{item}</span>
                  </li>
                ))}
              </ul>
            </div>
            <div className="min-w-0 bg-white px-4 py-3">
              <div className="flex items-center justify-between gap-3">
                <p className="text-xs font-semibold text-[#77736a]">{t("applyGate.forbiddenTitle")}</p>
                <span className="border border-[#e2a29b] bg-[#fff0ef] px-2 py-0.5 font-mono text-[11px] text-[#9f2f25]">
                  {forbiddenActions.length}
                </span>
              </div>
              <ul className="mt-3 space-y-2">
                {(forbiddenActions.length ? forbiddenActions : [emptyLabel]).map((item, index) => (
                  <li key={`${item}-${index}`} className="flex min-w-0 items-start gap-2 text-xs leading-5 text-[#141413]">
                    <TriangleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0 text-[#9f2f25]" aria-hidden="true" />
                    <span className="min-w-0 break-words font-mono">{item}</span>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      )}

      <div className="border-t border-[#e0ddd4] bg-[#faf9f3] px-4 py-2">
        <p className="text-xs font-semibold text-[#141413]">{t("toolchain.title")}</p>
      </div>
      <div className={cn("grid gap-px bg-[#e0ddd4]", compact ? "md:grid-cols-2" : "md:grid-cols-5")}>
        {toolchainItems.map((item) => (
          <div key={item.key} className="min-w-0 bg-white px-4 py-3">
            <div className="flex min-w-0 items-start gap-3">
              <span className={cn(
                "flex h-8 w-8 shrink-0 items-center justify-center border",
                sourceFlowToneClass(item.tone)
              )}>
                <item.Icon className="h-4 w-4" aria-hidden="true" />
              </span>
              <div className="min-w-0">
                <p className="text-xs font-semibold text-[#77736a]">{item.label}</p>
                <p className="mt-1 truncate font-mono text-sm font-semibold text-[#141413]" title={item.value}>
                  {item.value}
                </p>
              </div>
            </div>
            <p className="mt-2 truncate font-mono text-xs text-[#5f5b52]" title={item.detail}>
              {item.detail}
            </p>
          </div>
        ))}
      </div>

      {sourceCorrelation && (
        <div>
          <div className={cn("grid gap-px bg-[#e0ddd4]", compact ? "grid-cols-1" : "md:grid-cols-3")}>
            {sourceEvidenceFlow.map((item) => (
              <div key={item.key} className="min-w-0 bg-white px-4 py-3">
                <div className="flex min-w-0 items-start gap-3">
                  <span className={cn(
                    "flex h-8 w-8 shrink-0 items-center justify-center border",
                    sourceFlowToneClass(item.tone)
                  )}>
                    <item.Icon className="h-4 w-4" aria-hidden="true" />
                  </span>
                  <div className="min-w-0">
                    <p className="text-xs font-semibold text-[#77736a]">{item.label}</p>
                    <p className="mt-1 truncate font-mono text-sm font-semibold text-[#141413]" title={item.status}>
                      {item.status}
                    </p>
                  </div>
                </div>
                <p className="mt-2 truncate font-mono text-xs text-[#5f5b52]" title={item.detail}>
                  {item.detail}
                </p>
              </div>
            ))}
          </div>
          <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-6">
            <div className="min-w-0 bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{t("source.status")}</p>
              <p className="mt-2 truncate font-mono text-sm text-[#141413]" title={sourceStatusLabels[sourceStatus] ?? sourceStatus}>
                {sourceStatusLabels[sourceStatus] ?? valueOrEmpty(sourceCorrelation.status, emptyLabel)}
              </p>
            </div>
            <div className="min-w-0 bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{t("source.verification")}</p>
              <p
                className="mt-2 truncate font-mono text-sm text-[#141413]"
                title={sourceVerificationLabels[sourceVerificationStatus] ?? sourceVerificationStatus}
              >
                {sourceVerificationLabels[sourceVerificationStatus] ?? valueOrEmpty(sourceVerificationStatus, emptyLabel)}
              </p>
            </div>
            <div className="min-w-0 bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{t("source.directCandidate")}</p>
              <p className="mt-2 font-mono text-sm text-[#141413]">
                {t("source.directCandidateValue", {
                  direct: directRefTotal,
                  candidate: candidateTotal,
                  applied: appliedLinkTotal,
                })}
              </p>
            </div>
            <div className="min-w-0 bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{t("source.latestApplied")}</p>
              <p className="mt-2 truncate font-mono text-sm text-[#141413]" title={latestAppliedLabel}>
                {latestAppliedLabel}
              </p>
            </div>
            <div className="min-w-0 bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{t("source.reason")}</p>
              <p
                className="mt-2 truncate font-mono text-sm text-[#141413]"
                title={sourceReasonLabels[sourceMissingReason] ?? sourceMissingReason}
              >
                {sourceReasonLabels[sourceMissingReason] ?? valueOrEmpty(sourceMissingReason, emptyLabel)}
              </p>
            </div>
            <div className="min-w-0 bg-white px-4 py-3">
              <p className="text-xs font-semibold text-[#77736a]">{t("source.providers")}</p>
              <p className="mt-2 truncate font-mono text-sm text-[#141413]" title={sourceProviderSummary}>
                {sourceProviderSummary}
              </p>
            </div>
          </div>
        </div>
      )}

      {!compact && (
        <div>
          <div className="border-t border-[#e0ddd4] bg-[#faf9f3] px-4 py-2">
            <p className="text-xs font-semibold text-[#141413]">{t("drilldown.title")}</p>
          </div>
          <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-2 xl:grid-cols-3">
            {drilldownItems.map((item, index) => (
              <div key={item.key} className="min-w-0 bg-white px-4 py-3">
                <div className="flex min-w-0 items-start gap-3">
                  <span className={cn(
                    "flex h-8 w-8 shrink-0 items-center justify-center border",
                    sourceFlowToneClass(item.tone)
                  )}>
                    <item.Icon className="h-4 w-4" aria-hidden="true" />
                  </span>
                  <div className="min-w-0">
                    <p className="text-xs font-semibold text-[#77736a]">
                      {t("drilldown.step", { step: index + 1, label: item.title })}
                    </p>
                    <p className="mt-1 truncate font-mono text-sm font-semibold text-[#141413]" title={item.value}>
                      {item.value}
                    </p>
                  </div>
                </div>
                <p className="mt-2 truncate font-mono text-xs text-[#5f5b52]" title={item.detail}>
                  {item.detail}
                </p>
              </div>
            ))}
          </div>
        </div>
      )}

      {blockers.length > 0 && (
        <div className="border-t border-[#eee9dd] bg-[#fff7e8] px-4 py-3 text-xs leading-5 text-[#8a5a08]">
          <span className="font-semibold">{t("blockers")}</span>{" "}
          <span className="font-mono">{blockers.slice(0, compact ? 2 : 4).join(", ")}</span>
        </div>
      )}
    </section>
  );
}
