import { cn } from "@/lib/cn";
import { formatDateTime, formatResponseTime } from "@/lib/format";
import { STATUS_LABELS } from "@/lib/status";
import type { RecentOutcome } from "@/server/health/history";

const BLOCK: Record<RecentOutcome["status"], string> = {
  WORKING: "bg-emerald-500",
  SLOW: "bg-amber-500",
  NOT_WORKING: "bg-red-500",
};

/**
 * The latest checks as a row of blocks, oldest on the left. Each block carries
 * its full detail as a tooltip; the table below the strip has the same data.
 */
export function StatusTimeline({ outcomes, tz }: { outcomes: RecentOutcome[]; tz: string }) {
  if (outcomes.length === 0) return null;
  return (
    <div>
      <ol className="flex h-6 items-stretch gap-px" aria-label={`Latest ${outcomes.length} checks, oldest first`}>
        {outcomes.map((outcome) => (
          <li
            key={outcome.id}
            className={cn("min-w-0.5 flex-1 rounded-[1px]", BLOCK[outcome.status])}
            title={`${formatDateTime(outcome.checkedAt, tz)} — ${STATUS_LABELS[outcome.status]}${
              outcome.responseTimeMs !== null ? `, ${formatResponseTime(outcome.responseTimeMs)}` : ""
            }`}
          >
            <span className="sr-only">
              {formatDateTime(outcome.checkedAt, tz)}: {STATUS_LABELS[outcome.status]}
            </span>
          </li>
        ))}
      </ol>
      <div className="mt-1.5 flex items-center justify-between text-[11px] text-slate-500">
        <span>{formatDateTime(outcomes[0].checkedAt, tz)}</span>
        <span className="flex items-center gap-3">
          {(["WORKING", "SLOW", "NOT_WORKING"] as const).map((status) => (
            <span key={status} className="flex items-center gap-1">
              <span className={cn("size-2 rounded-full", BLOCK[status])} aria-hidden />
              {STATUS_LABELS[status]}
            </span>
          ))}
        </span>
        <span>{formatDateTime(outcomes[outcomes.length - 1].checkedAt, tz)}</span>
      </div>
    </div>
  );
}
