import { useEffect, useMemo, useRef, useState } from "react"


interface IUseDynamicSize {
    defaultWidth?: number
    defaultHeight?: number
}

export function useDynamicSize<T extends HTMLElement>({ defaultWidth = 0, defaultHeight = 0 }: IUseDynamicSize) {
    const [width, setWidth] = useState<number>(defaultWidth);
    const [height, setHeight] = useState<number>(defaultHeight);

    const elementRef = useRef<T>(null);

    useEffect(() => {
        if (!elementRef.current)
            return;

        const resizeObserver = new ResizeObserver(() => {
            if (elementRef.current?.clientWidth !== width) {
                setWidth(elementRef.current?.clientWidth || 0);
            }
            if (elementRef.current?.clientHeight !== height) {
                setHeight(elementRef.current?.clientHeight || 0);
            }
        });

        resizeObserver.observe(elementRef.current);

        return function cleanup() {
            resizeObserver.disconnect();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [elementRef.current])


    return useMemo(() => ({ width, height, elementRef }), [width, height, elementRef])
}