import React, { createContext, useCallback, useContext, useMemo, useRef } from "react";
//#region src/components/pisellDataSourceContainer/provider/RefManager.tsx
const RefManagerContext = createContext(null);
const RefManagerProvider = ({ children }) => {
	const refMapRef = useRef(/* @__PURE__ */ new Map());
	/** 共享状态存储 */
	const sharedStateRef = useRef(/* @__PURE__ */ new Map());
	/** 状态订阅器存储 */
	const subscribersRef = useRef(/* @__PURE__ */ new Map());
	const registerRef = useCallback((id, ref) => {
		if (!id) {
			console.warn("[RefManager] registerRef: id 不能为空");
			return;
		}
		refMapRef.current.set(id, ref);
	}, []);
	const getRef = useCallback((id) => {
		if (!id) {
			console.warn("[RefManager] getRef: id 不能为空");
			return;
		}
		const ref = refMapRef.current.get(id);
		if (!ref) console.warn(`[RefManager] 组件 "${id}" 未注册`);
		return ref;
	}, []);
	const unregisterRef = useCallback((id) => {
		if (!id) {
			console.warn("[RefManager] unregisterRef: id 不能为空");
			return;
		}
		refMapRef.current.delete(id);
	}, []);
	/**
	* 获取共享状态
	*/
	const getSharedState = useCallback((key) => {
		if (!key) {
			console.warn("[RefManager] getSharedState: key 不能为空");
			return;
		}
		return sharedStateRef.current.get(key);
	}, []);
	/**
	* 设置共享状态（会自动通知所有订阅者）
	*/
	const setSharedState = useCallback((key, value) => {
		if (!key) {
			console.warn("[RefManager] setSharedState: key 不能为空");
			return;
		}
		sharedStateRef.current.set(key, value);
		const subscribers = subscribersRef.current.get(key);
		if (subscribers && subscribers.size > 0) subscribers.forEach((callback) => {
			try {
				callback(value);
			} catch (error) {
				console.error(`[RefManager] 订阅回调执行失败 (key: ${key}):`, error);
			}
		});
	}, []);
	const subscribeSharedState = useCallback((key, callback) => {
		if (!key) {
			console.warn("[RefManager] subscribeSharedState: key 不能为空");
			return () => {};
		}
		if (!callback) {
			console.warn("[RefManager] subscribeSharedState: callback 不能为空");
			return () => {};
		}
		if (!subscribersRef.current.has(key)) subscribersRef.current.set(key, /* @__PURE__ */ new Set());
		const subscribers = subscribersRef.current.get(key);
		subscribers.add(callback);
		const currentState = sharedStateRef.current.get(key);
		if (currentState !== void 0) try {
			callback(currentState);
		} catch (error) {}
		return () => {
			subscribers.delete(callback);
			if (subscribers.size === 0) subscribersRef.current.delete(key);
		};
	}, []);
	const contextValue = useMemo(() => ({
		getRef,
		registerRef,
		unregisterRef,
		getSharedState,
		setSharedState,
		subscribeSharedState
	}), [
		getRef,
		registerRef,
		unregisterRef,
		getSharedState,
		setSharedState,
		subscribeSharedState
	]);
	return /* @__PURE__ */ React.createElement(RefManagerContext.Provider, { value: contextValue }, children);
};
const useRefManagerProvider = () => {
	return useContext(RefManagerContext);
};
//#endregion
export { RefManagerProvider, useRefManagerProvider };
