// Time formatting shared by the export formatters and the UI. Pure & tested.

/**
 * Format seconds as a subtitle timecode `HH:MM:SS<sep>mmm`.
 * @param sep millisecond separator: `,` for SRT, `.` for WebVTT.
 */
export function formatTimecode(totalSeconds: number, sep: ',' | '.' = '.'): string {
  const safe = Number.isFinite(totalSeconds) && totalSeconds > 0 ? totalSeconds : 0;
  const ms = Math.round(safe * 1000);
  const hours = Math.floor(ms / 3_600_000);
  const minutes = Math.floor((ms % 3_600_000) / 60_000);
  const seconds = Math.floor((ms % 60_000) / 1000);
  const millis = ms % 1000;
  return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}${sep}${pad(millis, 3)}`;
}

/** Short human clock for UI / Markdown: `m:ss` or `h:mm:ss`. */
export function formatClock(totalSeconds: number): string {
  const safe = Number.isFinite(totalSeconds) && totalSeconds > 0 ? totalSeconds : 0;
  const whole = Math.floor(safe);
  const hours = Math.floor(whole / 3600);
  const minutes = Math.floor((whole % 3600) / 60);
  const seconds = whole % 60;
  return hours > 0
    ? `${hours}:${pad(minutes)}:${pad(seconds)}`
    : `${minutes}:${pad(seconds)}`;
}

function pad(n: number, width = 2): string {
  return String(n).padStart(width, '0');
}
