import React__default, { useRef, useState, useEffect } from 'react';
import classnames from 'classnames';
import { I as InlineLabel } from './InlineLabel-es.js';
import { T as Text } from './Text-es.js';

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

function DataListTags({ items }) {
    const ref = useRef(null);
    const [visibleIndex, setVisibleIndex] = useState([]);
    const visibleItems = visibleIndex.filter(Boolean).length;
    const shouldShowTagCount = Boolean(visibleItems);
    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__default.createElement("div", { className: styles.tagWrapper, ref: ref },
        React__default.createElement("div", { className: classnames(styles.tags, {
                [styles.tagsMask]: shouldShowTagCount,
            }) }, items.filter(Boolean).map((tag, index) => (React__default.createElement("div", { key: tag, "data-tag-element": index },
            React__default.createElement(InlineLabel, null, tag))))),
        shouldShowTagCount && (React__default.createElement("div", { className: styles.tagCount },
            React__default.createElement(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;
}

export { DataListTags as D };
