/**
 * @license MIT
 * author: Cube Dev Team
 * @cube-dev/ui-kit v0.0.0-canary-43d3dd9
 * Released under the MIT license.
 */

import { useSyncExternalStore } from 'react';
import { useEvent } from '../../_internal/hooks/use-event.js';
/**
 * Create a shared store that survives hot-reloads.
 *
 * Pass a unique `name` once per logical store module:
 *   export const useSidebarStore = createSharedStore('sidebar', { open: false });
 */
export function createSharedStore(name, initialState) {
    const cacheKey = `__sharedStore_${name}__`;
    const existing = cacheKey && globalThis[cacheKey];
    const holder = existing ?? {
        state: initialState,
        listeners: new Set(),
    };
    /* Warn if someone tries to “re-initialise” with a different value */
    if (process.env.NODE_ENV === 'development' &&
        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;
}

        