const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
let react = require("react");
react = require_runtime.__toESM(react);
//#region src/plus/skuOptionsSelection/store/createStore.ts
/**
* useSyncExternalStore 的简易兼容实现 (Polyfill)
* 用于在 React < 18 的环境中模拟核心功能
*/
const useSyncExternalStoreShim = (subscribe, getSnapshot) => {
	const [snapshot, setSnapshot] = (0, react.useState)(getSnapshot);
	(0, react.useEffect)(() => {
		const handleChange = () => {
			const nextSnapshot = getSnapshot();
			setSnapshot((prev) => {
				if (Object.is(prev, nextSnapshot)) return prev;
				return nextSnapshot;
			});
		};
		const unsubscribe = subscribe(handleChange);
		handleChange();
		return unsubscribe;
	}, [subscribe, getSnapshot]);
	return snapshot;
};
const useSyncExternalStore = react.useSyncExternalStore || useSyncExternalStoreShim;
/**
* 创建一个跨 React 版本兼容的 Store
* 支持自动浅合并 (Auto Shallow Merge)
* @param initialState 初始状态
*/
function createStore(initialState) {
	let state = initialState;
	const listeners = /* @__PURE__ */ new Set();
	const getState = () => state;
	/**
	* 更新状态
	* 支持传入部分状态对象进行自动合并
	* 支持传入函数 (prev) => Partial<T>
	*/
	const setState = (partial) => {
		const partialState = typeof partial === "function" ? partial(state) : partial;
		let hasChange = false;
		const keys = Object.keys(partialState);
		for (const key of keys) if (!Object.is(partialState[key], state[key])) {
			hasChange = true;
			break;
		}
		if (!hasChange) return;
		state = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, state), partialState);
		listeners.forEach((listener) => listener());
	};
	const subscribe = (listener) => {
		listeners.add(listener);
		return () => listeners.delete(listener);
	};
	/**
	* React Hook
	* @param selector 选择器函数，默认返回整个 state
	*/
	const useStore = (selector = (s) => s) => {
		return useSyncExternalStore(subscribe, () => selector(state));
	};
	Object.assign(useStore, {
		getState,
		setState,
		subscribe
	});
	return useStore;
}
//#endregion
exports.default = createStore;
