// src/lib/support/relative-time.ts — French relative-time formatting for tickets.

const RELATIVE = new Intl.RelativeTimeFormat("fr-FR", { numeric: "auto" });
const RELATIVE_UNITS: [Intl.RelativeTimeFormatUnit, number][] = [
  ["year", 1000 * 60 * 60 * 24 * 365],
  ["month", 1000 * 60 * 60 * 24 * 30],
  ["day", 1000 * 60 * 60 * 24],
  ["hour", 1000 * 60 * 60],
  ["minute", 1000 * 60],
];

/** « il y a … » for a date (e.g. "il y a 3 heures"); "à l'instant" if very recent. */
export function relativeTime(d: Date | string): string {
  const diff = new Date(d).getTime() - Date.now();
  const abs = Math.abs(diff);
  for (const [unit, ms] of RELATIVE_UNITS) {
    if (abs >= ms) return RELATIVE.format(Math.round(diff / ms), unit);
  }
  return "à l'instant";
}
