import { formatNumber, localeTag } from '@/utils';

/**
 * Shared time formatters for the booking composites. Timestamps cross the wire as UTC ISO; these render
 * a locale clock (Persian digits for `fa`) for the EVV banner + session schedule. Kept internal to the
 * booking components — money/date-of formatting lives in `@/utils`; this is only the clock/duration view.
 */

/** `HH:MM` for a UTC ISO instant in the active locale (Persian digits for `fa`). */
export function formatClock(iso: string, locale: string): string {
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return '';
  return new Intl.DateTimeFormat(localeTag(locale), {
    hour: '2-digit',
    minute: '2-digit',
  }).format(date);
}

/** `HH:MM` for a `HH:mm:ss` wire time, in the active locale. */
export function formatTimeOfDay(time: string, locale: string): string {
  const [h, m] = time.split(':');
  if (h == null || m == null) return time;
  const nf = new Intl.NumberFormat(localeTag(locale), {
    minimumIntegerDigits: 2,
    useGrouping: false,
  });
  return `${nf.format(Number(h))}:${nf.format(Number(m))}`;
}

/** The `HH:MM`-range label for a session's scheduled window, in the active locale. */
export function formatTimeRange(start: string, end: string, locale: string): string {
  return `${formatTimeOfDay(start, locale)} – ${formatTimeOfDay(end, locale)}`;
}

/**
 * The elapsed on-site duration between two UTC ISO instants, as `H:MM` in the active locale. Returns
 * `null` when either endpoint is missing (e.g. an open check-in with no check-out yet).
 */
export function formatElapsed(startIso: string | null, endIso: string | null, locale: string): string | null {
  if (!startIso || !endIso) return null;
  const start = new Date(startIso).getTime();
  const end = new Date(endIso).getTime();
  if (Number.isNaN(start) || Number.isNaN(end) || end < start) return null;
  const totalMinutes = Math.round((end - start) / 60_000);
  const hours = Math.floor(totalMinutes / 60);
  const minutes = totalMinutes % 60;
  return `${formatNumber(hours, locale, { useGrouping: false })}:${formatNumber(minutes, locale, {
    minimumIntegerDigits: 2,
    useGrouping: false,
  })}`;
}
