import { debounce } from "@/lib/utils";
import {
    useState,
    useRef,
    useCallback,
    useEffect,
    useLayoutEffect
} from "react";


// Utility function for debouncing

function useMeasure(debounceDelay = 200) {
    const [rect, setRect] = useState({ width: 0, height: 0 });
    const ref = useRef<HTMLElement | null>(null);

    const updateRect = useCallback(
        debounce(() => {
            if (ref.current) {
                const { width, height } = ref.current.getBoundingClientRect();
                setRect({ width, height });
            }
        }, debounceDelay),
        [debounceDelay]
    );

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

        const observer = new ResizeObserver(() => {
            updateRect();
        });

        observer.observe(ref.current);

        return () => {
            observer.disconnect();
        };
    }, [updateRect]);

    return [ref, rect];
}

export default useMeasure;
