import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { useCallback, useEffect, useRef, useState } from "react";
//#region src/components/PisellScrollView/hooks/useScrollState.ts
/**
* 防抖函数
*/
const debounce = (fn, delay) => {
	let timeoutId = null;
	return ((...args) => {
		if (timeoutId) clearTimeout(timeoutId);
		timeoutId = setTimeout(() => {
			fn(...args);
			timeoutId = null;
		}, delay);
	});
};
/**
* 滚动状态管理 Hook
* @description 管理滚动容器的状态，包括滚动位置、溢出检测等
*/
const useScrollState = ({ containerRef, overflow }) => {
	const [scrollState, setScrollState] = useState(() => ({
		scrollTop: 0,
		scrollLeft: 0,
		percentY: 0,
		percentX: 0,
		scrollHeight: 0,
		scrollWidth: 0,
		clientHeight: 0,
		clientWidth: 0,
		direction: null,
		isScrollToTop: overflow === "y" || overflow === "both",
		isScrollToBottom: false,
		isScrollToLeft: overflow === "x" || overflow === "both",
		isScrollToRight: false,
		isOverflows: false
	}));
	const isMountedRef = useRef(true);
	const resizeObserverRef = useRef(null);
	/**
	* 计算并更新滚动状态
	*/
	const calculateScrollState = useCallback((prevState = null) => {
		const container = containerRef.current;
		if (!container) return null;
		try {
			const { scrollTop, scrollLeft, scrollHeight, scrollWidth, clientHeight, clientWidth } = container;
			const isOverflows = scrollHeight > clientHeight || scrollWidth > clientWidth;
			const isScrollToTop = scrollTop <= 0;
			const isScrollToBottom = scrollTop + clientHeight >= scrollHeight - 1;
			const isScrollToLeft = scrollLeft <= 0;
			const isScrollToRight = scrollLeft + clientWidth >= scrollWidth - 1;
			let direction = null;
			if (prevState) {
				const deltaY = Math.abs(scrollTop - prevState.scrollTop);
				const deltaX = Math.abs(scrollLeft - prevState.scrollLeft);
				if (deltaY > deltaX && deltaY > 0) direction = scrollTop > prevState.scrollTop ? "down" : "up";
				else if (deltaX > 0) direction = scrollLeft > prevState.scrollLeft ? "right" : "left";
				else direction = prevState.direction;
			}
			const maxScrollTop = Math.max(0, scrollHeight - clientHeight);
			const maxScrollLeft = Math.max(0, scrollWidth - clientWidth);
			return {
				scrollTop,
				scrollLeft,
				scrollHeight,
				scrollWidth,
				clientHeight,
				clientWidth,
				percentY: maxScrollTop > 0 ? scrollTop / maxScrollTop * 100 : 0,
				percentX: maxScrollLeft > 0 ? scrollLeft / maxScrollLeft * 100 : 0,
				direction,
				isScrollToTop,
				isScrollToBottom,
				isScrollToLeft,
				isScrollToRight,
				isOverflows
			};
		} catch (error) {
			console.warn("[useScrollState] 计算滚动状态时出错:", error);
			return null;
		}
	}, [containerRef]);
	/**
	* 更新滚动状态（用于滚动事件）
	*/
	const updateScrollState = useCallback(() => {
		if (!isMountedRef.current) return;
		setScrollState((prev) => {
			return calculateScrollState(prev) || prev;
		});
	}, [calculateScrollState]);
	/**
	* 更新溢出状态（用于尺寸变化）
	*/
	const updateOverflowState = useCallback(() => {
		if (!isMountedRef.current) return;
		const newState = calculateScrollState(null);
		if (newState) setScrollState((prev) => _objectSpread2(_objectSpread2({}, prev), {}, {
			scrollHeight: newState.scrollHeight,
			scrollWidth: newState.scrollWidth,
			clientHeight: newState.clientHeight,
			clientWidth: newState.clientWidth,
			isOverflows: newState.isOverflows,
			isScrollToTop: newState.isScrollToTop,
			isScrollToBottom: newState.isScrollToBottom,
			isScrollToLeft: newState.isScrollToLeft,
			isScrollToRight: newState.isScrollToRight
		}));
	}, [calculateScrollState]);
	useEffect(() => {
		isMountedRef.current = true;
		const container = containerRef.current;
		if (!container) return;
		const debouncedUpdateOverflow = debounce(updateOverflowState, 50);
		updateOverflowState();
		if (typeof ResizeObserver === "undefined") {
			const handleResize = () => debouncedUpdateOverflow();
			window.addEventListener("resize", handleResize);
			return () => {
				isMountedRef.current = false;
				window.removeEventListener("resize", handleResize);
			};
		}
		try {
			resizeObserverRef.current = new ResizeObserver((entries) => {
				if (entries.length > 0 && isMountedRef.current) debouncedUpdateOverflow();
			});
			resizeObserverRef.current.observe(container);
			const children = container.children;
			for (let i = 0; i < children.length; i++) resizeObserverRef.current.observe(children[i]);
			const mutationObserver = new MutationObserver((mutations) => {
				if (!isMountedRef.current || !resizeObserverRef.current) return;
				mutations.forEach((mutation) => {
					mutation.addedNodes.forEach((node) => {
						if (node instanceof Element) {
							var _resizeObserverRef$cu;
							(_resizeObserverRef$cu = resizeObserverRef.current) === null || _resizeObserverRef$cu === void 0 || _resizeObserverRef$cu.observe(node);
						}
					});
				});
				debouncedUpdateOverflow();
			});
			mutationObserver.observe(container, {
				childList: true,
				subtree: false
			});
			const handleWindowResize = () => debouncedUpdateOverflow();
			window.addEventListener("resize", handleWindowResize);
			return () => {
				var _resizeObserverRef$cu2;
				isMountedRef.current = false;
				(_resizeObserverRef$cu2 = resizeObserverRef.current) === null || _resizeObserverRef$cu2 === void 0 || _resizeObserverRef$cu2.disconnect();
				resizeObserverRef.current = null;
				mutationObserver.disconnect();
				window.removeEventListener("resize", handleWindowResize);
			};
		} catch (error) {
			console.warn("[useScrollState] 初始化 ResizeObserver 失败:", error);
			const handleResize = () => debouncedUpdateOverflow();
			window.addEventListener("resize", handleResize);
			return () => {
				isMountedRef.current = false;
				window.removeEventListener("resize", handleResize);
			};
		}
	}, [containerRef, updateOverflowState]);
	return {
		scrollState,
		updateScrollState
	};
};
//#endregion
export { useScrollState };
