/**
 * Pin a formatting locale to Western digits.
 *
 * Money is formatted with the *currency's* regional locale (BDT → bn-BD,
 * SAR → ar-SA) so the symbol, separators and symbol placement match the
 * currency — but that locale also carries a native numbering system, which
 * would print Bengali (১,২৩৪৳) or Arabic-Indic (١٬٢٣٤) numerals on an English
 * store. The currency is not a language choice, so digits stay Latin.
 */
function withLatinDigits(locale?: string): string | undefined {
  if (!locale) return locale;
  try {
    return new Intl.Locale(locale, { numberingSystem: "latn" }).toString();
  } catch {
    // Structurally invalid tag — Intl.NumberFormat would reject it too, so
    // fall back to the runtime default instead of throwing.
    return undefined;
  }
}

export function formatCurrency(
  amount: number,
  currency: string,
  locale?: string,
  options?: Intl.NumberFormatOptions,
): string {
  const safeAmount = Number.isFinite(amount) ? amount : 0;
  const currencyCode = (currency || "USD").toUpperCase();
  const formatLocale = withLatinDigits(locale);

  try {
    return new Intl.NumberFormat(formatLocale, {
      style: "currency",
      currency: currencyCode,
      ...options,
    }).format(safeAmount);
  } catch {
    const formatted = new Intl.NumberFormat(formatLocale, {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }).format(safeAmount);
    return `${formatted} ${currencyCode}`;
  }
}

