import { useEffect, useRef, useState } from "react";
//#region src/components/PisellCards/components/PisellImageCard/hooks/useImageLoad.ts
/**
* 图片加载状态管理 Hook
* @param src - 图片地址
* @param lazy - 是否启用懒加载
* @returns 加载状态对象
*/
const useImageLoad = (src, lazy) => {
	const [loading, setLoading] = useState(!!src);
	const [error, setError] = useState(false);
	const imgRef = useRef(null);
	const observerRef = useRef(null);
	useEffect(() => {
		if (!src) {
			setLoading(false);
			setError(false);
			return;
		}
		setLoading(true);
		setError(false);
		if (lazy && "IntersectionObserver" in window && imgRef.current) {
			observerRef.current = new IntersectionObserver((entries) => {
				entries.forEach((entry) => {
					if (entry.isIntersecting) {
						var _observerRef$current;
						loadImage();
						(_observerRef$current = observerRef.current) === null || _observerRef$current === void 0 || _observerRef$current.disconnect();
					}
				});
			}, { rootMargin: "50px" });
			observerRef.current.observe(imgRef.current);
			return () => {
				var _observerRef$current2;
				(_observerRef$current2 = observerRef.current) === null || _observerRef$current2 === void 0 || _observerRef$current2.disconnect();
			};
		} else loadImage();
	}, [src, lazy]);
	/**
	* 加载图片
	*/
	const loadImage = () => {
		if (!src) return;
		const img = new Image();
		img.src = src;
		img.onload = () => {
			setLoading(false);
			setError(false);
		};
		img.onerror = () => {
			setLoading(false);
			setError(true);
		};
	};
	return {
		loading,
		error,
		imgRef
	};
};
//#endregion
export { useImageLoad };
