import { GAP_BETWEEN_TAGS, MIN_AVAILABLE_WIDTH } from '../../constants';
import { getTagWidth } from '../getTagWidth';
/**
 * Вычисляет количество тегов, которые могут поместиться в доступную ширину
 * с учетом пробелов между тегами и счетчика оставшихся элементов
 */
export const calculateVisibleTagsCount = (tagLabels, availableWidth, theme) => {
    if (!tagLabels.length || availableWidth <= 0) {
        return 0;
    }
    const tagWidths = tagLabels.map((label) => getTagWidth(label, theme));
    const canFitTagAtIndex = (tagIndex, accumulatedWidth) => {
        const isFirstTag = tagIndex === 0;
        const gapWidth = isFirstTag ? 0 : GAP_BETWEEN_TAGS;
        const tagsAfterCurrent = tagLabels.length - (tagIndex + 1);
        const counterTagWidth = tagsAfterCurrent > 0
            ? getTagWidth(`+${tagsAfterCurrent}`, theme, true) + GAP_BETWEEN_TAGS
            : 0;
        const totalWidthWithTag = accumulatedWidth + gapWidth + tagWidths[tagIndex];
        return totalWidthWithTag + counterTagWidth <= availableWidth;
    };
    const fittingTagIndex = tagWidths.findIndex((_, index) => {
        const widthBeforeCurrentTag = tagWidths
            .slice(0, index)
            .reduce((sum, width, i) => sum + width + (i > 0 ? GAP_BETWEEN_TAGS : 0), 0);
        return !canFitTagAtIndex(index, widthBeforeCurrentTag);
    });
    const visibleTagsCount = fittingTagIndex === -1 ? tagLabels.length : fittingTagIndex;
    if (visibleTagsCount === 0) {
        const counterWidthAlone = getTagWidth(`+${tagLabels.length}`, theme);
        const remainingAfterCounter = availableWidth - counterWidthAlone;
        return remainingAfterCounter < MIN_AVAILABLE_WIDTH ? 0 : 1;
    }
    return visibleTagsCount;
};
