import { useMemo, useRef } from 'react';
import { useUnmountEffect } from '../useUnmountEffect/index.js';
export function useThrottledCallback(callback, deps, delay, noTrailing = false) {
    const timeout = useRef();
    const lastCall = useRef();
    useUnmountEffect(() => {
        if (timeout.current) {
            clearTimeout(timeout.current);
            timeout.current = undefined;
        }
    });
    return useMemo(() => {
        const execute = (context, args) => {
            lastCall.current = undefined;
            callback.apply(context, args);
            timeout.current = setTimeout(() => {
                timeout.current = undefined;
                if (!noTrailing && lastCall.current) {
                    execute(lastCall.current.this, lastCall.current.args);
                    lastCall.current = undefined;
                }
            }, delay);
        };
        const wrapped = function (...args) {
            if (timeout.current) {
                lastCall.current = { args, this: this };
                return;
            }
            execute(this, args);
        };
        Object.defineProperties(wrapped, {
            length: { value: callback.length },
            name: { value: `${callback.name || 'anonymous'}__throttled__${delay}` },
        });
        return wrapped;
    }, [delay, noTrailing, ...deps]);
}
