// =============================================================================
// WOOO AIOps - AwoooP Operator Console 首頁
// =============================================================================
// 將 AwoooP 定位為 AI 自動化飛輪的治理面、稽核面與人工操作面。

"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import {
  Activity,
  ArrowRight,
  BrainCircuit,
  CheckCircle2,
  FileText,
  GitBranch,
  ListChecks,
  Lock,
  RefreshCw,
  SearchCheck,
  ShieldCheck,
  TriangleAlert,
  Waypoints,
} from "lucide-react";
import { Link } from "@/i18n/routing";
import { cn } from "@/lib/utils";

type Tenant = {
  project_id: string;
  display_name?: string;
  migration_mode?: string;
  is_active?: boolean;
};

type PlatformResponse = {
  tenants?: Tenant[];
  total?: number;
  runs?: unknown[];
  contracts?: unknown[];
  items?: unknown[];
};

type Snapshot = {
  tenants: number;
  activeTenants: number;
  shadowTenants: number;
  runs: number;
  approvals: number;
  contracts: number;
};

type SnapshotStatus = "loading" | "ready" | "degraded";

type SecurityMirrorMetric = {
  key: string;
  value: string;
  icon: typeof ShieldCheck;
  tone: "good" | "warn" | "neutral";
};

type SecurityMirrorCheckpoint = {
  key: string;
  status: string;
  icon: typeof ShieldCheck;
  tone: "good" | "warn" | "neutral";
};

type GitHubPrimaryReadinessMetric = {
  key: string;
  value: string;
  icon: typeof ShieldCheck;
  tone: "good" | "warn" | "neutral";
};

type GitHubPrimaryReadinessRef = {
  key: string;
  contract: string;
  status: string;
  tone: "good" | "warn" | "neutral";
};

type OwnerResponseValidationMetric = {
  key: string;
  value: string;
  icon: typeof ShieldCheck;
  tone: "good" | "warn" | "neutral";
};

type OwnerResponseValidationPacket = {
  key: string;
  lane: string;
  templates: string;
  received: string;
  accepted: string;
  rejected: string;
  icon: typeof ShieldCheck;
};

type OwnerResponseValidationCheck = {
  key: string;
  value: string;
  tone: "good" | "warn" | "neutral";
};

type HighValueConfigOwnerPacketMetric = {
  key: string;
  value: string;
  icon: typeof ShieldCheck;
  tone: "good" | "warn" | "neutral";
};

type HighValueConfigOwnerPacketRef = {
  key: string;
  contract: string;
  status: string;
  tone: "good" | "warn" | "neutral";
};

type QualityVerdict = {
  verdict: string;
  total: number;
  min_score?: number;
  max_score?: number;
  avg_score?: number;
  needs_human?: boolean;
};

type QualityGateFailure = {
  gate: string;
  total: number;
  statuses?: Record<string, number>;
};

type AutomationQualitySummary = {
  schema_version: "automation_quality_summary_v1";
  incident_total: number;
  evaluated_total: number;
  verified_auto_repair_total: number;
  average_score: number;
  score_buckets: {
    green: number;
    yellow: number;
    red: number;
  };
  by_verdict: QualityVerdict[];
  gate_failures: QualityGateFailure[];
  production_claim: {
    can_claim_full_auto_repair: boolean;
    reason: string;
  };
};

type SourceFlowSummary = {
  source_event_total: number;
  recurrence_group_total: number;
  linked_run_total: number;
  unlinked_event_total: number;
  open_work_item_group_total?: number;
  manual_gate_group_total?: number;
  automation_gap_group_total?: number;
  failed_repair_group_total?: number;
  source_correlation_review_group_total?: number;
  source_correlation_decision_recorded_group_total?: number;
  source_correlation_applied_group_total?: number;
  latest_received_at?: string | null;
};

type SourceFlowResponse = {
  project_id: string;
  limit: number;
  summary: SourceFlowSummary;
};

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

const emptySnapshot: Snapshot = {
  tenants: 0,
  activeTenants: 0,
  shadowTenants: 0,
  runs: 0,
  approvals: 0,
  contracts: 0,
};

const securityMirrorMetrics: SecurityMirrorMetric[] = [
  { key: "headline", value: "64%", icon: ShieldCheck, tone: "warn" },
  { key: "framework", value: "92%", icon: FileText, tone: "good" },
  { key: "runtime", value: "40-45%", icon: TriangleAlert, tone: "warn" },
  { key: "activeGates", value: "0", icon: Lock, tone: "neutral" },
];

const securityMirrorCheckpoints: SecurityMirrorCheckpoint[] = [
  { key: "iwooosProjection", status: "C1", icon: SearchCheck, tone: "good" },
  { key: "rollupGuard", status: "C2", icon: ShieldCheck, tone: "good" },
  { key: "ownerResponse", status: "C3", icon: ListChecks, tone: "warn" },
  { key: "productionLanding", status: "C4", icon: ShieldCheck, tone: "good" },
];

const githubPrimaryReadinessMetrics: GitHubPrimaryReadinessMetric[] = [
  { key: "candidateRepos", value: "8", icon: GitBranch, tone: "neutral" },
  { key: "inScopeRepos", value: "7", icon: ListChecks, tone: "warn" },
  { key: "primaryReady", value: "0", icon: Lock, tone: "warn" },
  { key: "ownerResponses", value: "0/22", icon: ShieldCheck, tone: "warn" },
  { key: "workflowInventory", value: "0/7", icon: SearchCheck, tone: "warn" },
];

const githubPrimaryReadinessRefs: GitHubPrimaryReadinessRef[] = [
  {
    key: "primaryReadiness",
    contract: "source_control_primary_readiness_gate_v1",
    status: "S4.9",
    tone: "warn",
  },
  {
    key: "ownerValidation",
    contract: "source_control_owner_response_validation_rollup_v1",
    status: "0/22",
    tone: "warn",
  },
  {
    key: "rollbackAdr",
    contract: "source_control_primary_rollback_adr_v1",
    status: "0/7",
    tone: "warn",
  },
  {
    key: "workflowInventory",
    contract: "source_control_workflow_secret_name_inventory_v1",
    status: "0/7",
    tone: "warn",
  },
];

const githubPrimaryReadinessBoundaries = [
  "repo_creation_authorized=false",
  "refs_mutation_authorized=false",
  "secret_value_collection_allowed=false",
  "github_primary_switch_authorized=false",
  "gitea_disablement_authorized=false",
  "runtime_execution_authorized=false",
  "action_buttons_allowed=false",
];

const ownerResponseValidationMetrics: OwnerResponseValidationMetric[] = [
  { key: "packets", value: "4", icon: ListChecks, tone: "warn" },
  { key: "templates", value: "22", icon: FileText, tone: "neutral" },
  { key: "received", value: "0", icon: Lock, tone: "warn" },
  { key: "accepted", value: "0", icon: ShieldCheck, tone: "warn" },
  { key: "rejected", value: "0", icon: TriangleAlert, tone: "neutral" },
];

const ownerResponseValidationPackets: OwnerResponseValidationPacket[] = [
  {
    key: "giteaInventory",
    lane: "S4.9",
    templates: "5",
    received: "0",
    accepted: "0",
    rejected: "0",
    icon: GitBranch,
  },
  {
    key: "githubTarget",
    lane: "S4.10",
    templates: "7",
    received: "0",
    accepted: "0",
    rejected: "0",
    icon: ShieldCheck,
  },
  {
    key: "refTruth",
    lane: "S4.11",
    templates: "5",
    received: "0",
    accepted: "0",
    rejected: "0",
    icon: Waypoints,
  },
  {
    key: "workflowSecret",
    lane: "S4.12",
    templates: "5",
    received: "0",
    accepted: "0",
    rejected: "0",
    icon: SearchCheck,
  },
];

const ownerResponseValidationChecks: OwnerResponseValidationCheck[] = [
  { key: "crossPacket", value: "10", tone: "warn" },
  { key: "evidenceRouting", value: "6", tone: "neutral" },
  { key: "displaySections", value: "8", tone: "neutral" },
  { key: "stateTransitions", value: "7", tone: "neutral" },
  { key: "reviewerChecklist", value: "9", tone: "neutral" },
  { key: "reviewerOutcomes", value: "7", tone: "neutral" },
];

const ownerResponseValidationBoundaries = [
  "owner_response_validation_received_count=0",
  "owner_response_validation_accepted_count=0",
  "owner_response_validation_rejected_count=0",
  "repo_creation_authorized=false",
  "refs_sync_authorized=false",
  "workflow_modification_authorized=false",
  "secret_value_collection_allowed=false",
  "github_primary_switch_authorized=false",
  "runtime_execution_authorized=false",
  "action_buttons_allowed=false",
];

const highValueConfigOwnerPacketMetrics: HighValueConfigOwnerPacketMetric[] = [
  { key: "packetDrafts", value: "1", icon: FileText, tone: "warn" },
  { key: "c0Packets", value: "0", icon: Lock, tone: "neutral" },
  { key: "responses", value: "0 / 0", icon: ShieldCheck, tone: "warn" },
  { key: "runtimeGate", value: "0", icon: Lock, tone: "neutral" },
];

const highValueConfigOwnerPacketRefs: HighValueConfigOwnerPacketRef[] = [
  {
    key: "packetDraft",
    contract: "high_value_config_owner_packet_v1",
    status: "草案 1",
    tone: "warn",
  },
  {
    key: "c0Scope",
    contract: "high_value_config_change_gate_v1",
    status: "C0 0",
    tone: "neutral",
  },
  {
    key: "s49Envelope",
    contract: "source_control_owner_response_validation_rollup_v1",
    status: "0 / 0",
    tone: "warn",
  },
  {
    key: "runtimeBoundary",
    contract: "iwooos_posture_projection_v1",
    status: "gate 0",
    tone: "neutral",
  },
];

const highValueConfigOwnerPacketBoundaries = [
  "awooop_high_value_config_owner_packet_summary_count=4",
  "awooop_high_value_config_owner_packet_ref_count=4",
  "high_value_config_owner_packet_count=1",
  "high_value_config_owner_packet_c0_packet_count=0",
  "high_value_config_owner_packet_request_sent_count=0",
  "high_value_config_owner_packet_received_response_count=0",
  "high_value_config_owner_packet_accepted_response_count=0",
  "runtime_execution_authorized=false",
  "action_buttons_allowed=false",
  "send_owner_request_allowed=false",
  "mark_received_allowed=false",
  "mark_accepted_allowed=false",
  "nginx_reload_authorized=false",
  "workflow_modification_authorized=false",
  "agent_bounty_runtime_authorized=false",
];

function numberValue(value: unknown): number {
  return typeof value === "number" && Number.isFinite(value) ? value : 0;
}

function countRows(data: PlatformResponse, keys: Array<keyof PlatformResponse>): number {
  if (typeof data.total === "number") return data.total;
  for (const key of keys) {
    const rows = data[key];
    if (Array.isArray(rows)) return rows.length;
  }
  return 0;
}

function MetricCell({
  label,
  value,
  detail,
  icon: Icon,
  tone = "neutral",
}: {
  label: string;
  value: string | number;
  detail: string;
  icon: typeof Activity;
  tone?: "neutral" | "good" | "warn";
}) {
  return (
    <div className="min-h-[116px] border border-[#e0ddd4] bg-white px-4 py-3">
      <div className="flex items-start justify-between gap-3">
        <div>
          <p className="text-xs font-semibold text-[#77736a]">{label}</p>
          <p className="mt-2 font-mono text-3xl font-semibold leading-none text-[#141413]">
            {value}
          </p>
        </div>
        <span
          className={cn(
            "flex h-8 w-8 items-center justify-center border",
            tone === "good" && "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
            tone === "warn" && "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
            tone === "neutral" && "border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]"
          )}
        >
          <Icon className="h-4 w-4" aria-hidden="true" />
        </span>
      </div>
      <p className="mt-3 text-xs leading-5 text-[#5f5b52]">{detail}</p>
    </div>
  );
}

function LaneRow({
  name,
  status,
  detail,
  tone,
}: {
  name: string;
  status: string;
  detail: string;
  tone: "good" | "warn" | "neutral";
}) {
  return (
    <div className="grid gap-3 border-b border-[#eee9dd] px-4 py-3 last:border-b-0 md:grid-cols-[180px_140px_1fr]">
      <div className="font-mono text-xs font-semibold text-[#141413]">{name}</div>
      <div>
        <span
          className={cn(
            "inline-flex border px-2 py-0.5 text-xs font-semibold",
            tone === "good" && "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
            tone === "warn" && "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
            tone === "neutral" && "border-[#d8d3c7] bg-white text-[#5f5b52]"
          )}
        >
          {status}
        </span>
      </div>
      <div className="text-sm leading-5 text-[#5f5b52]">{detail}</div>
    </div>
  );
}

function DispositionCell({
  title,
  signal,
  owner,
  route,
  tone,
  icon: Icon,
}: {
  title: string;
  signal: string;
  owner: string;
  route: string;
  tone: "diagnosis" | "approval" | "execute" | "manual";
  icon: typeof SearchCheck;
}) {
  return (
    <div className="min-h-[154px] border border-[#e0ddd4] bg-white px-4 py-3">
      <div className="flex items-start justify-between gap-3">
        <div>
          <p className="text-xs font-semibold text-[#77736a]">{signal}</p>
          <h3 className="mt-2 text-base font-semibold tracking-normal text-[#141413]">
            {title}
          </h3>
        </div>
        <span
          className={cn(
            "flex h-8 w-8 items-center justify-center border",
            tone === "diagnosis" && "border-[#9bb6d9] bg-[#eef5ff] text-[#1f5b9b]",
            tone === "approval" && "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
            tone === "execute" && "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
            tone === "manual" && "border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]"
          )}
        >
          <Icon className="h-4 w-4" aria-hidden="true" />
        </span>
      </div>
      <dl className="mt-4 grid gap-2 text-xs">
        <div className="flex items-center justify-between gap-3">
          <dt className="text-[#77736a]">{route}</dt>
        </div>
        <div className="flex items-center justify-between gap-3">
          <dt className="text-[#77736a]">{owner}</dt>
        </div>
      </dl>
    </div>
  );
}

function verdictLabel(verdict: string, t: ReturnType<typeof useTranslations>): string {
  switch (verdict) {
    case "auto_repaired_verified":
      return t("verdicts.autoRepairedVerified");
    case "execution_unverified":
      return t("verdicts.executionUnverified");
    case "execution_failed":
      return t("verdicts.executionFailed");
    case "manual_required_no_action":
      return t("verdicts.manualRequiredNoAction");
    case "approval_required":
      return t("verdicts.approvalRequired");
    case "observed_not_executed":
      return t("verdicts.observedNotExecuted");
    case "received_only":
      return t("verdicts.receivedOnly");
    default:
      return verdict || "--";
  }
}

function gateLabel(gate: string, t: ReturnType<typeof useTranslations>): string {
  switch (gate) {
    case "source_persisted":
      return t("gates.sourcePersisted");
    case "outbound_recorded":
      return t("gates.outboundRecorded");
    case "evidence_collected":
      return t("gates.evidenceCollected");
    case "mcp_gateway_observed":
      return t("gates.mcpGatewayObserved");
    case "approval_state":
      return t("gates.approvalState");
    case "execution_recorded":
      return t("gates.executionRecorded");
    case "auto_repair_recorded":
      return t("gates.autoRepairRecorded");
    case "verification_recorded":
      return t("gates.verificationRecorded");
    case "learning_recorded":
      return t("gates.learningRecorded");
    case "timeline_recorded":
      return t("gates.timelineRecorded");
    default:
      return gate || "--";
  }
}

function gateStatusLabel(status: string, t: ReturnType<typeof useTranslations>): string {
  switch (status) {
    case "failed":
      return t("gateStatuses.failed");
    case "missing":
      return t("gateStatuses.missing");
    default:
      return status || "--";
  }
}

function QualityMetric({
  label,
  value,
  detail,
}: {
  label: string;
  value: string | number;
  detail: string;
}) {
  return (
    <div className="min-h-[96px] border border-[#e0ddd4] bg-white px-4 py-3">
      <p className="text-xs font-semibold text-[#77736a]">{label}</p>
      <p className="mt-2 font-mono text-2xl font-semibold leading-none text-[#141413]">
        {value}
      </p>
      <p className="mt-2 text-xs leading-5 text-[#5f5b52]">{detail}</p>
    </div>
  );
}

function percentValue(numerator: number, denominator: number): number {
  if (denominator <= 0) return 0;
  return Math.max(0, Math.min(100, (numerator / denominator) * 100));
}

function ProgressRow({
  label,
  value,
  detail,
  percent,
  tone,
}: {
  label: string;
  value: string;
  detail: string;
  percent: number;
  tone: "good" | "warn" | "neutral";
}) {
  return (
    <div className="border border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <p className="text-xs font-semibold text-[#77736a]">{label}</p>
          <p className="mt-1 text-xs leading-5 text-[#5f5b52]">{detail}</p>
        </div>
        <span className="font-mono text-sm font-semibold text-[#141413]">{value}</span>
      </div>
      <div className="mt-3 h-2 overflow-hidden border border-[#d8d3c7] bg-white">
        <div
          className={cn(
            "h-full",
            tone === "good" && "bg-[#6aa879]",
            tone === "warn" && "bg-[#d9b36f]",
            tone === "neutral" && "bg-[#9bb6d9]"
          )}
          style={{ width: `${percent}%` }}
        />
      </div>
    </div>
  );
}

function SourceFlowActionLink({
  href,
  label,
  value,
  detail,
  icon: Icon,
  tone,
}: {
  href: string;
  label: string;
  value: string | number;
  detail: string;
  icon: typeof ArrowRight;
  tone: "good" | "warn" | "neutral";
}) {
  return (
    <Link
      href={href as never}
      className="group flex min-h-[92px] items-start justify-between gap-3 border border-[#e0ddd4] bg-white px-4 py-3 hover:border-[#d97757] hover:bg-[#faf9f3]"
    >
      <div className="min-w-0">
        <p className="text-xs font-semibold text-[#77736a]">{label}</p>
        <p className="mt-2 font-mono text-2xl font-semibold leading-none text-[#141413]">
          {value}
        </p>
        <p className="mt-2 text-xs leading-5 text-[#5f5b52]">{detail}</p>
      </div>
      <span
        className={cn(
          "flex h-8 w-8 shrink-0 items-center justify-center border",
          tone === "good" && "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
          tone === "warn" && "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
          tone === "neutral" && "border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]"
        )}
      >
        <Icon
          className="h-4 w-4 transition-transform group-hover:translate-x-0.5"
          aria-hidden="true"
        />
      </span>
    </Link>
  );
}

function SourceFlowOverviewPanel({
  summary,
  error,
  locale,
}: {
  summary: SourceFlowSummary | null;
  error: boolean;
  locale: string;
}) {
  const t = useTranslations("awooop.home.sourceFlow");
  const sourceTotal = summary?.source_event_total ?? 0;
  const groupTotal = summary?.recurrence_group_total ?? 0;
  const linkedRuns = summary?.linked_run_total ?? 0;
  const unlinkedEvents = summary?.unlinked_event_total ?? 0;
  const openWork = summary?.open_work_item_group_total ?? 0;
  const automationGaps = summary?.automation_gap_group_total ?? 0;
  const manualGates = summary?.manual_gate_group_total ?? 0;
  const failedRepairs = summary?.failed_repair_group_total ?? 0;
  const sourceReview = summary?.source_correlation_review_group_total ?? 0;
  const sourceReviewRecorded = summary?.source_correlation_decision_recorded_group_total ?? 0;
  const sourceApplied = summary?.source_correlation_applied_group_total ?? 0;
  const sourceDecisionKnown = sourceReviewRecorded + sourceApplied;
  const sourceDecisionTotal = sourceReview + sourceDecisionKnown;
  const linkedPercent = percentValue(linkedRuns, sourceTotal);
  const workClearPercent = percentValue(Math.max(0, groupTotal - openWork), groupTotal);
  const sourceDecisionPercent = sourceDecisionTotal === 0
    ? 100
    : percentValue(sourceDecisionKnown, sourceDecisionTotal);
  const latestTime = summary?.latest_received_at
    ? new Date(summary.latest_received_at).toLocaleTimeString(locale === "zh-TW" ? "zh-TW" : "en-US", {
        hour: "2-digit",
        minute: "2-digit",
      })
    : "--";

  return (
    <section className="border border-[#e0ddd4] bg-white">
      <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex items-start gap-2">
          <GitBranch className="mt-0.5 h-4 w-4 text-[#d97757]" aria-hidden="true" />
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 text-xs leading-5 text-[#77736a]">{t("subtitle")}</p>
          </div>
        </div>
        <span
          className={cn(
            "inline-flex border px-2 py-0.5 text-xs font-semibold",
            error && "border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]",
            !error && sourceTotal > 0 && "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
            !error && sourceTotal === 0 && "border-[#d8d3c7] bg-white text-[#5f5b52]"
          )}
        >
          {error ? t("unavailable") : t("sourceEvents", { count: sourceTotal })}
        </span>
      </div>

      {error || !summary ? (
        <div className="px-4 py-5 text-sm leading-6 text-[#5f5b52]">
          {error ? t("loadFailed") : t("empty")}
        </div>
      ) : (
        <div className="space-y-4 p-4">
          <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
            <QualityMetric
              label={t("metrics.linkedRuns")}
              value={`${linkedRuns}/${sourceTotal}`}
              detail={t("metrics.linkedRunsDetail", { unlinked: unlinkedEvents })}
            />
            <QualityMetric
              label={t("metrics.openWork")}
              value={openWork}
              detail={t("metrics.openWorkDetail", {
                gap: automationGaps,
                manual: manualGates,
                failed: failedRepairs,
              })}
            />
            <QualityMetric
              label={t("metrics.sourceDecision")}
              value={
                sourceDecisionTotal === 0
                  ? t("metrics.sourceDecisionNone")
                  : `${sourceDecisionKnown}/${sourceDecisionTotal}`
              }
              detail={t("metrics.sourceDecisionDetail", { recorded: sourceReviewRecorded })}
            />
            <QualityMetric
              label={t("metrics.latest")}
              value={latestTime}
              detail={t("metrics.latestDetail", { groups: groupTotal })}
            />
          </div>

          <div className="grid gap-3 xl:grid-cols-3">
            <ProgressRow
              label={t("progress.linked")}
              value={`${linkedPercent.toFixed(0)}%`}
              detail={t("progress.linkedDetail")}
              percent={linkedPercent}
              tone={unlinkedEvents === 0 ? "good" : "warn"}
            />
            <ProgressRow
              label={t("progress.work")}
              value={`${workClearPercent.toFixed(0)}%`}
              detail={t("progress.workDetail")}
              percent={workClearPercent}
              tone={openWork === 0 ? "good" : "warn"}
            />
            <ProgressRow
              label={t("progress.decision")}
              value={`${sourceDecisionPercent.toFixed(0)}%`}
              detail={t("progress.decisionDetail")}
              percent={sourceDecisionPercent}
              tone={sourceReview === 0 ? "good" : "neutral"}
            />
          </div>

          <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
            <SourceFlowActionLink
              href="/awooop/work-items?project_id=awoooi"
              label={t("actions.workItems")}
              value={openWork}
              detail={t("actions.workItemsDetail", { count: openWork })}
              icon={ArrowRight}
              tone={openWork === 0 ? "good" : "warn"}
            />
            <SourceFlowActionLink
              href="/awooop/runs?project_id=awoooi"
              label={t("actions.runs")}
              value={`${linkedRuns}/${sourceTotal}`}
              detail={t("actions.runsDetail", { unlinked: unlinkedEvents })}
              icon={Activity}
              tone={unlinkedEvents === 0 ? "good" : "warn"}
            />
            <SourceFlowActionLink
              href="/awooop/approvals"
              label={t("actions.approvals")}
              value={manualGates}
              detail={t("actions.approvalsDetail", { count: manualGates })}
              icon={ShieldCheck}
              tone={manualGates === 0 ? "good" : "warn"}
            />
            <SourceFlowActionLink
              href="/awooop/work-items?project_id=awoooi"
              label={t("actions.sourceReviews")}
              value={sourceReview}
              detail={t("actions.sourceReviewsDetail", { count: sourceReview })}
              icon={SearchCheck}
              tone={sourceReview === 0 ? "good" : "neutral"}
            />
          </div>
        </div>
      )}
    </section>
  );
}

function SecurityMirrorPanel() {
  const t = useTranslations("awooop.home.securityMirror");

  return (
    <section className="border border-[#e0ddd4] bg-white">
      <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex items-start gap-2">
          <ShieldCheck className="mt-0.5 h-4 w-4 text-[#d97757]" aria-hidden="true" />
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 max-w-3xl text-xs leading-5 text-[#77736a]">{t("subtitle")}</p>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <span className="inline-flex border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5 text-xs font-semibold text-[#8a5a08]">
            {t("badge")}
          </span>
          <Link
            href="/iwooos"
            className="inline-flex items-center gap-2 border border-[#d8d3c7] bg-white px-3 py-1.5 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
          >
            {t("openIwooos")}
            <ArrowRight className="h-3.5 w-3.5 text-[#77736a]" aria-hidden="true" />
          </Link>
        </div>
      </div>

      <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-2 xl:grid-cols-4">
        {securityMirrorMetrics.map((metric) => {
          const Icon = metric.icon;
          return (
            <div key={metric.key} className="min-h-[122px] 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(`metrics.${metric.key}.label` as never)}
                  </p>
                  <p className="mt-2 font-mono text-2xl font-semibold leading-none text-[#141413]">
                    {metric.value}
                  </p>
                </div>
                <span
                  className={cn(
                    "flex h-8 w-8 shrink-0 items-center justify-center border",
                    metric.tone === "good" && "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
                    metric.tone === "warn" && "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
                    metric.tone === "neutral" && "border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]"
                  )}
                >
                  <Icon className="h-4 w-4" aria-hidden="true" />
                </span>
              </div>
              <p className="mt-3 text-xs leading-5 text-[#5f5b52]">
                {t(`metrics.${metric.key}.detail` as never)}
              </p>
            </div>
          );
        })}
      </div>

      <div className="grid min-w-0 gap-4 p-4 xl:grid-cols-[1.15fr_0.85fr]">
        <div className="min-w-0 overflow-hidden border border-[#e0ddd4] bg-white">
          <div className="break-words border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3 text-xs font-semibold text-[#141413]">
            {t("checkpointsTitle")}
          </div>
          <div className="divide-y divide-[#eee9dd]">
            {securityMirrorCheckpoints.map((checkpoint) => {
              const Icon = checkpoint.icon;
              return (
                <div key={checkpoint.key} className="grid min-w-0 gap-3 px-4 py-3 md:grid-cols-[160px_1fr]">
                  <div className="flex min-w-0 items-center gap-2">
                    <Icon className="h-4 w-4 text-[#d97757]" aria-hidden="true" />
                    <span className="min-w-0 break-words font-mono text-xs font-semibold text-[#141413]">
                      {checkpoint.status}
                    </span>
                  </div>
                  <div className="min-w-0">
                    <p className="break-words text-sm font-semibold text-[#141413]">
                      {t(`checkpoints.${checkpoint.key}.title` as never)}
                    </p>
                    <p className="mt-1 break-words text-xs leading-5 text-[#5f5b52]">
                      {t(`checkpoints.${checkpoint.key}.detail` as never)}
                    </p>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="min-w-0 overflow-hidden border border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
          <p className="text-xs font-semibold text-[#77736a]">{t("boundaryLabel")}</p>
          <p className="mt-2 text-sm font-semibold text-[#141413]">{t("boundaryTitle")}</p>
          <p className="mt-2 break-words text-xs leading-5 text-[#5f5b52]">{t("boundaryDetail")}</p>
          <div className="mt-4 grid gap-2 break-all font-mono text-xs text-[#141413]">
            <span>read_only_production_landing_evidence_count=1</span>
            <span>execution_router_linked=false</span>
            <span>runtime_execution_authorized=false</span>
            <span>action_buttons_allowed=false</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function GitHubPrimaryReadinessHomePanel() {
  const t = useTranslations("awooop.home.githubPrimaryReadiness");

  return (
    <section className="border border-[#e0ddd4] bg-white">
      <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex items-start gap-2">
          <GitBranch className="mt-0.5 h-4 w-4 text-[#d97757]" aria-hidden="true" />
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 max-w-3xl text-xs leading-5 text-[#77736a]">{t("subtitle")}</p>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <span className="inline-flex border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5 text-xs font-semibold text-[#8a5a08]">
            {t("badge")}
          </span>
          <Link
            href="/iwooos"
            className="inline-flex items-center gap-2 border border-[#d8d3c7] bg-white px-3 py-1.5 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
          >
            {t("openIwooos")}
            <ArrowRight className="h-3.5 w-3.5 text-[#77736a]" aria-hidden="true" />
          </Link>
        </div>
      </div>

      <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-2 xl:grid-cols-5">
        {githubPrimaryReadinessMetrics.map((metric) => {
          const Icon = metric.icon;
          return (
            <div key={metric.key} className="min-h-[128px] 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(`metrics.${metric.key}.label` as never)}
                  </p>
                  <p className="mt-2 font-mono text-2xl font-semibold leading-none text-[#141413]">
                    {metric.value}
                  </p>
                </div>
                <span
                  className={cn(
                    "flex h-8 w-8 shrink-0 items-center justify-center border",
                    metric.tone === "good" && "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
                    metric.tone === "warn" && "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
                    metric.tone === "neutral" && "border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]"
                  )}
                >
                  <Icon className="h-4 w-4" aria-hidden="true" />
                </span>
              </div>
              <p className="mt-3 text-xs leading-5 text-[#5f5b52]">
                {t(`metrics.${metric.key}.detail` as never)}
              </p>
            </div>
          );
        })}
      </div>

      <div className="grid gap-4 p-4 xl:grid-cols-[1.15fr_0.85fr]">
        <div className="border border-[#e0ddd4] bg-white">
          <div className="border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3 text-xs font-semibold text-[#141413]">
            {t("readinessRefsTitle")}
          </div>
          <div className="divide-y divide-[#eee9dd]">
            {githubPrimaryReadinessRefs.map((ref) => (
              <div key={ref.key} className="grid gap-3 px-4 py-3 lg:grid-cols-[minmax(0,1fr)_96px]">
                <div className="min-w-0">
                  <p className="break-all font-mono text-xs font-semibold text-[#141413]">
                    {ref.contract}
                  </p>
                  <p className="mt-1 text-xs leading-5 text-[#5f5b52]">
                    {t(`readinessRefs.${ref.key}` as never)}
                  </p>
                </div>
                <div>
                  <span
                    className={cn(
                      "inline-flex border px-2 py-0.5 font-mono text-xs font-semibold",
                      ref.tone === "good" && "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
                      ref.tone === "warn" && "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
                      ref.tone === "neutral" && "border-[#d8d3c7] bg-white text-[#5f5b52]"
                    )}
                  >
                    {ref.status}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="border border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
          <p className="text-xs font-semibold text-[#77736a]">{t("boundaryLabel")}</p>
          <p className="mt-2 text-sm font-semibold text-[#141413]">{t("boundaryTitle")}</p>
          <p className="mt-2 text-xs leading-5 text-[#5f5b52]">{t("boundaryDetail")}</p>
          <div className="mt-4 grid gap-2 break-all font-mono text-xs text-[#141413]">
            {githubPrimaryReadinessBoundaries.map((boundary) => (
              <span key={boundary}>{boundary}</span>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function OwnerResponseValidationRollupPanel() {
  const t = useTranslations("awooop.home.ownerResponseValidation");

  return (
    <section className="border border-[#e0ddd4] bg-white">
      <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex items-start gap-2">
          <ListChecks className="mt-0.5 h-4 w-4 text-[#d97757]" aria-hidden="true" />
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 max-w-3xl text-xs leading-5 text-[#77736a]">{t("subtitle")}</p>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <span className="inline-flex border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5 text-xs font-semibold text-[#8a5a08]">
            {t("badge")}
          </span>
          <Link
            href="/iwooos"
            className="inline-flex items-center gap-2 border border-[#d8d3c7] bg-white px-3 py-1.5 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
          >
            {t("openIwooos")}
            <ArrowRight className="h-3.5 w-3.5 text-[#77736a]" aria-hidden="true" />
          </Link>
        </div>
      </div>

      <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-2 xl:grid-cols-5">
        {ownerResponseValidationMetrics.map((metric) => {
          const Icon = metric.icon;
          return (
            <div key={metric.key} className="min-h-[124px] 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(`metrics.${metric.key}.label` as never)}
                  </p>
                  <p className="mt-2 font-mono text-2xl font-semibold leading-none text-[#141413]">
                    {metric.value}
                  </p>
                </div>
                <span
                  className={cn(
                    "flex h-8 w-8 shrink-0 items-center justify-center border",
                    metric.tone === "good" && "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
                    metric.tone === "warn" && "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
                    metric.tone === "neutral" && "border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]"
                  )}
                >
                  <Icon className="h-4 w-4" aria-hidden="true" />
                </span>
              </div>
              <p className="mt-3 text-xs leading-5 text-[#5f5b52]">
                {t(`metrics.${metric.key}.detail` as never)}
              </p>
            </div>
          );
        })}
      </div>

      <div className="grid min-w-0 gap-4 p-4 xl:grid-cols-[1.25fr_0.75fr]">
        <div className="min-w-0 border border-[#e0ddd4] bg-white">
          <div className="border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3 text-xs font-semibold text-[#141413]">
            {t("packetsTitle")}
          </div>
          <div className="divide-y divide-[#eee9dd]">
            {ownerResponseValidationPackets.map((packet) => {
              const Icon = packet.icon;
              return (
                <div key={packet.key} className="grid min-w-0 gap-3 px-4 py-3 lg:grid-cols-[minmax(0,1fr)_240px]">
                  <div className="min-w-0">
                    <div className="flex flex-wrap items-center gap-2">
                      <Icon className="h-4 w-4 text-[#d97757]" aria-hidden="true" />
                      <span className="border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5 font-mono text-xs font-semibold text-[#8a5a08]">
                        {packet.lane}
                      </span>
                      <p className="text-sm font-semibold text-[#141413]">
                        {t(`packets.${packet.key}.title` as never)}
                      </p>
                    </div>
                    <p className="mt-2 text-xs leading-5 text-[#5f5b52]">
                      {t(`packets.${packet.key}.detail` as never)}
                    </p>
                  </div>
                  <div className="grid min-w-0 grid-cols-4 gap-px bg-[#e0ddd4] text-center">
                    {[
                      { label: t("fields.templates"), value: packet.templates },
                      { label: t("fields.received"), value: packet.received },
                      { label: t("fields.accepted"), value: packet.accepted },
                      { label: t("fields.rejected"), value: packet.rejected },
                    ].map((item) => (
                      <div key={item.label} className="bg-white px-2 py-2">
                        <p className="text-[10px] font-semibold text-[#77736a]">{item.label}</p>
                        <p className="mt-1 font-mono text-base font-semibold text-[#141413]">
                          {item.value}
                        </p>
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="grid min-w-0 gap-4">
          <div className="min-w-0 border border-[#e0ddd4] bg-white">
            <div className="border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3 text-xs font-semibold text-[#141413]">
              {t("validationTitle")}
            </div>
            <div className="grid min-w-0 gap-px bg-[#e0ddd4] sm:grid-cols-2">
              {ownerResponseValidationChecks.map((check) => (
                <div key={check.key} className="min-h-[88px] bg-white px-4 py-3">
                  <p className="text-xs font-semibold text-[#77736a]">
                    {t(`checks.${check.key}.label` as never)}
                  </p>
                  <p className="mt-2 font-mono text-2xl font-semibold leading-none text-[#141413]">
                    {check.value}
                  </p>
                  <p className="mt-2 text-xs leading-5 text-[#5f5b52]">
                    {t(`checks.${check.key}.detail` as never)}
                  </p>
                </div>
              ))}
            </div>
          </div>

          <div className="min-w-0 border border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
            <p className="text-xs font-semibold text-[#77736a]">{t("boundaryLabel")}</p>
            <p className="mt-2 text-sm font-semibold text-[#141413]">{t("boundaryTitle")}</p>
            <p className="mt-2 break-words text-xs leading-5 text-[#5f5b52]">{t("boundaryDetail")}</p>
            <div className="mt-4 grid gap-2 break-all font-mono text-xs text-[#141413]">
              {ownerResponseValidationBoundaries.map((boundary) => (
                <span key={boundary}>{boundary}</span>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function HighValueConfigOwnerPacketHomePanel() {
  const t = useTranslations("awooop.home.highValueConfigOwnerPacket");

  return (
    <section
      data-testid="awooop-high-value-config-owner-packet-board"
      className="border border-[#e0ddd4] bg-white"
    >
      <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex items-start gap-2">
          <ShieldCheck className="mt-0.5 h-4 w-4 text-[#d97757]" aria-hidden="true" />
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 max-w-3xl text-xs leading-5 text-[#77736a]">{t("subtitle")}</p>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <span className="inline-flex border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5 text-xs font-semibold text-[#8a5a08]">
            {t("badge")}
          </span>
          <Link
            href="/iwooos"
            className="inline-flex items-center gap-2 border border-[#d8d3c7] bg-white px-3 py-1.5 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
          >
            {t("openIwooos")}
            <ArrowRight className="h-3.5 w-3.5 text-[#77736a]" aria-hidden="true" />
          </Link>
        </div>
      </div>

      <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-2 xl:grid-cols-4">
        {highValueConfigOwnerPacketMetrics.map((metric) => {
          const Icon = metric.icon;
          return (
            <div key={metric.key} className="min-h-[124px] 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(`metrics.${metric.key}.label` as never)}
                  </p>
                  <p className="mt-2 break-words font-mono text-2xl font-semibold text-[#141413]">
                    {metric.value}
                  </p>
                </div>
                <span
                  className={cn(
                    "flex h-8 w-8 shrink-0 items-center justify-center border",
                    metric.tone === "good" && "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
                    metric.tone === "warn" && "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
                    metric.tone === "neutral" && "border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]"
                  )}
                >
                  <Icon className="h-4 w-4" aria-hidden="true" />
                </span>
              </div>
              <p className="mt-3 text-xs leading-5 text-[#5f5b52]">
                {t(`metrics.${metric.key}.detail` as never)}
              </p>
            </div>
          );
        })}
      </div>

      <div className="grid min-w-0 gap-4 p-4 xl:grid-cols-[1.15fr_0.85fr]">
        <div className="min-w-0 border border-[#e0ddd4] bg-white">
          <div className="border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3 text-xs font-semibold text-[#141413]">
            {t("refsTitle")}
          </div>
          <div className="divide-y divide-[#eee9dd]">
            {highValueConfigOwnerPacketRefs.map((ref) => (
              <div key={ref.key} className="grid gap-3 px-4 py-3 md:grid-cols-[minmax(0,1fr)_96px]">
                <div className="min-w-0">
                  <p className="break-all font-mono text-xs font-semibold text-[#141413]">
                    {ref.contract}
                  </p>
                  <p className="mt-1 text-xs leading-5 text-[#5f5b52]">
                    {t(`refs.${ref.key}` as never)}
                  </p>
                </div>
                <div>
                  <span
                    className={cn(
                      "inline-flex border px-2 py-0.5 font-mono text-xs font-semibold",
                      ref.tone === "good" && "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
                      ref.tone === "warn" && "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
                      ref.tone === "neutral" && "border-[#d8d3c7] bg-white text-[#5f5b52]"
                    )}
                  >
                    {ref.status}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div
          data-testid="awooop-high-value-config-owner-packet-boundaries"
          className="min-w-0 border border-[#e0ddd4] bg-[#faf9f3] px-4 py-3"
        >
          <p className="text-xs font-semibold text-[#77736a]">{t("boundaryLabel")}</p>
          <p className="mt-2 text-sm font-semibold text-[#141413]">{t("boundaryTitle")}</p>
          <p className="mt-2 break-words text-xs leading-5 text-[#5f5b52]">{t("boundaryDetail")}</p>
          <div className="mt-4 grid gap-2 break-all font-mono text-xs text-[#141413]">
            {highValueConfigOwnerPacketBoundaries.map((boundary) => (
              <span key={boundary}>{boundary}</span>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function AutomationQualityPanel({
  summary,
  error,
}: {
  summary: AutomationQualitySummary | null;
  error: boolean;
}) {
  const t = useTranslations("awooop.home.quality");
  const total = summary?.evaluated_total ?? 0;
  const claimReady = summary?.production_claim.can_claim_full_auto_repair === true;
  const buckets = summary?.score_buckets ?? { green: 0, yellow: 0, red: 0 };
  const bucketTotal = Math.max(1, buckets.green + buckets.yellow + buckets.red);

  return (
    <section className="border border-[#e0ddd4] bg-white">
      <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex items-start gap-2">
          <ShieldCheck className="mt-0.5 h-4 w-4 text-[#d97757]" aria-hidden="true" />
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 text-xs leading-5 text-[#77736a]">{t("subtitle")}</p>
          </div>
        </div>
        <span
          className={cn(
            "inline-flex border px-2 py-0.5 text-xs font-semibold",
            claimReady && "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
            !claimReady && !error && "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
            error && "border-[#e2a29b] bg-[#fff0ef] text-[#9f2f25]"
          )}
        >
          {error ? t("unavailable") : claimReady ? t("claimReady") : t("claimBlocked")}
        </span>
      </div>

      {error || !summary ? (
        <div className="px-4 py-5 text-sm leading-6 text-[#5f5b52]">
          {error ? t("loadFailed") : t("empty")}
        </div>
      ) : (
        <div className="space-y-4 p-4">
          <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
            <QualityMetric
              label={t("metrics.evaluated")}
              value={`${summary.evaluated_total}/${summary.incident_total}`}
              detail={t("metrics.evaluatedDetail")}
            />
            <QualityMetric
              label={t("metrics.verified")}
              value={summary.verified_auto_repair_total}
              detail={t("metrics.verifiedDetail")}
            />
            <QualityMetric
              label={t("metrics.averageScore")}
              value={summary.average_score.toFixed(1)}
              detail={t("metrics.averageScoreDetail")}
            />
            <QualityMetric
              label={t("metrics.claim")}
              value={claimReady ? t("yes") : t("no")}
              detail={claimReady ? t("claimReadyDetail") : t("claimBlockedDetail")}
            />
          </div>

          <div className="border border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div>
                <p className="text-xs font-semibold text-[#77736a]">{t("scoreBuckets")}</p>
                <p className="mt-1 text-xs text-[#5f5b52]">
                  {t("scoreBucketsDetail", { total })}
                </p>
              </div>
              <div className="flex gap-2 font-mono text-xs text-[#141413]">
                <span>{t("green")}: {buckets.green}</span>
                <span>{t("yellow")}: {buckets.yellow}</span>
                <span>{t("red")}: {buckets.red}</span>
              </div>
            </div>
            <div className="mt-3 flex h-2 overflow-hidden border border-[#d8d3c7] bg-white">
              <div
                className="bg-[#6aa879]"
                style={{ width: `${(buckets.green / bucketTotal) * 100}%` }}
              />
              <div
                className="bg-[#d9b36f]"
                style={{ width: `${(buckets.yellow / bucketTotal) * 100}%` }}
              />
              <div
                className="bg-[#d76f61]"
                style={{ width: `${(buckets.red / bucketTotal) * 100}%` }}
              />
            </div>
          </div>

          <div className="grid gap-4 xl:grid-cols-2">
            <div className="border border-[#e0ddd4] bg-white">
              <div className="border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3 text-xs font-semibold text-[#141413]">
                {t("verdictTitle")}
              </div>
              <div className="divide-y divide-[#eee9dd]">
                {summary.by_verdict.slice(0, 6).map((row) => (
                  <div key={row.verdict} className="flex items-center justify-between gap-3 px-4 py-3">
                    <div className="min-w-0">
                      <p className="truncate text-sm font-semibold text-[#141413]">
                        {verdictLabel(row.verdict, t)}
                      </p>
                      <p className="mt-1 font-mono text-xs text-[#77736a]">
                        {t("scoreRange", {
                          min: row.min_score ?? 0,
                          max: row.max_score ?? 0,
                          avg: (row.avg_score ?? 0).toFixed(1),
                        })}
                      </p>
                    </div>
                    <span className="shrink-0 border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5 font-mono text-xs text-[#141413]">
                      {row.total}
                    </span>
                  </div>
                ))}
              </div>
            </div>

            <div className="border border-[#e0ddd4] bg-white">
              <div className="border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3 text-xs font-semibold text-[#141413]">
                {t("gateFailureTitle")}
              </div>
              <div className="divide-y divide-[#eee9dd]">
                {summary.gate_failures.slice(0, 6).map((row) => (
                  <div key={row.gate} className="flex items-center justify-between gap-3 px-4 py-3">
                    <div className="min-w-0">
                      <p className="truncate text-sm font-semibold text-[#141413]">
                        {gateLabel(row.gate, t)}
                      </p>
                      <p className="mt-1 font-mono text-xs text-[#77736a]">
                        {Object.entries(row.statuses ?? {})
                          .map(([key, value]) => `${gateStatusLabel(key, t)}:${value}`)
                          .join(" / ") || "--"}
                      </p>
                    </div>
                    <span className="shrink-0 border border-[#d8d3c7] bg-[#faf9f3] px-2 py-0.5 font-mono text-xs text-[#141413]">
                      {row.total}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </section>
  );
}

export default function AwoooPPage() {
  const t = useTranslations("awooop.home");
  const locale = useLocale();
  const [snapshot, setSnapshot] = useState<Snapshot>(emptySnapshot);
  const [qualitySummary, setQualitySummary] = useState<AutomationQualitySummary | null>(null);
  const [qualityError, setQualityError] = useState(false);
  const [sourceFlowSummary, setSourceFlowSummary] = useState<SourceFlowSummary | null>(null);
  const [sourceFlowError, setSourceFlowError] = useState(false);
  const [status, setStatus] = useState<SnapshotStatus>("loading");
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);

  const fetchSnapshot = useCallback(async () => {
    setStatus("loading");
    try {
      const qualityParams = new URLSearchParams({
        project_id: "awoooi",
        hours: "24",
        limit: "50",
      });
      const sourceFlowParams = new URLSearchParams({
        project_id: "awoooi",
        limit: "100",
      });
      const [tenantRes, runRes, approvalRes, contractRes, qualityRes, sourceFlowRes] = await Promise.all([
        fetch(`${API_BASE}/api/v1/platform/tenants`),
        fetch(`${API_BASE}/api/v1/platform/runs/list?per_page=1`),
        fetch(`${API_BASE}/api/v1/platform/approvals`),
        fetch(`${API_BASE}/api/v1/platform/contracts?per_page=1`),
        fetch(`${API_BASE}/api/v1/platform/truth-chain/quality/summary?${qualityParams.toString()}`)
          .catch(() => null),
        fetch(`${API_BASE}/api/v1/platform/events/dossier/recurrence?${sourceFlowParams.toString()}`)
          .catch(() => null),
      ]);

      if (![tenantRes, runRes, approvalRes, contractRes].every((res) => res.ok)) {
        throw new Error("platform snapshot fetch failed");
      }

      const [tenantData, runData, approvalData, contractData] = await Promise.all([
        tenantRes.json() as Promise<PlatformResponse>,
        runRes.json() as Promise<PlatformResponse>,
        approvalRes.json() as Promise<PlatformResponse>,
        contractRes.json() as Promise<PlatformResponse>,
      ]);
      const tenants = Array.isArray(tenantData.tenants) ? tenantData.tenants : [];

      setSnapshot({
        tenants: countRows(tenantData, ["tenants", "items"]),
        activeTenants: tenants.filter((tenant) => tenant.is_active !== false).length,
        shadowTenants: tenants.filter((tenant) => tenant.migration_mode === "shadow").length,
        runs: countRows(runData, ["runs", "items"]),
        approvals: countRows(approvalData, ["items"]),
        contracts: countRows(contractData, ["contracts", "items"]),
      });
      if (qualityRes?.ok) {
        const qualityData = await qualityRes.json() as AutomationQualitySummary;
        setQualitySummary(qualityData);
        setQualityError(false);
      } else {
        setQualitySummary(null);
        setQualityError(true);
      }
      if (sourceFlowRes?.ok) {
        const sourceFlowData = await sourceFlowRes.json() as SourceFlowResponse;
        setSourceFlowSummary(sourceFlowData.summary);
        setSourceFlowError(false);
      } else {
        setSourceFlowSummary(null);
        setSourceFlowError(true);
      }
      setLastUpdated(new Date());
      setStatus("ready");
    } catch {
      setStatus("degraded");
      setQualitySummary(null);
      setQualityError(true);
      setSourceFlowSummary(null);
      setSourceFlowError(true);
      setLastUpdated(new Date());
    }
  }, []);

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

  const formattedUpdated = useMemo(() => {
    if (!lastUpdated) return "--";
    return lastUpdated.toLocaleTimeString(locale === "zh-TW" ? "zh-TW" : "en-US", {
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });
  }, [lastUpdated, locale]);

  const healthTone = status === "ready" ? "good" : status === "loading" ? "neutral" : "warn";

  return (
    <div className="space-y-5">
      <section className="border border-[#e0ddd4] bg-white">
        <div className="grid gap-px bg-[#e0ddd4] lg:grid-cols-[1.4fr_0.9fr]">
          <div className="bg-white p-5">
            <div className="flex flex-wrap items-start justify-between gap-4">
              <div className="max-w-3xl">
                <div className="flex items-center gap-2 text-xs font-semibold text-[#d97757]">
                  <BrainCircuit className="h-4 w-4" aria-hidden="true" />
                  <span>{t("eyebrow")}</span>
                </div>
                <h2 className="mt-3 text-2xl font-semibold tracking-normal text-[#141413]">
                  {t("title")}
                </h2>
                <p className="mt-3 max-w-2xl text-sm leading-6 text-[#5f5b52]">
                  {t("subtitle")}
                </p>
              </div>
              <button
                type="button"
                onClick={fetchSnapshot}
                className="inline-flex items-center gap-2 border border-[#d8d3c7] bg-[#faf9f3] px-3 py-2 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
                aria-label={t("refresh")}
              >
                <RefreshCw
                  className={cn("h-4 w-4", status === "loading" && "animate-spin")}
                  aria-hidden="true"
                />
                {t("refresh")}
              </button>
            </div>
          </div>

          <div className="bg-[#faf9f3] p-5">
            <div className="grid gap-3 text-sm">
              <div className="flex items-center justify-between gap-3">
                <span className="text-[#77736a]">{t("snapshotStatus")}</span>
                <span
                  className={cn(
                    "inline-flex border px-2 py-0.5 text-xs font-semibold",
                    healthTone === "good" && "border-[#9bc7a4] bg-[#f0faf2] text-[#17602a]",
                    healthTone === "warn" && "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
                    healthTone === "neutral" && "border-[#d8d3c7] bg-white text-[#5f5b52]"
                  )}
                >
                  {status === "ready" ? t("ready") : status === "loading" ? t("loading") : t("degraded")}
                </span>
              </div>
              <div className="flex items-center justify-between gap-3">
                <span className="text-[#77736a]">{t("lastUpdated")}</span>
                <span className="font-mono text-[#141413]">{formattedUpdated}</span>
              </div>
              <div className="flex items-center justify-between gap-3">
                <span className="text-[#77736a]">{t("migrationMode")}</span>
                <span className="font-mono text-[#141413]">{t("migrationValue")}</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
        <MetricCell
          label={t("metrics.tenants")}
          value={numberValue(snapshot.tenants)}
          detail={t("metrics.tenantsDetail", {
            active: numberValue(snapshot.activeTenants),
            shadow: numberValue(snapshot.shadowTenants),
          })}
          icon={Waypoints}
          tone="good"
        />
        <MetricCell
          label={t("metrics.runs")}
          value={numberValue(snapshot.runs)}
          detail={t("metrics.runsDetail")}
          icon={Activity}
          tone={snapshot.runs > 0 ? "good" : "neutral"}
        />
        <MetricCell
          label={t("metrics.approvals")}
          value={numberValue(snapshot.approvals)}
          detail={t("metrics.approvalsDetail")}
          icon={ShieldCheck}
          tone={snapshot.approvals > 0 ? "warn" : "good"}
        />
        <MetricCell
          label={t("metrics.contracts")}
          value={numberValue(snapshot.contracts)}
          detail={t("metrics.contractsDetail")}
          icon={FileText}
          tone={snapshot.contracts > 0 ? "good" : "warn"}
        />
      </section>

      <SourceFlowOverviewPanel
        summary={sourceFlowSummary}
        error={sourceFlowError}
        locale={locale}
      />

      <AutomationQualityPanel summary={qualitySummary} error={qualityError} />

      <SecurityMirrorPanel />

      <GitHubPrimaryReadinessHomePanel />

      <OwnerResponseValidationRollupPanel />

      <HighValueConfigOwnerPacketHomePanel />

      <section className="border border-[#e0ddd4] bg-[#e0ddd4]">
        <div className="border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
          <div className="flex items-center gap-2">
            <ListChecks className="h-4 w-4 text-[#d97757]" aria-hidden="true" />
            <h3 className="text-sm font-semibold text-[#141413]">
              {t("disposition.title")}
            </h3>
          </div>
        </div>
        <div className="grid gap-px md:grid-cols-2 xl:grid-cols-4">
          <DispositionCell
            title={t("disposition.diagnosis.title")}
            signal={t("disposition.diagnosis.signal")}
            owner={t("disposition.diagnosis.owner")}
            route={t("disposition.diagnosis.route")}
            tone="diagnosis"
            icon={SearchCheck}
          />
          <DispositionCell
            title={t("disposition.approval.title")}
            signal={t("disposition.approval.signal")}
            owner={t("disposition.approval.owner")}
            route={t("disposition.approval.route")}
            tone="approval"
            icon={ShieldCheck}
          />
          <DispositionCell
            title={t("disposition.execute.title")}
            signal={t("disposition.execute.signal")}
            owner={t("disposition.execute.owner")}
            route={t("disposition.execute.route")}
            tone="execute"
            icon={Activity}
          />
          <DispositionCell
            title={t("disposition.manual.title")}
            signal={t("disposition.manual.signal")}
            owner={t("disposition.manual.owner")}
            route={t("disposition.manual.route")}
            tone="manual"
            icon={TriangleAlert}
          />
        </div>
      </section>

      <section className="grid gap-5 xl:grid-cols-[1.1fr_0.9fr]">
        <div className="border border-[#e0ddd4] bg-white">
          <div className="border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
            <div className="flex items-center gap-2">
              <GitBranch className="h-4 w-4 text-[#d97757]" aria-hidden="true" />
              <h3 className="text-sm font-semibold text-[#141413]">{t("lanes.title")}</h3>
            </div>
          </div>
          <LaneRow
            name={t("lanes.providerName")}
            status={t("lanes.live")}
            detail={t("lanes.providerDetail")}
            tone="good"
          />
          <LaneRow
            name={t("lanes.mcpName")}
            status={t("lanes.mirror")}
            detail={t("lanes.mcpDetail")}
            tone="warn"
          />
          <LaneRow
            name={t("lanes.channelName")}
            status={t("lanes.mirror")}
            detail={t("lanes.channelDetail")}
            tone="warn"
          />
          <LaneRow
            name={t("lanes.approvalName")}
            status={t("lanes.live")}
            detail={t("lanes.approvalDetail")}
            tone="good"
          />
        </div>

        <div className="border border-[#e0ddd4] bg-white">
          <div className="border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
            <div className="flex items-center gap-2">
              <CheckCircle2 className="h-4 w-4 text-[#d97757]" aria-hidden="true" />
              <h3 className="text-sm font-semibold text-[#141413]">{t("next.title")}</h3>
            </div>
          </div>
          <div className="divide-y divide-[#eee9dd]">
            {[
              [t("next.item1"), "/awooop/runs" as const],
              [t("next.item2"), "/awooop/approvals" as const],
              [t("next.item3"), "/awooop/contracts" as const],
              [t("next.item4"), "/awooop/work-items" as const],
            ].map(([label, href]) => (
              <Link
                key={String(label)}
                href={href}
                className="flex items-center justify-between gap-3 px-4 py-3 text-sm text-[#141413] hover:bg-[#faf9f3]"
              >
                <span>{label}</span>
                <ArrowRight className="h-4 w-4 text-[#77736a]" aria-hidden="true" />
              </Link>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}
