import { useRef, useState, useEffect, useMemo, useLayoutEffect } from 'react';

const DEFAULT_CONTAINER_WIDTH = 0;
/**
 * Custom hook used to check the width of a referenced component
 * on a window resize event
 * @param {number} - debounceInterval - Interval value in milliseconds
 * before updating containerWidth (Default of 250 ms)
 * @returns {array} - Reference object and the width of the referenced component
 */
export const useContainerWidth = (debounceInterval = 250) => {
    let timeout;

    const containerRef = useRef({});

    const [containerWidth, setContainerWidth] = useState(DEFAULT_CONTAINER_WIDTH);

    const updateSize = useMemo(() => (
        () => {
            const { current } = containerRef;
            const { clientWidth } = current || { clientWidth: DEFAULT_CONTAINER_WIDTH };
            setContainerWidth(clientWidth);
        }
    ), [containerRef]);

    const debounceResize = () => {
        if (timeout) { clearTimeout(timeout); }
        timeout = setTimeout(updateSize, debounceInterval);
    };

    useLayoutEffect(() => {
        window.addEventListener('resize', debounceResize);
        return () => window.removeEventListener('resize', debounceResize);
    }, []);

    useEffect(updateSize, []);

    return [containerRef, containerWidth];
};
