export type CountdownStage = 'cool' | 'warm' | 'hot' | 'expired';

export interface TimeLabels {
  days?: string;
  hours?: string;
  minutes?: string;
  seconds?: string;
}

const DEFAULT_LABELS: Required<TimeLabels> = {
  days: 'd',
  hours: 'h',
  minutes: 'm',
  seconds: 's',
};

/** Seconds until an ISO end time. Returns 0 if already expired. */
export function getSecondsUntil(isoEnd: string): number {
  return Math.max(0, Math.floor((new Date(isoEnd).getTime() - Date.now()) / 1000));
}

/** Stage thresholds: >=3600 cool, >=600 warm, >0 hot, 0 expired. */
export function getCountdownStage(secs: number): CountdownStage {
  if (secs <= 0) return 'expired';
  if (secs < 600) return 'hot';
  if (secs < 3600) return 'warm';
  return 'cool';
}

/**
 * Format seconds into human-readable countdown string.
 * Returns { text: '2h 15m', hasWords: true } or { text: '00:45', hasWords: false }.
 */
export function formatCountdownSeconds(
  secs: number,
  labels: TimeLabels = {},
): { text: string; hasWords: boolean } {
  const L = { ...DEFAULT_LABELS, ...labels };

  if (secs <= 0) return { text: `0${L.seconds}`, hasWords: true };

  const d = Math.floor(secs / 86400);
  const h = Math.floor((secs % 86400) / 3600);
  const m = Math.floor((secs % 3600) / 60);
  const s = secs % 60;

  if (d > 0) return { text: `${d}${L.days} ${h}${L.hours}`, hasWords: true };
  if (h > 0) return { text: `${h}${L.hours} ${m}${L.minutes}`, hasWords: true };
  if (m > 0) return { text: `${m}${L.minutes} ${s}${L.seconds}`, hasWords: true };
  const mm = String(m).padStart(2, '0');
  const ss = String(s).padStart(2, '0');
  return { text: `${mm}:${ss}`, hasWords: false };
}