/**
 * Map a site locale (`"en"` / `"fr"`) to a BCP-47 tag for `Intl` formatting.
 * Anything other than `"fr"` falls back to British English.
 *
 * @param locale - The active site locale.
 * @returns The matching `Intl` locale tag (`"fr-FR"` or `"en-GB"`).
 */
function loc(locale: string) {
  return locale === "fr" ? "fr-FR" : "en-GB";
}

/**
 * Format an ISO date string for display, localized to the active locale.
 * Returns `""` for a missing value or an unparseable date, so the result is
 * always safe to render directly.
 *
 * @param value - ISO date string (e.g. from Sanity). Optional.
 * @param locale - Site locale; defaults to `"en"`.
 * @param opts - `Intl.DateTimeFormat` options; defaults to numeric day / long month / numeric year.
 * @returns The localized date string, or `""` if it cannot be formatted.
 */
export function formatDate(
  value?: string,
  locale = "en",
  opts?: Intl.DateTimeFormatOptions,
) {
  if (!value) return "";
  try {
    return new Intl.DateTimeFormat(
      loc(locale),
      opts ?? { day: "numeric", month: "long", year: "numeric" },
    ).format(new Date(value));
  } catch {
    return "";
  }
}

/**
 * Format a start–end time span as localized `HH:MM` (e.g. `"09:00 – 11:00"`).
 * With no end time, only the start time is returned; `""` is returned when
 * there is no start time or a value cannot be parsed.
 *
 * @param start - ISO start datetime. Optional.
 * @param end - ISO end datetime. Optional.
 * @param locale - Site locale; defaults to `"en"`.
 * @returns The localized time range, a single time, or `""`.
 */
export function formatTimeRange(start?: string, end?: string, locale = "en") {
  if (!start) return "";
  const t = (d: string) =>
    new Intl.DateTimeFormat(loc(locale), {
      hour: "2-digit",
      minute: "2-digit",
    }).format(new Date(d));
  try {
    return end ? `${t(start)} – ${t(end)}` : t(start);
  } catch {
    return "";
  }
}
