// ---------------------------------------------------------------------------
// Live-tail status pill (sub-project 5, Phase 5 Task 21).
//
// Tiny presentational component used in the toolbar of `Claims`,
// `Remittances`, and `ActivityLog` to surface the connection status of
// `useTailStream`. Renders a status dot + label + "Last event: 12s ago"
// subtitle that re-ticks every second, plus a "↻ Reconnect" button
// that only appears when the connection has visibly failed (`stalled`
// or `error`).
// ---------------------------------------------------------------------------

import { RotateCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  StatusPill,
  formatAge,
  useTickingNow,
  type ConnectionStatus,
} from "@/components/StatusPill";
import type { TailStatus } from "@/hooks/useTailStream";

export interface TailStatusPillProps {
  status: TailStatus;
  lastEventAt: Date | null;
  onReconnect: () => void;
}

const STATUS_LABEL: Record<TailStatus, string> = {
  connecting: "Connecting",
  live: "Live",
  reconnecting: "Reconnecting",
  closed: "Closed",
  stalled: "Stalled",
  error: "Error",
};

export function TailStatusPill({
  status,
  lastEventAt,
  onReconnect,
}: TailStatusPillProps): React.JSX.Element {
  const now = useTickingNow(1000);
  const ageSeconds = lastEventAt
    ? Math.max(0, Math.floor((now - lastEventAt.getTime()) / 1000))
    : null;

  const subtitle =
    ageSeconds === null
      ? "Last event: never"
      : `Last event: ${formatAge(ageSeconds)} ago`;

  const showReconnect = status === "stalled" || status === "error";

  return (
    <div
      className="inline-flex items-center gap-2.5"
      data-testid="tail-status-pill"
    >
      <StatusPill
        status={status as ConnectionStatus}
        label={STATUS_LABEL[status]}
      />
      <span
        className="mono text-[10.5px] text-muted-foreground hidden sm:inline"
        data-testid="tail-status-pill-subtitle"
      >
        {subtitle}
      </span>
      {showReconnect ? (
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={onReconnect}
          data-testid="tail-status-pill-reconnect"
        >
          <RotateCw className="h-3 w-3" strokeWidth={2} />
          Reconnect
        </Button>
      ) : null}
    </div>
  );
}
