import React from "react";
import { useCallback, useState } from 'react';
/**
 * A custom React hook for calculating the number of visible children in a dynamic list based on container width and child widths.
 *
 * @returns {object} An object containing the `calculateNumberOfVisibleChildren` function.
 *
 * @example
 * // Basic usage:
 * const parentRef = useRef();
 * const childRefs = useRef([]);
 * const { calculateNumberOfVisibleChildren } = useDynamicListCalculation();
 * const maxVisibleChildren = calculateNumberOfVisibleChildren(parentRef, childRefs);

 * @example
 * // Excluding a buffer for less white space:
 * const parentRef = useRef();
 * const childRefs = useRef([]);
 * const { calculateNumberOfVisibleChildren } = useDynamicListCalculation();
 * const maxVisibleChildren = calculateNumberOfVisibleChildren(parentRef, childRefs, false);
 */
export const useDynamicListCalculation = () => {
    const [averageChildWidth, setAverageChildWidth] = useState(0);
    const [previousChildRefs, setPreviousChildRefs] = useState([]);
    /**
     * Calculate the number of visible children based on container width and child widths.
     *
     * @param {object} parentRef - Ref object for the parent container.
     * @param {object} childRefs - Ref object for an array of child elements.
     * @param {boolean} includeBuffer - Whether to include a buffer for better performance (default: true).
     * @returns {number} The maximum number of visible children.
     */
    const calculateNumberOfVisibleChildren = useCallback((parentRef, childRefs, includeBuffer = true) => {
        var _a;
        if (!parentRef.current || !childRefs.current)
            return;
        const containerWidth = (_a = parentRef.current.getBoundingClientRect().width) !== null && _a !== void 0 ? _a : 0;
        // If the average child width has not been calculated yet, or the child refs have changed, then calculate the average child width
        if (!averageChildWidth || previousChildRefs !== childRefs.current) {
            const childrenTotalWidth = childRefs.current
                .map((ref) => ref && typeof (ref === null || ref === void 0 ? void 0 : ref.getBoundingClientRect) === 'function'
                ? ref.getBoundingClientRect().width
                : 0)
                .reduce((acc, curr) => acc + curr, 0);
            const calculatedAverageWidth = childrenTotalWidth / childRefs.current.length;
            setAverageChildWidth(calculatedAverageWidth);
            setPreviousChildRefs(childRefs.current);
        }
        const maxVisibleChildren = Math.floor(containerWidth / averageChildWidth);
        if (includeBuffer)
            return maxVisibleChildren - 1;
        return maxVisibleChildren;
    }, [averageChildWidth, previousChildRefs]);
    return { calculateNumberOfVisibleChildren };
};
//# sourceMappingURL=useDynamicListCalculation.js.map