/** Always 24-hour clock (00–23), no AM/PM. */
export const CLOCK_TIME_OPTIONS: Intl.DateTimeFormatOptions = {
  hour: "2-digit",
  minute: "2-digit",
  hour12: false,
  hourCycle: "h23",
};

/** Normalize API/UI time strings to `HH:mm` (24h). */
export function normalizeClockTime(value?: string | null): string {
  if (!value) return "";
  const match = String(value).trim().match(/^(\d{1,2}):(\d{2})(?::\d{2})?/);
  if (!match) return "";
  const hour = Math.min(23, Math.max(0, Number(match[1])));
  const minute = Math.min(59, Math.max(0, Number(match[2])));
  return `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`;
}

/** Format a Date/ISO string as 24h clock (`HH:mm`). Falls back to normalizing `HH:mm[:ss]`. */
export function formatClockTime(value?: string | Date | null): string {
  if (value == null || value === "") return "";
  if (typeof value === "string") {
    const asClock = normalizeClockTime(value);
    if (asClock && !/[T\s]/.test(value.trim()) && value.trim().length <= 8) {
      return asClock;
    }
  }
  const date = value instanceof Date ? value : new Date(value);
  if (Number.isNaN(date.getTime())) {
    return typeof value === "string" ? normalizeClockTime(value) : "";
  }
  return date.toLocaleTimeString("en-GB", CLOCK_TIME_OPTIONS);
}
