"use client";

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

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;
  };
  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;
      }>;
    };
  };
  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.needs_human) return "border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]";
  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.needs_human) return TriangleAlert;
  if (chain.repair_state === "auto_repaired_verified") return CheckCircle2;
  if (chain.repair_state === "blocked_manual_required") return ShieldAlert;
  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 blockers = chain?.blockers ?? [];
  const sourceCorrelation = chain?.source_refs?.correlation;

  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: valueOrEmpty(outcome?.next_action ?? chain.next_step, emptyLabel) },
  ];
  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 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: valueOrEmpty(chain.next_step, emptyLabel),
      }),
    },
  ];
  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: valueOrEmpty(chain.next_step, emptyLabel),
      }),
    },
    {
      key: "handoff",
      Icon: chain.needs_human ? TriangleAlert : CheckCircle2,
      tone: (chain.needs_human ? "blocked" : "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: valueOrEmpty(outcome?.next_action ?? chain.next_step, emptyLabel),
      }),
    },
  ];

  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>

      <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>
  );
}
