import { useCallback, useEffect, useRef, } from 'react';
import { useMergedRefs } from '@base-ui/utils/useMergedRefs';
import { useCustomCompareEffect, useCustomCompareMemo } from '@react-hookz/web';
import { isEqual } from '@ver0/deep-equal';
import { useRefWithInit } from "./useRefWithInit.js";
/**
 * Hook that combines useEffect with ref dependencies. Runs the effect whenever regular dependencies
 * change or when ref values change.
 */
export function useEffectWithRefDeps(effect, regularDeps, refDeps, options = {}) {
    const { deepCompare = false, hook = useEffect } = options;
    const cleanupFunction = useRef(null);
    const cleanUpIfNeeded = () => {
        cleanupFunction.current?.();
        cleanupFunction.current = null;
    };
    const runEffectToken = useRef(0);
    const runEffect = useCustomCompareMemo(() => () => {
        runEffectToken.current++;
        cleanUpIfNeeded();
        cleanupFunction.current = effect() ?? null;
    }, regularDeps, deepCompare ? isEqual : Object.is);
    useCustomCompareEffect(() => {
        runEffect();
        return cleanUpIfNeeded;
    }, [runEffect], undefined, hook);
    const runEffectNextTick = useCallback(() => {
        const token = ++runEffectToken.current;
        window.queueMicrotask(() => {
            if (runEffectToken.current === token) {
                runEffect();
            }
        });
    }, [runEffect]);
    const stableRefDepCount = useRefWithInit(() => refDeps.length).current;
    const resizedRefDeps = getResizedArray(refDeps, stableRefDepCount);
    if (resizedRefDeps.some((refDep) => refDep === undefined)) {
        throw new Error('[useEffectWithRefDeps] Number of passed `refDeps` must be stable');
    }
    const callbackRefs = resizedRefDeps.map((refDep) => 
    // oxlint-disable-next-line react-hooks/rules-of-hooks
    useMergedRefs(refDep, runEffectNextTick));
    return callbackRefs;
}
function getResizedArray(array, newLength) {
    return Array.from({ length: newLength }, (_, i) => array[i]);
}
//# sourceMappingURL=useEffectWithRefDeps.js.map