import type { WidgetTranslations } from '../i18n';

const MS_PER_DAY = 24 * 60 * 60 * 1000;

/** Local midnight, so the label follows calendar days rather than 24h blocks. */
function startOfDay(date: Date): number {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
}

/**
 * "Today" and "Yesterday" for the recent try-ons a shopper actually thinks
 * about, a written date for everything older.
 */
export function formatTryOnDate(
  iso: string,
  t: WidgetTranslations['gallery'],
  now: Date = new Date()
): string {
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return '';

  // Rounded because a DST boundary makes the gap 23 or 25 hours.
  const days = Math.round((startOfDay(now) - startOfDay(date)) / MS_PER_DAY);
  if (days === 0) return t.today;
  if (days === 1) return t.yesterday;
  return t.formatDate(date);
}
