/**
 * Locale-aware date/number formatters that ALWAYS render Latin (0-9) digits,
 * even when the active language is Arabic. Month and weekday names still
 * localize to Arabic as expected.
 */

function withLatn(locale: string): string {
  return locale.includes("-u-") ? `${locale}-nu-latn` : `${locale}-u-nu-latn`;
}

function baseLocale(lang: string): string {
  return lang === "ar" ? "ar" : "en-US";
}

export function formatTime(
  date: Date | string | number,
  lang: string,
  options: Intl.DateTimeFormatOptions = { hour: "2-digit", minute: "2-digit" },
): string {
  const d = date instanceof Date ? date : new Date(date);
  const hour12 = options.hour12 ?? false;
  return new Intl.DateTimeFormat(withLatn(baseLocale(lang)), {
    ...options,
    hour12,
    numberingSystem: "latn",
  }).format(d);
}

export function formatDate(
  date: Date | string | number,
  lang: string,
  options: Intl.DateTimeFormatOptions = {
    day: "numeric",
    month: "long",
    year: "numeric",
  },
): string {
  const d = date instanceof Date ? date : new Date(date);
  return new Intl.DateTimeFormat(withLatn(baseLocale(lang)), {
    ...options,
    numberingSystem: "latn",
  }).format(d);
}

export function formatHijri(
  date: Date | string | number,
  lang: string,
  options: Intl.DateTimeFormatOptions = {
    day: "numeric",
    month: "long",
    year: "numeric",
  },
): string {
  const d = date instanceof Date ? date : new Date(date);
  const loc = lang === "ar" ? "ar-u-ca-islamic-umalqura-nu-latn" : "en-u-ca-islamic-umalqura-nu-latn";
  return new Intl.DateTimeFormat(loc, {
    ...options,
    numberingSystem: "latn",
  }).format(d);
}

export function formatWeekday(
  date: Date | string | number,
  lang: string,
  weekday: "long" | "short" | "narrow" = "long",
): string {
  const d = date instanceof Date ? date : new Date(date);
  return new Intl.DateTimeFormat(withLatn(baseLocale(lang)), {
    weekday,
    numberingSystem: "latn",
  }).format(d);
}

export function formatDateTime(
  date: Date | string | number,
  lang: string,
  hour12: boolean = false,
): string {
  const d = date instanceof Date ? date : new Date(date);
  return new Intl.DateTimeFormat(withLatn(baseLocale(lang)), {
    dateStyle: "medium",
    timeStyle: "short",
    numberingSystem: "latn",
    hour12,
  }).format(d);
}

export function formatNumber(value: number, lang: string): string {
  return new Intl.NumberFormat(withLatn(baseLocale(lang)), {
    numberingSystem: "latn",
  }).format(value);
}

/**
 * Localized time-of-day greeting key. Uses the local hour to pick one of
 * "morning", "afternoon", or "evening". Caller provides the i18n strings.
 */
export function greetingKey(date: Date = new Date()): "morning" | "afternoon" | "evening" {
  const h = date.getHours();
  if (h < 12) return "morning";
  if (h < 18) return "afternoon";
  return "evening";
}
