import { useLayoutEffect, useCallback, RefObject } from 'react';

/**
 * Watch for changes on an element an
 * @param ref - element to watch for resizes
 * @param callback - tallback to trigger when the element resizes
 * @returns
 */
export const useResizeObserver = (
    ref: RefObject<HTMLElement>,
    callback: (entry: DOMRectReadOnly) => void,
): void => {
    const handleResize = useCallback(
        (entries: ResizeObserverEntry[]) => {
            if (!Array.isArray(entries)) {
                return;
            }

            const entry = entries[0];
            callback(entry.contentRect);
        },
        [callback],
    );

    useLayoutEffect(() => {
        if (!ref.current) {
            return;
        }

        let observer: ResizeObserver | null = new ResizeObserver(
            (entries: ResizeObserverEntry[]) => handleResize(entries),
        );
        observer.observe(ref.current);

        return () => {
            if (observer) {
                observer.disconnect();
            }
            observer = null;
        };
    }, [ref, handleResize]);
};
