/** @license MIT | @cube-dev/ui-kit v0.0.0-canary-b04eed0 | Cube Dev Team */
import { useEffect, useRef, useState } from "react";

//#region src/_internal/hooks/use-debounced-value.ts
function useDebouncedValue(value, delay = 300, maxWait) {
	const [debouncedValue, setDebouncedValue] = useState(value);
	const lastValueRef = useRef(value);
	const timeoutRef = useRef(null);
	const maxWaitTimeoutRef = useRef(null);
	useEffect(() => {
		if (value === lastValueRef.current) {
			if (timeoutRef.current) clearTimeout(timeoutRef.current);
			if (maxWaitTimeoutRef.current) clearTimeout(maxWaitTimeoutRef.current);
			return;
		}
		timeoutRef.current = setTimeout(() => {
			setDebouncedValue(value);
			lastValueRef.current = value;
			if (maxWaitTimeoutRef.current) {
				clearTimeout(maxWaitTimeoutRef.current);
				maxWaitTimeoutRef.current = null;
			}
		}, delay);
		if (maxWait && !maxWaitTimeoutRef.current) maxWaitTimeoutRef.current = setTimeout(() => {
			setDebouncedValue(value);
			lastValueRef.current = value;
			if (timeoutRef.current) {
				clearTimeout(timeoutRef.current);
				timeoutRef.current = null;
			}
		}, maxWait);
		return () => {
			if (timeoutRef.current) clearTimeout(timeoutRef.current);
			if (maxWaitTimeoutRef.current) clearTimeout(maxWaitTimeoutRef.current);
		};
	}, [
		value,
		delay,
		maxWait
	]);
	return debouncedValue;
}

//#endregion
export { useDebouncedValue };
//# sourceMappingURL=use-debounced-value.js.map