import { useLayoutEffect, useRef, useState } from 'react';
const getChildWidths = (el) => {
    if (!el)
        return [];
    return Array.from(el.childNodes)
        .filter((n) => n instanceof HTMLElement)
        .map(n => n.getBoundingClientRect().width);
};
const getComputedGapPx = (el) => {
    const raw = getComputedStyle(el).columnGap ?? getComputedStyle(el).gap ?? '0';
    return parseFloat(raw) || 0;
};
export function useTopNavOverflow(items, opts) {
    const { moreButtonRef, epsilon = 16 } = opts;
    const containerRef = useRef(null);
    const measureRef = useRef(null);
    const [result, setResult] = useState({
        visibleCount: items.length
    });
    const resultRef = useRef(result);
    resultRef.current = result;
    useLayoutEffect(() => {
        const containerEl = containerRef.current;
        const measureEl = measureRef.current;
        if (!containerEl || !measureEl)
            return undefined;
        const recompute = () => {
            const containerWidth = containerEl.getBoundingClientRect().width;
            if (containerWidth === 0)
                return;
            const widths = getChildWidths(measureEl);
            if (widths.length === 0)
                return;
            const gap = getComputedGapPx(containerEl);
            const totalWidth = widths.reduce((sum, w) => sum + w, 0) + Math.max(0, widths.length - 1) * gap;
            const prev = resultRef.current;
            const isOverflowing = prev.visibleCount < items.length;
            const expandThreshold = isOverflowing ? totalWidth + epsilon : totalWidth;
            if (expandThreshold <= containerWidth) {
                if (prev.visibleCount !== items.length) {
                    setResult({ visibleCount: items.length });
                }
                return;
            }
            const moreButtonWidth = moreButtonRef?.current?.getBoundingClientRect().width ?? 0;
            const available = moreButtonWidth > 0 ? containerWidth - moreButtonWidth - gap : containerWidth;
            let used = 0;
            let visible = 0;
            for (let i = 0; i < widths.length; i += 1) {
                const itemWidth = widths[i] + (i > 0 ? gap : 0);
                if (used + itemWidth <= available) {
                    used += itemWidth;
                    visible += 1;
                }
                else {
                    break;
                }
            }
            if (prev.visibleCount !== visible) {
                setResult({ visibleCount: visible });
            }
        };
        recompute();
        const ro = new ResizeObserver(recompute);
        ro.observe(containerEl);
        ro.observe(measureEl);
        return () => {
            ro.disconnect();
        };
    }, [items.length, moreButtonRef, epsilon]);
    return { containerRef, measureRef, result };
}
//# sourceMappingURL=useTopNavOverflow.js.map