import { useState, useEffect } from 'react';

export const useSliderHeights = (layout, size) => {
    const [height, setHeight] = useState(0);
    const allHeights = [];
    useEffect(() => {
        // reset height on resize, debounced
        let timeout;
        const handleResize = () => {
            clearTimeout(timeout);
            setHeight(0);
        };
        const debounceResize = () => {
            if (timeout) { clearTimeout(timeout); }
            timeout = setTimeout(handleResize, 250);
        };
        window.addEventListener('resize', debounceResize);
        return () => {
            clearTimeout(timeout);
            window.removeEventListener('resize', debounceResize);
        };
    });

    // heights should reset when some props change
    useEffect(() => {
        setHeight(0);
    }, [layout, size, setHeight]);

    // store the heights reported by the children
    const reportHeight = (tileIndex, reportedHeight) => {
        if (reportedHeight) {
            allHeights.push(reportedHeight);
        }
        setHeight(Math.max(...allHeights));
    };
    return [height, reportHeight];
};
