'use strict';

var React = require('react');
var classnames = require('classnames');
var InlineLabel = require('./InlineLabel-cjs.js');
var Text = require('./Text-cjs.js');

var styles = {"tagWrapper":"ld5hWlraYD8-","tags":"yi316XKxcHc-","tagsMask":"OHjlxTgwQMM-","tagCount":"uUuTxKoLb5k-","spinning":"mlKQ8-cSttI-"};

function DataListTags({ items }) {
    const ref = React.useRef(null);
    const [visibleIndex, setVisibleIndex] = React.useState([]);
    const visibleItems = visibleIndex.filter(Boolean).length;
    const shouldShowTagCount = Boolean(visibleItems);
    React.useEffect(() => {
        var _a;
        if (!window.IntersectionObserver)
            return;
        setVisibleIndex([]);
        const observer = new IntersectionObserver(handleIntersection, {
            root: ref.current,
            threshold: buildIntersectionThreshold(items),
        });
        const elements = (_a = ref.current) === null || _a === void 0 ? void 0 : _a.querySelectorAll("[data-tag-element]");
        elements === null || elements === void 0 ? void 0 : elements.forEach(element => observer.observe(element));
        return () => {
            elements === null || elements === void 0 ? void 0 : elements.forEach(element => observer.unobserve(element));
        };
    }, [items]);
    return (React.createElement("div", { className: styles.tagWrapper, ref: ref },
        React.createElement("div", { className: classnames(styles.tags, {
                [styles.tagsMask]: shouldShowTagCount,
            }) }, items.filter(Boolean).map((tag, index) => (React.createElement("div", { key: tag, "data-tag-element": index },
            React.createElement(InlineLabel.InlineLabel, null, tag))))),
        shouldShowTagCount && (React.createElement("div", { className: styles.tagCount },
            React.createElement(Text.Text, null,
                "+",
                visibleItems)))));
    function handleIntersection(...[entries]) {
        entries.forEach(entry => {
            const index = entry.target.getAttribute("data-tag-element");
            const indexNumber = Number(index);
            if (!index || isNaN(indexNumber))
                return;
            setVisibleIndex(prevState => {
                const newState = [...prevState];
                newState[indexNumber] = entry.intersectionRatio !== 1;
                return newState;
            });
        });
    }
}
function buildIntersectionThreshold(items) {
    const thresholds = [];
    const totalItems = items.length;
    for (let i = 1.0; i <= totalItems; i++) {
        const ratio = i / totalItems;
        thresholds.push(ratio);
    }
    thresholds.push(0);
    return thresholds;
}

exports.DataListTags = DataListTags;
