const formatterCache = new Map<string, Intl.NumberFormat>();

export const getFormatter = (locale: string) => {
  const cached = formatterCache.get(locale);
  if (cached) {
    return cached;
  }
  const formatter = new Intl.NumberFormat(locale, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
  formatterCache.set(locale, formatter);
  return formatter;
};

const decimalSeparatorCache = new Map<string, string>();

const getDecimalSeparator = (locale: string) => {
  const cached = decimalSeparatorCache.get(locale);
  if (cached !== undefined) {
    return cached;
  }
  const probe = getFormatter(locale).format(1.1);
  const separator = probe.replace(/\d/g, '');
  decimalSeparatorCache.set(locale, separator);
  return separator;
};

export const splitCurrencyParts = (locale: string, amount: number) => {
  const formatted = getFormatter(locale).format(amount);
  const separator = getDecimalSeparator(locale);
  const sepIndex = separator ? formatted.lastIndexOf(separator) : -1;
  if (sepIndex === -1) {
    return {integerText: formatted, fractionText: ''};
  }
  return {
    integerText: formatted.slice(0, sepIndex),
    fractionText: formatted.slice(sepIndex + separator.length),
  };
};
