/** @license MIT | @cube-dev/ui-kit v0.0.0-canary-b04eed0 | Cube Dev Team */
import { useEvent } from "../../_internal/hooks/use-event.js";
import { useSyncExternalStore } from "react";

//#region src/utils/react/sharedStore.ts
/**
* Create a shared store that survives hot-reloads.
*
* Pass a unique `name` once per logical store module:
*   export const useSidebarStore = createSharedStore('sidebar', { open: false });
*/
function createSharedStore(name, initialState) {
	const cacheKey = `__sharedStore_${name}__`;
	const existing = cacheKey && globalThis[cacheKey];
	const holder = existing ?? {
		state: initialState,
		listeners: /* @__PURE__ */ new Set()
	};
	if (existing && existing.state !== initialState) console.warn(`[createSharedStore] Store "${name}" already exists – the new initialState is ignored to preserve hot-reload state.`);
	if (cacheKey && !existing) globalThis[cacheKey] = holder;
	const getSnapshot = () => holder.state;
	const subscribe = (cb) => {
		holder.listeners.add(cb);
		return () => holder.listeners.delete(cb);
	};
	const setStore = (update) => {
		holder.state = typeof update === "function" ? update(holder.state) : update;
		holder.listeners.forEach((l) => l());
	};
	const useSharedStore = () => {
		return [useSyncExternalStore(subscribe, getSnapshot), useEvent(setStore)];
	};
	return useSharedStore;
}

//#endregion
export { createSharedStore };
//# sourceMappingURL=sharedStore.js.map