import { _ as __assign, b as __awaiter, c as __generator } from './bundle-B8Grfnrx.js';
import { S as SendbirdContext, s as shimExports } from './bundle-C4OmfIXk.js';
import { useContext, useMemo } from 'react';
import SendbirdChat, { SendbirdProduct, SendbirdPlatform, DeviceOsPlatform } from '@sendbird/chat';
import { GroupChannelModule } from '@sendbird/chat/groupChannel';
import { OpenChannelModule } from '@sendbird/chat/openChannel';

var updateAppInfoStore = function (state, payload) {
    return __assign(__assign({}, state), { stores: __assign(__assign({}, state.stores), { appInfoStore: __assign(__assign({}, state.stores.appInfoStore), payload) }) });
};
var updateSdkStore = function (state, payload) {
    return __assign(__assign({}, state), { stores: __assign(__assign({}, state.stores), { sdkStore: __assign(__assign({}, state.stores.sdkStore), payload) }) });
};
var updateUserStore = function (state, payload) {
    return __assign(__assign({}, state), { stores: __assign(__assign({}, state.stores), { userStore: __assign(__assign({}, state.stores.userStore), payload) }) });
};
function initSDK(_a) {
    var appId = _a.appId, customApiHost = _a.customApiHost, customWebSocketHost = _a.customWebSocketHost, _b = _a.sdkInitParams, sdkInitParams = _b === void 0 ? {} : _b;
    var params = Object.assign(sdkInitParams, {
        appId: appId,
        modules: [new GroupChannelModule(), new OpenChannelModule()],
        // newInstance: isNewApp,
        localCacheEnabled: true,
    });
    if (customApiHost)
        params.customApiHost = customApiHost;
    if (customWebSocketHost)
        params.customWebSocketHost = customWebSocketHost;
    return SendbirdChat.init(params);
}
var APP_VERSION_STRING = '3.15.14';
/**
 * Sets up the Sendbird SDK after initialization.
 * Configures necessary settings, adds extensions, sets the platform, and configures the session handler if provided.
 */
function setupSDK(sdk, params) {
    var _a, _b;
    var logger = params.logger, sessionHandler = params.sessionHandler, isMobile = params.isMobile, customExtensionParams = params.customExtensionParams;
    (_a = logger.info) === null || _a === void 0 ? void 0 : _a.call(logger, 'SendbirdProvider | useConnect/setupConnection/setVersion', { version: APP_VERSION_STRING });
    sdk.addExtension('sb_uikit', APP_VERSION_STRING);
    sdk.addSendbirdExtensions([{ product: SendbirdProduct.UIKIT_CHAT, version: APP_VERSION_STRING, platform: SendbirdPlatform === null || SendbirdPlatform === void 0 ? void 0 : SendbirdPlatform.JS }], { platform: isMobile ? DeviceOsPlatform.MOBILE_WEB : DeviceOsPlatform.WEB }, customExtensionParams);
    if (sessionHandler) {
        (_b = logger.info) === null || _b === void 0 ? void 0 : _b.call(logger, 'SendbirdProvider | useConnect/setupConnection/configureSession', sessionHandler);
        sdk.setSessionHandler(sessionHandler);
    }
}

var NO_CONTEXT_ERROR = 'No sendbird state value available. Make sure you are rendering `<SendbirdProvider>` at the top of your app.';
var useSendbird = function () {
    var store = useContext(SendbirdContext);
    if (!store)
        throw new Error(NO_CONTEXT_ERROR);
    var state = shimExports.useSyncExternalStore(store.subscribe, store.getState);
    var actions = useMemo(function () { return ({
        /* Example: How to set the state basically */
        // exampleAction: () => {
        //   store.setState((state): SendbirdState => ({
        //     ...state,
        //     example: true,
        //   })),
        // },
        /* AppInfo */
        initMessageTemplateInfo: function (_a) {
            var payload = _a.payload;
            store.setState(function (state) { return (updateAppInfoStore(state, {
                messageTemplatesInfo: payload,
                waitingTemplateKeysMap: {},
            })); });
        },
        upsertMessageTemplates: function (_a) {
            var payload = _a.payload;
            var appInfoStore = state.stores.appInfoStore;
            var templatesInfo = appInfoStore.messageTemplatesInfo;
            if (!templatesInfo)
                return state; // Not initialized. Ignore.
            var waitingTemplateKeysMap = __assign({}, appInfoStore.waitingTemplateKeysMap);
            payload.forEach(function (templatesMapData) {
                var key = templatesMapData.key, template = templatesMapData.template;
                templatesInfo.templatesMap[key] = template;
                delete waitingTemplateKeysMap[key];
            });
            store.setState(function (state) { return (updateAppInfoStore(state, {
                waitingTemplateKeysMap: waitingTemplateKeysMap,
                messageTemplatesInfo: templatesInfo,
            })); });
        },
        upsertWaitingTemplateKeys: function (_a) {
            var payload = _a.payload;
            var appInfoStore = state.stores.appInfoStore;
            var keys = payload.keys, requestedAt = payload.requestedAt;
            var waitingTemplateKeysMap = __assign({}, appInfoStore.waitingTemplateKeysMap);
            keys.forEach(function (key) {
                var _a, _b;
                waitingTemplateKeysMap[key] = {
                    erroredMessageIds: (_b = (_a = waitingTemplateKeysMap[key]) === null || _a === void 0 ? void 0 : _a.erroredMessageIds) !== null && _b !== void 0 ? _b : [],
                    requestedAt: requestedAt,
                };
            });
            store.setState(function (state) { return (updateAppInfoStore(state, {
                waitingTemplateKeysMap: waitingTemplateKeysMap,
            })); });
        },
        markErrorWaitingTemplateKeys: function (_a) {
            var payload = _a.payload;
            var appInfoStore = state.stores.appInfoStore;
            var keys = payload.keys, messageId = payload.messageId;
            var waitingTemplateKeysMap = __assign({}, appInfoStore.waitingTemplateKeysMap);
            keys.forEach(function (key) {
                var waitingTemplateKeyData = waitingTemplateKeysMap[key];
                if (waitingTemplateKeyData && waitingTemplateKeyData.erroredMessageIds.indexOf(messageId) === -1) {
                    waitingTemplateKeyData.erroredMessageIds.push(messageId);
                }
            });
            store.setState(function (state) { return (updateAppInfoStore(state, {
                waitingTemplateKeysMap: waitingTemplateKeysMap,
            })); });
        },
        /* SDK */
        setSdkLoading: function (payload) {
            store.setState(function (state) { return (updateSdkStore(state, {
                initialized: false,
                loading: payload,
            })); });
        },
        sdkError: function () {
            store.setState(function (state) { return (updateSdkStore(state, {
                initialized: false,
                loading: false,
                error: true,
            })); });
        },
        initSdk: function (payload) {
            store.setState(function (state) { return (updateSdkStore(state, {
                sdk: payload,
                initialized: true,
                loading: false,
                error: false,
            })); });
        },
        resetSdk: function () {
            store.setState(function (state) { return (updateSdkStore(state, {
                sdk: null,
                initialized: false,
                loading: false,
                error: false,
            })); });
        },
        /* User */
        initUser: function (payload) {
            store.setState(function (state) { return (updateUserStore(state, {
                initialized: true,
                loading: false,
                user: payload,
            })); });
        },
        resetUser: function () {
            store.setState(function (state) { return (updateUserStore(state, {
                initialized: false,
                loading: false,
                user: null,
            })); });
        },
        updateUserInfo: function (payload) {
            store.setState(function (state) { return (updateUserStore(state, {
                user: payload,
            })); });
        },
        /* Connection */
        connect: function (params) { return __awaiter(void 0, void 0, void 0, function () {
            var logger, userId, appId, accessToken, nickname, profileUrl, isMobile, sdkInitParams, customApiHost, customWebSocketHost, customExtensionParams, eventHandlers, initializeMessageTemplatesInfo, configureSession, initDashboardConfigs, sdk, user, error_1, sendbirdError;
            var _a, _b, _c, _d, _e;
            return __generator(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        logger = params.logger, userId = params.userId, appId = params.appId, accessToken = params.accessToken, nickname = params.nickname, profileUrl = params.profileUrl, isMobile = params.isMobile, sdkInitParams = params.sdkInitParams, customApiHost = params.customApiHost, customWebSocketHost = params.customWebSocketHost, customExtensionParams = params.customExtensionParams, eventHandlers = params.eventHandlers, initializeMessageTemplatesInfo = params.initializeMessageTemplatesInfo, configureSession = params.configureSession, initDashboardConfigs = params.initDashboardConfigs;
                        // clean up previous ws connection
                        return [4 /*yield*/, actions.disconnect({ logger: logger })];
                    case 1:
                        // clean up previous ws connection
                        _f.sent();
                        sdk = initSDK({
                            appId: appId,
                            customApiHost: customApiHost,
                            customWebSocketHost: customWebSocketHost,
                            sdkInitParams: sdkInitParams,
                        });
                        setupSDK(sdk, {
                            logger: logger,
                            isMobile: isMobile,
                            customExtensionParams: customExtensionParams,
                            sessionHandler: configureSession ? configureSession(sdk) : undefined,
                        });
                        actions.setSdkLoading(true);
                        _f.label = 2;
                    case 2:
                        _f.trys.push([2, 8, , 9]);
                        return [4 /*yield*/, sdk.connect(userId, accessToken)];
                    case 3:
                        user = _f.sent();
                        actions.initUser(user);
                        if (!(nickname || profileUrl)) return [3 /*break*/, 5];
                        return [4 /*yield*/, sdk.updateCurrentUserInfo({
                                nickname: nickname || user.nickname || '',
                                profileUrl: profileUrl || user.profileUrl,
                            })];
                    case 4:
                        _f.sent();
                        _f.label = 5;
                    case 5: return [4 /*yield*/, (initializeMessageTemplatesInfo === null || initializeMessageTemplatesInfo === void 0 ? void 0 : initializeMessageTemplatesInfo(sdk))];
                    case 6:
                        _f.sent();
                        return [4 /*yield*/, (initDashboardConfigs === null || initDashboardConfigs === void 0 ? void 0 : initDashboardConfigs(sdk))];
                    case 7:
                        _f.sent();
                        actions.initSdk(sdk);
                        (_b = (_a = eventHandlers === null || eventHandlers === void 0 ? void 0 : eventHandlers.connection) === null || _a === void 0 ? void 0 : _a.onConnected) === null || _b === void 0 ? void 0 : _b.call(_a, user);
                        return [3 /*break*/, 9];
                    case 8:
                        error_1 = _f.sent();
                        sendbirdError = error_1;
                        actions.resetSdk();
                        actions.resetUser();
                        (_c = logger.error) === null || _c === void 0 ? void 0 : _c.call(logger, 'SendbirdProvider | useSendbird/connect failed', sendbirdError);
                        (_e = (_d = eventHandlers === null || eventHandlers === void 0 ? void 0 : eventHandlers.connection) === null || _d === void 0 ? void 0 : _d.onFailed) === null || _e === void 0 ? void 0 : _e.call(_d, sendbirdError);
                        return [3 /*break*/, 9];
                    case 9: return [2 /*return*/];
                }
            });
        }); },
        disconnect: function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
            var sdk;
            var _c;
            var logger = _b.logger;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        actions.setSdkLoading(true);
                        sdk = state.stores.sdkStore.sdk;
                        if (!(sdk === null || sdk === void 0 ? void 0 : sdk.disconnectWebSocket)) return [3 /*break*/, 2];
                        return [4 /*yield*/, sdk.disconnectWebSocket()];
                    case 1:
                        _d.sent();
                        _d.label = 2;
                    case 2:
                        actions.resetSdk();
                        actions.resetUser();
                        (_c = logger.info) === null || _c === void 0 ? void 0 : _c.call(logger, 'SendbirdProvider | useSendbird/disconnect completed');
                        return [2 /*return*/];
                }
            });
        }); },
    }); }, [store, state.stores.appInfoStore]);
    return { state: state, actions: actions };
};

export { useSendbird as u };
//# sourceMappingURL=bundle-I25ah_Bv.js.map
