/**
 * Copyright IBM Corp. 2020, 2026
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

require("../../../_virtual/_rolldown/runtime.js");
const require_useIsomorphicEffect = require("./useIsomorphicEffect.js");
const require_scrollableAncestor = require("../utils/scrollableAncestor.js");
let react = require("react");
//#region src/global/js/hooks/useWindowScroll.js
/**
* Copyright IBM Corp. 2022, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
const windowExists = typeof window !== `undefined`;
const useTargetScroll = function(target, effect, deps, throttleInterval) {
	const scrollPosition = (0, react.useRef)({});
	const throttleTimeout = (0, react.useRef)(null);
	const getScrollPosition = () => {
		if (!target || !windowExists && target === window) return {
			scrollX: -1,
			scrollY: -1
		};
		let scrollX, scrollY;
		if (target === window) {
			scrollX = window.scrollX;
			scrollY = window.scrollY;
		} else {
			scrollX = target.scrollLeft;
			scrollY = target.scrollTop;
		}
		return {
			scrollX,
			scrollY
		};
	};
	const doGetScrollPosition = () => {
		const newVal = {
			previous: scrollPosition.current,
			current: getScrollPosition()
		};
		effect(newVal);
		scrollPosition.current = newVal.current;
		throttleTimeout.current = null;
	};
	require_useIsomorphicEffect.useIsomorphicEffect(() => {
		const handleScroll = () => {
			if (throttleInterval) {
				if (throttleTimeout.current === null) throttleTimeout.current = setTimeout(doGetScrollPosition, throttleInterval);
			} else doGetScrollPosition();
		};
		if (target) {
			target.addEventListener("scroll", handleScroll);
			doGetScrollPosition();
		}
		return () => target && target.removeEventListener("scroll", handleScroll);
	}, deps);
};
function useNearestScroll(ref, effect, deps, throttle = 0) {
	let scrollableTarget = require_scrollableAncestor.scrollableAncestor(ref.current);
	if (scrollableTarget && (document.body === scrollableTarget || scrollableTarget.contains(document.body))) scrollableTarget = window;
	return useTargetScroll(scrollableTarget, effect, deps, throttle);
}
//#endregion
exports.useNearestScroll = useNearestScroll;
