import { NUMBER_MAX_DECIMAL_PLACES } from '../Number/NumberInput.types';
import { getFormattedValue as getNumberFormattedValue } from '../Number/utils';
export const isValidCurrency = (currency) => {
    try {
        // eslint-disable-next-line no-new
        new Intl.NumberFormat(undefined, { style: 'currency', currency });
        return true;
    }
    catch {
        return false;
    }
};
export const getFormattedValue = (value, locale, currency, { showGroupSeparators = true, showAs = 'code', numberOfDecimals } = {}) => {
    const [integer, fractionPart] = value.split('.', 2);
    if (!currency)
        return getNumberFormattedValue(value, locale, undefined, {
            useGrouping: showGroupSeparators,
            maximumFractionDigits: numberOfDecimals,
            minimumFractionDigits: Math.min(numberOfDecimals ?? 0, fractionPart?.length ?? 0)
        });
    const isCurrency = isValidCurrency(currency);
    const formatter = new Intl.NumberFormat(locale, {
        useGrouping: showGroupSeparators,
        maximumFractionDigits: numberOfDecimals,
        minimumFractionDigits: Math.min(numberOfDecimals ?? 0, fractionPart?.length ?? 0),
        ...(isCurrency
            ? {
                style: 'currency',
                currency,
                currencyDisplay: showAs
            }
            : {}),
        numberingSystem: 'latn'
    });
    let formatted = value;
    if (value && !Number.isNaN(parseFloat(integer))) {
        const endsWithDot = fractionPart === '';
        const valueNumber = endsWithDot ? `${value}1` : value;
        // @ts-expect-error https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts#number
        formatted = formatter.formatToParts(valueNumber).reduce((result, { type, value: part }) => {
            if (type === 'fraction' && endsWithDot)
                return result;
            return result + part;
        }, '');
    }
    else if (currency) {
        formatted = formatter
            .formatToParts(value.startsWith('-') ? -1 : 1)
            .reduce((result, { type, value: part }) => ['currency', 'minusSign'].includes(type) ? result + part : result, '');
    }
    return formatted;
};
export function getCurrencyMinimumFractionDigits(locale, currencyISOCode) {
    return currencyISOCode
        ? new Intl.NumberFormat(locale, {
            style: 'currency',
            currency: currencyISOCode
        }).resolvedOptions().minimumFractionDigits
        : NUMBER_MAX_DECIMAL_PLACES;
}
export function formatCurrency(value, { locale, options }) {
    const formatter = new Intl.NumberFormat(locale, options);
    return formatter.format(value);
}
//# sourceMappingURL=utils.js.map