// Per-region entries of one run (the run.json view): status, last stage,
// wall-clock duration, and — the reason this table exists — the persisted
// failure cause. Error text is the raw message the runner captured (client
// timeouts, dataplane responses), so it renders monospaced and clamped.

import type { RunRegionEntry } from "@/lib/api-types";
import { utc8Stamp } from "@/lib/fmt";
import { DataTable, Td, Th } from "@/components/ui/DataTable";
import { Empty } from "@/components/ui/Empty";
import { Badge } from "@/components/ui/Badge";
import { RegionStatusBadge } from "@/components/runs/RunBadges";

/** Wall-clock seconds between the entry's stamps, when both exist. */
function durationOf(entry: RunRegionEntry): number | null {
  if (!entry.startedAt || !entry.finishedAt) return null;
  const seconds = (Date.parse(entry.finishedAt) - Date.parse(entry.startedAt)) / 1000;
  return Number.isFinite(seconds) ? seconds : null;
}

export function RunRegionTable({ entries }: { entries: RunRegionEntry[] }) {
  if (entries.length === 0) {
    return <Empty>No regions recorded for this run.</Empty>;
  }
  return (
    <DataTable>
      <thead>
        <tr>
          <Th>Region</Th>
          <Th>Status</Th>
          <Th>Stage</Th>
          <Th>Finished</Th>
          <Th numeric>Duration</Th>
          <Th>Error</Th>
        </tr>
      </thead>
      <tbody>
        {entries.map((entry) => {
          const duration = durationOf(entry);
          return (
            <tr key={entry.regionKey} className="hover:bg-surface-1">
              <Td><span className="font-mono text-xs">{entry.regionKey}</span></Td>
              <Td>
                <span className="inline-flex items-center gap-1.5">
                  <RegionStatusBadge status={entry.status} />
                  {entry.degradedStages?.includes("shrink") ? (
                    <Badge tone="warn">shrink degraded</Badge>
                  ) : null}
                </span>
              </Td>
              <Td><span className="text-text-secondary">{entry.stage ?? "—"}</span></Td>
              <Td>
                <span className="text-text-secondary">
                  {entry.finishedAt ? utc8Stamp(entry.finishedAt) : "—"}
                </span>
              </Td>
              <Td numeric>
                <span className="text-text-secondary">
                  {duration === null ? "—" : `${duration.toFixed(1)}s`}
                </span>
              </Td>
              <Td>
                {entry.error ? (
                  <span className="block max-h-24 max-w-[36rem] overflow-y-auto break-all font-mono text-xs text-danger">
                    {entry.error}
                  </span>
                ) : (
                  <span className="text-text-muted">—</span>
                )}
              </Td>
            </tr>
          );
        })}
      </tbody>
    </DataTable>
  );
}
