'use client'
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var React = require('react');
var EventEmitter = require('eventemitter3');
var utils = require('@dynamic-labs/utils');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter);

// Store client + emitter on globalThis so state survives dual-package loading.
// Next.js 16 / React 19 may load both ESM and CJS builds of this package,
// giving each its own module scope. globalThis is shared across both.
// See: https://nodejs.org/api/packages.html#dual-package-hazard
const GLOBAL_KEY = Symbol.for('@dynamic-labs/sdk-react-core/client');
const getClientStore = () => {
    const g = globalThis;
    if (!g[GLOBAL_KEY]) {
        g[GLOBAL_KEY] = {
            client: null,
            emitter: new EventEmitter__default["default"](),
        };
    }
    return g[GLOBAL_KEY];
};
const setDynamicClient = (newClient) => {
    const store = getClientStore();
    store.client = newClient;
    store.emitter.emit('changed', newClient);
};
const hasDynamicClient = () => getClientStore().client !== null;
const getDynamicClient = () => {
    const { client } = getClientStore();
    if (!client) {
        throw new utils.DynamicError('Tried to getClient when it was still null', 'tried_to_getclient_when_it_was');
    }
    return client;
};
/**
 * Not many customers will ever change the client mid execution, but demo v2 will.
 * That means we need hooks that can react to client changes.
 */
const useDynamicClient = () => {
    const [client, setClient] = React.useState(getDynamicClient());
    React.useEffect(() => {
        const { emitter, client: currentClient } = getClientStore();
        // Guard against race: client may have changed between useState init and effect mount
        if (currentClient && currentClient !== client) {
            setClient(currentClient);
        }
        emitter.on('changed', setClient);
        return () => {
            emitter.off('changed', setClient);
        };
    }, [client]);
    return client;
};

exports.getDynamicClient = getDynamicClient;
exports.hasDynamicClient = hasDynamicClient;
exports.setDynamicClient = setDynamicClient;
exports.useDynamicClient = useDynamicClient;
