'use client';

import { useGetElementOrWindow } from "./useGetElementOrWindow.mjs";
import { useCallback, useSyncExternalStore } from "react";

//#region src/hooks/useScrollY.ts
const INITIAL_SCROLL_STATE = {
	scrollY: 0,
	scrollPercentage: 0,
	scrollYMax: 0
};
let lastSnapshot = INITIAL_SCROLL_STATE;
const useScrollY = (props) => {
	const { element } = props ?? {};
	const containerElement = useGetElementOrWindow(element);
	const subscribe = useCallback((onChange) => {
		if (typeof window === "undefined" || !containerElement) return () => {};
		let raf = 0;
		const handler = () => {
			if (raf) return;
			raf = window.requestAnimationFrame(() => {
				raf = 0;
				onChange();
			});
		};
		containerElement.addEventListener("scroll", handler, { passive: true });
		return () => {
			containerElement.removeEventListener("scroll", handler);
			if (raf) window.cancelAnimationFrame(raf);
		};
	}, [containerElement]);
	const getSnapshot = () => {
		if (typeof window === "undefined" || !containerElement) return INITIAL_SCROLL_STATE;
		if (containerElement instanceof HTMLElement) {
			const scrollY$1 = containerElement.scrollTop;
			const scrollHeight$1 = containerElement.scrollHeight;
			const clientHeight$1 = containerElement.clientHeight;
			const scrollYMax$1 = Math.max(0, scrollHeight$1 - clientHeight$1);
			const scrollPercentage$1 = scrollYMax$1 > 0 ? scrollY$1 / scrollYMax$1 : 0;
			if (lastSnapshot.scrollY === scrollY$1 && lastSnapshot.scrollPercentage === scrollPercentage$1 && lastSnapshot.scrollYMax === scrollYMax$1) return lastSnapshot;
			lastSnapshot = {
				scrollY: scrollY$1,
				scrollPercentage: scrollPercentage$1,
				scrollYMax: scrollYMax$1
			};
			return lastSnapshot;
		}
		const doc = document.documentElement;
		const body = document.body;
		const scrollY = window.scrollY ?? window.pageYOffset ?? doc?.scrollTop ?? body?.scrollTop ?? 0;
		const scrollHeight = doc?.scrollHeight ?? body?.scrollHeight ?? 0;
		const clientHeight = doc?.clientHeight ?? window.innerHeight ?? 0;
		const scrollYMax = Math.max(0, scrollHeight - clientHeight);
		const scrollPercentage = scrollYMax > 0 ? scrollY / scrollYMax : 0;
		if (lastSnapshot.scrollY === scrollY && lastSnapshot.scrollPercentage === scrollPercentage && lastSnapshot.scrollYMax === scrollYMax) return lastSnapshot;
		lastSnapshot = {
			scrollY,
			scrollPercentage,
			scrollYMax
		};
		return lastSnapshot;
	};
	const getServerSnapshot = () => INITIAL_SCROLL_STATE;
	return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
};

//#endregion
export { useScrollY };
//# sourceMappingURL=useScrollY.mjs.map