/** Pad number to 2 digits */
export const pad = (n: number): string => String(Math.max(0, n)).padStart(2, '0');

/** Format seconds as human-readable duration: "1h 23m 45s" */
export const fmt = (s: number): string => {
  if (!isFinite(s) || s < 0) return '—';
  const h = Math.floor(s / 3600);
  const m = Math.floor((s % 3600) / 60);
  const ss = Math.floor(s % 60);
  return h > 0 ? `${h}h ${pad(m)}m ${pad(ss)}s` : m > 0 ? `${m}m ${pad(ss)}s` : `${ss}s`;
};

/** Format seconds as clock: "01:23:45" */
export const fmtClock = (s: number): string => {
  if (!isFinite(s) || isNaN(s) || s < 0) return '--:--:--';
  return `${pad(Math.floor(s / 3600))}:${pad(Math.floor((s % 3600) / 60))}:${pad(Math.floor(s % 60))}`;
};

/** Escape HTML special characters */
export const esc = (s: string | number): string =>
  String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
