import { jsx as _jsx } from "react/jsx-runtime";
import { forwardRef } from 'react';
import styled, { css } from 'styled-components';
import { rgba } from 'polished';
import { defaultThemeProp } from '../../theme';
import { tryCatch, withTestIds } from '../../utils';
import { calculateFontSize } from '../../styles';
import { useTestIds } from '../../hooks';
import { getCountTestIds } from './Badges.test-ids';
export const StyledCount = styled.span(({ theme, variant, children }) => {
    const { foreground, background } = theme.components.badges.count[variant];
    const shadow = tryCatch(() => rgba(foreground, 0.1));
    const fontSize = calculateFontSize(theme.base['font-size'], theme.base['font-scale']);
    return css `
    display: inline-block;
    block-size: 1rem;
    flex-shrink: 0;
    border-radius: calc(9999 * ${theme.base['border-radius']});
    color: ${foreground};
    background-color: ${background};
    box-shadow: inset 0 0 0 0.0625rem ${shadow};
    font-size: ${fontSize.xxs};
    font-weight: ${theme.base['font-weight'].bold};
    line-height: 1rem;
    text-align: center;
    white-space: nowrap;

    ${children.length === 1
        ? css `
          aspect-ratio: 1 / 1;
        `
        : css `
          padding-inline: ${theme.base.spacing};
        `}
  `;
});
StyledCount.defaultProps = defaultThemeProp;
// Replace this with Intl.NumberFormat when roundingMode is supported.
/* eslint-disable yoda */
const getLabel = (val) => {
    if (val < 1_000)
        return '';
    if (1_000 <= val && val < 1_000_000)
        return 'K';
    if (1_000_000 <= val && val < 1_000_000_000)
        return 'M';
    if (1_000_000_000 <= val && val < 1_000_000_000_000)
        return 'B';
    if (1_000_000_000_000 <= val && val < 1_000_000_000_000_000)
        return 'T';
    return '';
};
/* eslint-enable yoda */
const truncateValue = (val) => {
    for (let magnitude = 3; magnitude < 15; magnitude += 3) {
        if (val < 10 ** (magnitude + 1)) {
            return `${`${val}`.slice(0, 1)}.${`${val}`.slice(1, 2)}${getLabel(val)}`;
        }
        if (val < 10 ** (magnitude + 2)) {
            return `${`${val}`.slice(0, 2)}${getLabel(val)}`;
        }
        if (val < 10 ** (magnitude + 3)) {
            return `${`${val}`.slice(0, 3)}${getLabel(val)}`;
        }
    }
    return '999T+';
};
const formatValue = (val) => {
    const absVal = Math.abs(val);
    if (absVal < 1_000)
        return `${val}`;
    return `${val < 0 ? '-' : ''}${truncateValue(absVal)}`;
};
export default withTestIds(forwardRef(function Count({ testId, variant = 'default', children, ...restProps }, ref) {
    const testIds = useTestIds(testId, getCountTestIds);
    return Number.isInteger(children) ? (_jsx(StyledCount, { "data-testid": testIds.root, variant: variant, ...restProps, ref: ref, children: formatValue(children) })) : null;
}), getCountTestIds);
//# sourceMappingURL=Count.js.map