import { b as __awaiter, c as __generator, _ as __assign, a as __spreadArray } from './chunks/bundle-B8Grfnrx.js';
import React__default, { useLayoutEffect, useCallback, useEffect, useMemo, useState, useRef } from 'react';
import { useUIKitConfig, UIKitConfigProvider } from '@sendbird/uikit-tools';
import { g as getCaseResolvedReplyType } from './chunks/bundle-B5_aP8LE.js';
import { a as VoicePlayerProvider } from './chunks/bundle-zOZq2Vpt.js';
import { VoiceRecorderProvider } from './VoiceRecorder/context.js';
import { u as useMediaQueryContext, M as MediaQueryProvider } from './chunks/bundle-yKqHFFfz.js';
import { a as LocalizationProvider } from './chunks/bundle-l_QLKq1Y.js';
import { GlobalModalProvider } from './hooks/useModal.js';
import { n as noop } from './chunks/bundle-CDcu1I4f.js';
import { p as pubSubFactory } from './chunks/bundle-Dx4-1s0A.js';
import { m as mapColorKeys, E as EmojiManager } from './chunks/bundle-Dkmv9H3b.js';
import cssVars from 'css-vars-ponyfill';
import { C as CACHED_MESSAGE_TEMPLATES_TOKEN_KEY, p as CACHED_MESSAGE_TEMPLATES_KEY, n as VOICE_PLAYER_ROOT_ID, q as DEFAULT_MULTIPLE_FILES_MESSAGE_LIMIT, r as DEFAULT_UPLOAD_SIZE_LIMIT, s as VOICE_RECORDER_DEFAULT_MAX, h as VOICE_RECORDER_DEFAULT_MIN } from './chunks/bundle-Ob7Cw3V-.js';
import { s as schedulerFactory, b as useUnmount, u as useOnlineStatus, a as useMarkAsDeliveredScheduler } from './chunks/bundle-WsWZ-SJW.js';
import { g as getStringSet } from './chunks/bundle-Y2KBbxRr.js';
import { i as EmojiReactionListRoot, j as MenuRoot } from './chunks/bundle-QCH8CZT8.js';
import { u as useSendbird } from './chunks/bundle-I25ah_Bv.js';
import { a as useSendbirdStore, c as createStore, b as initialState, S as SendbirdContext } from './chunks/bundle-C4OmfIXk.js';
import { u as useDeepCompareEffect } from './chunks/bundle-C5Pz6wMm.js';
import { b as ModalRoot } from './chunks/bundle-LnGQMQVt.js';
import './chunks/bundle-BTxw_tIt.js';
import './chunks/bundle-BYOddwmS.js';
import 'react-dom';
import './ui/IconButton.js';
import './ui/Button.js';
import './chunks/bundle-HspRRkmy.js';
import './ui/Icon.js';
import './chunks/bundle-CTkGIdt8.js';
import '@sendbird/chat';
import '@sendbird/chat/groupChannel';
import '@sendbird/chat/openChannel';
import './chunks/bundle-De-3zaYV.js';
import './ui/SortByRow.js';
import './chunks/bundle-CgLhYjm5.js';
import './utils/message/getOutgoingMessageState.js';
import './chunks/bundle-DYBTopZK.js';

function uikitConfigMapper(_a) {
    var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8;
    var legacyConfig = _a.legacyConfig, _9 = _a.uikitOptions, uikitOptions = _9 === void 0 ? {} : _9;
    var replyType = legacyConfig.replyType, isMentionEnabled = legacyConfig.isMentionEnabled, isReactionEnabled = legacyConfig.isReactionEnabled, disableUserProfile = legacyConfig.disableUserProfile, isVoiceMessageEnabled = legacyConfig.isVoiceMessageEnabled, isTypingIndicatorEnabledOnChannelList = legacyConfig.isTypingIndicatorEnabledOnChannelList, isMessageReceiptStatusEnabledOnChannelList = legacyConfig.isMessageReceiptStatusEnabledOnChannelList, showSearchIcon = legacyConfig.showSearchIcon;
    return {
        common: {
            enableUsingDefaultUserProfile: (_c = (_b = uikitOptions.common) === null || _b === void 0 ? void 0 : _b.enableUsingDefaultUserProfile) !== null && _c !== void 0 ? _c : (typeof disableUserProfile === 'boolean' ? !disableUserProfile : undefined),
        },
        groupChannel: {
            enableOgtag: (_d = uikitOptions.groupChannel) === null || _d === void 0 ? void 0 : _d.enableOgtag,
            enableMention: (_f = (_e = uikitOptions.groupChannel) === null || _e === void 0 ? void 0 : _e.enableMention) !== null && _f !== void 0 ? _f : isMentionEnabled,
            enableReactions: (_h = (_g = uikitOptions.groupChannel) === null || _g === void 0 ? void 0 : _g.enableReactions) !== null && _h !== void 0 ? _h : isReactionEnabled,
            enableReactionsSupergroup: (_j = uikitOptions.groupChannel) === null || _j === void 0 ? void 0 : _j.enableReactionsSupergroup,
            enableTypingIndicator: (_k = uikitOptions.groupChannel) === null || _k === void 0 ? void 0 : _k.enableTypingIndicator,
            enableVoiceMessage: (_m = (_l = uikitOptions.groupChannel) === null || _l === void 0 ? void 0 : _l.enableVoiceMessage) !== null && _m !== void 0 ? _m : isVoiceMessageEnabled,
            replyType: (_p = (_o = uikitOptions.groupChannel) === null || _o === void 0 ? void 0 : _o.replyType) !== null && _p !== void 0 ? _p : (replyType != null ? getCaseResolvedReplyType(replyType).lowerCase : undefined),
            threadReplySelectType: (_q = uikitOptions.groupChannel) === null || _q === void 0 ? void 0 : _q.threadReplySelectType,
            input: {
                enableDocument: (_s = (_r = uikitOptions.groupChannel) === null || _r === void 0 ? void 0 : _r.input) === null || _s === void 0 ? void 0 : _s.enableDocument,
            },
            typingIndicatorTypes: (_t = uikitOptions.groupChannel) === null || _t === void 0 ? void 0 : _t.typingIndicatorTypes,
            enableFeedback: (_u = uikitOptions.groupChannel) === null || _u === void 0 ? void 0 : _u.enableFeedback,
            enableSuggestedReplies: (_v = uikitOptions.groupChannel) === null || _v === void 0 ? void 0 : _v.enableSuggestedReplies,
            showSuggestedRepliesFor: (_w = uikitOptions.groupChannel) === null || _w === void 0 ? void 0 : _w.showSuggestedRepliesFor,
            suggestedRepliesDirection: (_x = uikitOptions.groupChannel) === null || _x === void 0 ? void 0 : _x.suggestedRepliesDirection,
            enableMarkdownForUserMessage: (_y = uikitOptions.groupChannel) === null || _y === void 0 ? void 0 : _y.enableMarkdownForUserMessage,
            enableFormTypeMessage: (_z = uikitOptions.groupChannel) === null || _z === void 0 ? void 0 : _z.enableFormTypeMessage,
        },
        groupChannelList: {
            enableTypingIndicator: (_1 = (_0 = uikitOptions.groupChannelList) === null || _0 === void 0 ? void 0 : _0.enableTypingIndicator) !== null && _1 !== void 0 ? _1 : isTypingIndicatorEnabledOnChannelList,
            enableMessageReceiptStatus: (_3 = (_2 = uikitOptions.groupChannelList) === null || _2 === void 0 ? void 0 : _2.enableMessageReceiptStatus) !== null && _3 !== void 0 ? _3 : isMessageReceiptStatusEnabledOnChannelList,
        },
        groupChannelSettings: {
            enableMessageSearch: (_5 = (_4 = uikitOptions.groupChannelSettings) === null || _4 === void 0 ? void 0 : _4.enableMessageSearch) !== null && _5 !== void 0 ? _5 : showSearchIcon,
        },
        openChannel: {
            enableOgtag: (_6 = uikitOptions.openChannel) === null || _6 === void 0 ? void 0 : _6.enableOgtag,
            input: {
                enableDocument: (_8 = (_7 = uikitOptions.openChannel) === null || _7 === void 0 ? void 0 : _7.input) === null || _8 === void 0 ? void 0 : _8.enableDocument,
            },
        },
    };
}

var uikitConfigStorage = {
    getItem: function (key) {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                return [2 /*return*/, (_a = localStorage.getItem(key)) !== null && _a !== void 0 ? _a : null];
            });
        });
    },
    setItem: function (key, value) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, localStorage.setItem(key, value)];
            });
        });
    },
};

var VoiceMessageProvider = function (_a) {
    var children = _a.children;
    return (React__default.createElement(VoicePlayerProvider, null,
        React__default.createElement(VoiceRecorderProvider, null, children)));
};

// Logger, pretty much explains it
// in SendbirdProvider
// const [logger, setLogger] = useState(LoggerFactory(logLevel));
var LOG_LEVELS = {
    DEBUG: 'debug',
    WARNING: 'warning',
    ERROR: 'error',
    INFO: 'info',
    ALL: 'all',
};
var colorLog = function (level) {
    switch (level) {
        case LOG_LEVELS.WARNING:
            return ('color: Orange');
        case LOG_LEVELS.ERROR:
            return ('color: Red');
        default:
            return ('color: Gray');
    }
};
var printLog = function (_a) {
    var level = _a.level, title = _a.title, _b = _a.description, description = _b === void 0 ? '' : _b, _c = _a.payload, payload = _c === void 0 ? [] : _c;
    // eslint-disable-next-line no-console
    console.log.apply(console, __spreadArray(["%c SendbirdUIKit | ".concat(level, " | ").concat(new Date().toISOString(), " | ").concat(title, " ").concat(description && '|'), colorLog(level), description], payload, false));
};
var getDefaultLogger = function () { return ({
    info: noop,
    error: noop,
    warning: noop,
}); };
var LoggerFactory = function (lvl, customInterface) {
    var logInterface = printLog;
    var lvlArray = Array.isArray(lvl) ? lvl : [lvl];
    var applyLog = function (lgLvl) { return function (title, description) {
        var payload = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            payload[_i - 2] = arguments[_i];
        }
        return logInterface({
            level: lgLvl,
            title: title,
            description: description,
            payload: payload,
        });
    }; };
    return lvlArray.reduce(function (accumulator, currentLvl) {
        if (currentLvl === LOG_LEVELS.DEBUG || currentLvl === LOG_LEVELS.ALL) {
            return (__assign(__assign({}, accumulator), { info: applyLog(LOG_LEVELS.INFO), error: applyLog(LOG_LEVELS.ERROR), warning: applyLog(LOG_LEVELS.WARNING) }));
        }
        if (currentLvl === LOG_LEVELS.INFO) {
            return (__assign(__assign({}, accumulator), { info: applyLog(LOG_LEVELS.INFO) }));
        }
        if (currentLvl === LOG_LEVELS.ERROR) {
            return (__assign(__assign({}, accumulator), { error: applyLog(LOG_LEVELS.ERROR) }));
        }
        if (currentLvl === LOG_LEVELS.WARNING) {
            return (__assign(__assign({}, accumulator), { warning: applyLog(LOG_LEVELS.WARNING) }));
        }
        return __assign({}, accumulator);
    }, getDefaultLogger());
};
// TODO: Make this to hook, useLogger

var DEFAULT_COLOR_SET = {
    '--sendbird-dark-primary-500': '#4d2aa6',
    '--sendbird-dark-primary-400': '#6440C4',
    '--sendbird-dark-primary-300': '#7B53EF',
    '--sendbird-dark-primary-200': '#9E8CF5',
    '--sendbird-dark-primary-100': '#E2DFFF',
    '--sendbird-dark-secondary-500': '#007A7A',
    '--sendbird-dark-secondary-400': '#189A8D',
    '--sendbird-dark-secondary-300': '#2EBA9F',
    '--sendbird-dark-secondary-200': '#6FD6BE',
    '--sendbird-dark-secondary-100': '#AEF2DC',
    '--sendbird-dark-information-100': '#b2d9ff',
    '--sendbird-dark-error-500': '#A30E2D',
    '--sendbird-dark-error-400': '#C11F41',
    '--sendbird-dark-error-300': '#E53157',
    '--sendbird-dark-error-200': '#FF6183',
    '--sendbird-dark-error-100': '#FFABBD',
    '--sendbird-dark-background-700': '#000000',
    '--sendbird-dark-background-600': '#161616',
    '--sendbird-dark-background-500': '#2C2C2C',
    '--sendbird-dark-background-400': '#393939',
    '--sendbird-dark-background-300': '#A8A8A8',
    '--sendbird-dark-background-200': '#D9D9D9',
    '--sendbird-dark-background-100': '#F0F0F0',
    '--sendbird-dark-background-50': '#FFFFFF',
    '--sendbird-dark-overlay': 'rgba(0, 0, 0, 0.32)',
    '--sendbird-dark-onlight-01': 'rgba(0, 0, 0, 0.88)',
    '--sendbird-dark-onlight-02': 'rgba(0, 0, 0, 0.50)',
    '--sendbird-dark-onlight-03': 'rgba(0, 0, 0, 0.38)',
    '--sendbird-dark-onlight-04': 'rgba(0, 0, 0, 0.12)',
    '--sendbird-dark-ondark-01': 'rgba(255, 255, 255, 0.88)',
    '--sendbird-dark-ondark-02': 'rgba(255, 255, 255, 0.50)',
    '--sendbird-dark-ondark-03': 'rgba(255, 255, 255, 0.38)',
    '--sendbird-dark-ondark-04': 'rgba(255, 255, 255, 0.12)',
    '--sendbird-dark-shadow-01': '0 1px 5px 0 rgba(33, 34, 66, 0.04), 0 0 3px 0 rgba(0, 0, 0, 0.08), 0 2px 1px 0 rgba(0, 0, 0, 0.12)',
    '--sendbird-dark-shadow-02': '0 3px 5px -3px rgba(33, 34, 66, 0.04), 0 3px 14px 2px rgba(0, 0, 0, 0.08), 0 8px 10px 1px rgba(0, 0, 0, 0.12)',
    '--sendbird-dark-shadow-03': '0 6px 10px -5px rgba(0, 0, 0, 0.04), 0 6px 30px 5px rgba(0, 0, 0, 0.08), 0 16px 24px 2px rgba(0, 0, 0, 0.12)',
    '--sendbird-dark-shadow-04': '0 9px 15px -7px rgba(0, 0, 0, 0.04), 0 9px 46px 8px rgba(0, 0, 0, 0.08), 0 24px 38px 3px rgba(0, 0, 0, 0.12)',
    '--sendbird-dark-shadow-message-input': '0 1px 5px 0 rgba(33, 34, 66, 0.12), 0 0 1px 0 rgba(33, 34, 66, 0.16), 0 2px 1px 0 rgba(33, 34, 66, 0.08), 0 1px 5px 0 rgba(0, 0, 0, 0.12)',
    '--sendbird-light-primary-500': '#4d2aa6',
    '--sendbird-light-primary-400': '#6440C4',
    '--sendbird-light-primary-300': '#7B53EF',
    '--sendbird-light-primary-200': '#9E8CF5',
    '--sendbird-light-primary-100': '#E2DFFF',
    '--sendbird-light-secondary-500': '#007A7A',
    '--sendbird-light-secondary-400': '#189A8D',
    '--sendbird-light-secondary-300': '#2EBA9F',
    '--sendbird-light-secondary-200': '#6FD6BE',
    '--sendbird-light-secondary-100': '#AEF2DC',
    '--sendbird-light-information-100': '#b2d9ff',
    '--sendbird-light-error-500': '#A30E2D',
    '--sendbird-light-error-400': '#C11F41',
    '--sendbird-light-error-300': '#E53157',
    '--sendbird-light-error-200': '#FF6183',
    '--sendbird-light-error-100': '#FFABBD',
    '--sendbird-light-background-700': '#000000',
    '--sendbird-light-background-600': '#161616',
    '--sendbird-light-background-500': '#2C2C2C',
    '--sendbird-light-background-400': '#393939',
    '--sendbird-light-background-300': '#A8A8A8',
    '--sendbird-light-background-200': '#D9D9D9',
    '--sendbird-light-background-100': '#F0F0F0',
    '--sendbird-light-background-50': ' #FFFFFF',
    '--sendbird-light-overlay': 'rgba(0, 0, 0, 0.32)',
    '--sendbird-light-onlight-01': 'rgba(0, 0, 0, 0.88)',
    '--sendbird-light-onlight-02': 'rgba(0, 0, 0, 0.50)',
    '--sendbird-light-onlight-03': 'rgba(0, 0, 0, 0.38)',
    '--sendbird-light-onlight-04': 'rgba(0, 0, 0, 0.12)',
    '--sendbird-light-ondark-01': 'rgba(255, 255, 255, 0.88)',
    '--sendbird-light-ondark-02': 'rgba(255, 255, 255, 0.50)',
    '--sendbird-light-ondark-03': 'rgba(255, 255, 255, 0.38)',
    '--sendbird-light-ondark-04': 'rgba(255, 255, 255, 0.12)',
    '--sendbird-light-shadow-01': '0 1px 5px 0 rgba(33, 34, 66, 0.04), 0 0 3px 0 rgba(0, 0, 0, 0.08), 0 2px 1px 0 rgba(0, 0, 0, 0.12)',
    '--sendbird-light-shadow-02': '0 3px 5px -3px rgba(33, 34, 66, 0.04), 0 3px 14px 2px rgba(0, 0, 0, 0.08), 0 8px 10px 1px rgba(0, 0, 0, 0.12)',
    '--sendbird-light-shadow-03': '0 6px 10px -5px rgba(0, 0, 0, 0.04), 0 6px 30px 5px rgba(0, 0, 0, 0.08), 0 16px 24px 2px rgba(0, 0, 0, 0.12)',
    '--sendbird-light-shadow-04': '0 9px 15px -7px rgba(0, 0, 0, 0.04), 0 9px 46px 8px rgba(0, 0, 0, 0.08), 0 24px 38px 3px rgba(0, 0, 0, 0.12)',
    '--sendbird-light-shadow-message-input': '0 1px 5px 0 rgba(33, 34, 66, 0.12), 0 0 1px 0 rgba(33, 34, 66, 0.16), 0 2px 1px 0 rgba(33, 34, 66, 0.08), 0 1px 5px 0 rgba(0, 0, 0, 0.12)',
};
var isEmpty = function (obj) {
    if (obj === null || obj === undefined) {
        return true;
    }
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            return false;
        }
    }
    return JSON.stringify(obj) === JSON.stringify({});
};
var useTheme = function (overrides) {
    useLayoutEffect(function () {
        if (!isEmpty(overrides)) {
            var variables = __assign(__assign({}, DEFAULT_COLOR_SET), mapColorKeys(overrides));
            cssVars({ variables: variables });
        }
    }, [overrides]);
};

var MESSAGE_TEMPLATES_FETCH_LIMIT = 20;
/**
 * Takes JSON parsed template and then returns processed message template for storing it in global state.
 */
var getProcessedTemplate = function (parsedTemplate) {
    return {
        version: Number(parsedTemplate.ui_template.version),
        uiTemplate: JSON.stringify(parsedTemplate.ui_template.body.items),
        colorVariables: parsedTemplate.color_variables,
    };
};
var getProcessedTemplatesMap = function (parsedTemplates) {
    var processedTemplates = {};
    parsedTemplates.forEach(function (template) {
        processedTemplates[template.key] = getProcessedTemplate(template);
    });
    return processedTemplates;
};
function useMessageTemplateUtils(_a) {
    var _this = this;
    var _b;
    var sdk = _a.sdk, logger = _a.logger, appInfoStore = _a.appInfoStore, actions = _a.actions;
    var messageTemplatesInfo = appInfoStore === null || appInfoStore === void 0 ? void 0 : appInfoStore.messageTemplatesInfo;
    var getCachedTemplate = useCallback(function (key) {
        var _a, _b;
        if (!messageTemplatesInfo)
            return null;
        var cachedTemplate = null;
        var cachedMessageTemplates = (_a = messageTemplatesInfo === null || messageTemplatesInfo === void 0 ? void 0 : messageTemplatesInfo.templatesMap) !== null && _a !== void 0 ? _a : null;
        if (cachedMessageTemplates) {
            cachedTemplate = (_b = cachedMessageTemplates[key]) !== null && _b !== void 0 ? _b : null;
        }
        return cachedTemplate;
    }, [appInfoStore === null || appInfoStore === void 0 ? void 0 : appInfoStore.messageTemplatesInfo]);
    /**
     * Fetches a single message template by given key and then
     * returns processed template for updating templates info in global state.
     * If no such templates exists (error) or any error occurs in response, return null.
     */
    var fetchAllMessageTemplates = function (readySdk) { return __awaiter(_this, void 0, void 0, function () {
        var hasMore, paginationToken, fetchedTemplates, res;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    hasMore = true;
                    paginationToken = null;
                    fetchedTemplates = [];
                    _a.label = 1;
                case 1:
                    if (!hasMore) return [3 /*break*/, 3];
                    return [4 /*yield*/, readySdk.message.getMessageTemplatesByToken(paginationToken, { limit: MESSAGE_TEMPLATES_FETCH_LIMIT })];
                case 2:
                    res = _a.sent();
                    hasMore = res.hasMore;
                    paginationToken = res.token;
                    res.templates.forEach(function (messageTemplate) {
                        fetchedTemplates.push(JSON.parse(messageTemplate.template));
                    });
                    return [3 /*break*/, 1];
                case 3: return [2 /*return*/, fetchedTemplates];
            }
        });
    }); };
    var initializeMessageTemplatesInfo = function (readySdk) { return __awaiter(_this, void 0, void 0, function () {
        var sdkMessageTemplateToken, cachedMessageTemplatesToken, cachedMessageTemplates, parsedTemplates, newMessageTemplatesInfo, parsedTemplates, newMessageTemplatesInfo;
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    sdkMessageTemplateToken = (_a = readySdk.appInfo) === null || _a === void 0 ? void 0 : _a.messageTemplateInfo.token;
                    /**
                     * no sdkMessageTemplateToken => no templates => clear cached
                     */
                    if (!sdkMessageTemplateToken) {
                        localStorage.removeItem(CACHED_MESSAGE_TEMPLATES_TOKEN_KEY);
                        localStorage.removeItem(CACHED_MESSAGE_TEMPLATES_KEY);
                        return [2 /*return*/];
                    }
                    cachedMessageTemplatesToken = localStorage.getItem(CACHED_MESSAGE_TEMPLATES_TOKEN_KEY);
                    cachedMessageTemplates = localStorage.getItem(CACHED_MESSAGE_TEMPLATES_KEY);
                    if (!(!cachedMessageTemplatesToken
                        || cachedMessageTemplatesToken !== sdkMessageTemplateToken)) return [3 /*break*/, 2];
                    return [4 /*yield*/, fetchAllMessageTemplates(readySdk)];
                case 1:
                    parsedTemplates = _b.sent();
                    newMessageTemplatesInfo = {
                        token: sdkMessageTemplateToken,
                        templatesMap: getProcessedTemplatesMap(parsedTemplates),
                    };
                    actions.initMessageTemplateInfo({ payload: newMessageTemplatesInfo });
                    localStorage.setItem(CACHED_MESSAGE_TEMPLATES_TOKEN_KEY, sdkMessageTemplateToken);
                    localStorage.setItem(CACHED_MESSAGE_TEMPLATES_KEY, JSON.stringify(parsedTemplates));
                    return [3 /*break*/, 3];
                case 2:
                    if (cachedMessageTemplatesToken
                        && cachedMessageTemplatesToken === sdkMessageTemplateToken
                        && cachedMessageTemplates) {
                        parsedTemplates = JSON.parse(cachedMessageTemplates);
                        newMessageTemplatesInfo = {
                            token: sdkMessageTemplateToken,
                            templatesMap: getProcessedTemplatesMap(parsedTemplates),
                        };
                        actions.initMessageTemplateInfo({ payload: newMessageTemplatesInfo });
                    }
                    _b.label = 3;
                case 3: return [2 /*return*/];
            }
        });
    }); };
    /**
     * If given message is a template message with template key and if the key does not exist in the cache,
     * update the cache by fetching the template.
     */
    var updateMessageTemplatesInfo = useCallback(function (templateKeys, messageId, requestedAt) { return __awaiter(_this, void 0, void 0, function () {
        var newParsedTemplates, hasMore, token, result, e_1, cachedMessageTemplates, parsedTemplates_1, existingKeys_1;
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    actions.upsertWaitingTemplateKeys({ keys: templateKeys, requestedAt: requestedAt });
                    newParsedTemplates = [];
                    _b.label = 1;
                case 1:
                    _b.trys.push([1, 5, , 6]);
                    hasMore = true;
                    token = null;
                    _b.label = 2;
                case 2:
                    if (!hasMore) return [3 /*break*/, 4];
                    return [4 /*yield*/, sdk.message.getMessageTemplatesByToken(token, {
                            keys: templateKeys,
                        })];
                case 3:
                    result = _b.sent();
                    result.templates.forEach(function (newTemplate) {
                        newParsedTemplates.push(JSON.parse(newTemplate.template));
                    });
                    hasMore = result.hasMore;
                    token = result.token;
                    return [3 /*break*/, 2];
                case 4: return [3 /*break*/, 6];
                case 5:
                    e_1 = _b.sent();
                    (_a = logger === null || logger === void 0 ? void 0 : logger.error) === null || _a === void 0 ? void 0 : _a.call(logger, 'Sendbird | fetchProcessedMessageTemplates failed', e_1, templateKeys);
                    return [3 /*break*/, 6];
                case 6:
                    if (newParsedTemplates.length > 0) {
                        cachedMessageTemplates = localStorage.getItem(CACHED_MESSAGE_TEMPLATES_KEY);
                        if (cachedMessageTemplates) {
                            parsedTemplates_1 = JSON.parse(cachedMessageTemplates);
                            existingKeys_1 = parsedTemplates_1.map(function (parsedTemplate) { return parsedTemplate.key; });
                            newParsedTemplates.forEach(function (newParsedTemplate) {
                                if (!existingKeys_1.includes(newParsedTemplate.key)) {
                                    parsedTemplates_1.push(newParsedTemplate);
                                }
                            });
                            localStorage.setItem(CACHED_MESSAGE_TEMPLATES_KEY, JSON.stringify(parsedTemplates_1));
                        }
                        else {
                            localStorage.setItem(CACHED_MESSAGE_TEMPLATES_KEY, JSON.stringify([newParsedTemplates]));
                        }
                        // Update memory
                        actions.upsertMessageTemplates({
                            payload: newParsedTemplates.map(function (newParsedTemplate) {
                                return {
                                    key: newParsedTemplate.key,
                                    template: getProcessedTemplate(newParsedTemplate),
                                };
                            }),
                        });
                    }
                    else {
                        actions.markErrorWaitingTemplateKeys({
                            keys: templateKeys,
                            messageId: messageId,
                        });
                    }
                    return [2 /*return*/];
            }
        });
    }); }, [
        actions.upsertMessageTemplates,
        actions.upsertWaitingTemplateKeys,
        (_b = sdk === null || sdk === void 0 ? void 0 : sdk.message) === null || _b === void 0 ? void 0 : _b.getMessageTemplatesByToken,
    ]);
    return {
        getCachedTemplate: getCachedTemplate,
        updateMessageTemplatesInfo: updateMessageTemplatesInfo,
        initializeMessageTemplatesInfo: initializeMessageTemplatesInfo,
    };
}

var useHTMLTextDirection = function (direction) {
    useEffect(function () {
        /**
         * It sets the 'dir' attribute of the closest parent <div> element of the element with VOICE_PLAYER_ROOT_ID cause:
         * - An empty <div> element is created in the VoiceMessageProvider, which is the highest-level <div> element within the SendbirdProvider.
         * - It tries to find the nearest parent <div> element within the SendbirdProvider and sets 'dir' attribute,
         * ensuring that the directionality is applied correctly.
         * */
        var targetElement = document.getElementById(VOICE_PLAYER_ROOT_ID);
        targetElement.parentElement.dir = direction;
    }, [direction]);
};

function useMarkAsReadScheduler(_a, _b) {
    var isConnected = _a.isConnected;
    var logger = _b.logger;
    var markAsReadScheduler = useMemo(function () { return schedulerFactory({
        logger: logger,
        cb: function (channel) {
            try {
                channel.markAsRead();
            }
            catch (error) {
                logger.warning('Channel: Mark as delivered failed', { channel: channel, error: error });
            }
        },
    }); }, []);
    useEffect(function () {
        // for simplicity, we clear the queue when the connection is lost
        if (!isConnected) {
            markAsReadScheduler.clear();
        }
    }, [isConnected]);
    useUnmount(function () { markAsReadScheduler.clear(); });
    return markAsReadScheduler;
}

/**
 * SendbirdContext - Manager
 */
var SendbirdContextManager = function (_a) {
    var _b;
    var appId = _a.appId, userId = _a.userId, accessToken = _a.accessToken, customApiHost = _a.customApiHost, customWebSocketHost = _a.customWebSocketHost, configureSession = _a.configureSession, _c = _a.theme, theme = _c === void 0 ? 'light' : _c, _d = _a.config, config = _d === void 0 ? {} : _d, _e = _a.nickname, nickname = _e === void 0 ? '' : _e, colorSet = _a.colorSet, _f = _a.profileUrl, profileUrl = _f === void 0 ? '' : _f, voiceRecord = _a.voiceRecord, userListQuery = _a.userListQuery, _g = _a.imageCompression, imageCompression = _g === void 0 ? {} : _g, _h = _a.allowProfileEdit, allowProfileEdit = _h === void 0 ? false : _h, _j = _a.disableMarkAsDelivered, disableMarkAsDelivered = _j === void 0 ? false : _j, renderUserProfile = _a.renderUserProfile, _onUserProfileMessage = _a.onUserProfileMessage, _onStartDirectMessage = _a.onStartDirectMessage, _k = _a.isUserIdUsedForNickname, isUserIdUsedForNickname = _k === void 0 ? true : _k, sdkInitParams = _a.sdkInitParams, customExtensionParams = _a.customExtensionParams, _l = _a.isMultipleFilesMessageEnabled, isMultipleFilesMessageEnabled = _l === void 0 ? false : _l, eventHandlers = _a.eventHandlers, _m = _a.htmlTextDirection, htmlTextDirection = _m === void 0 ? 'ltr' : _m, _o = _a.forceLeftToRightMessageLayout, forceLeftToRightMessageLayout = _o === void 0 ? false : _o;
    var onStartDirectMessage = _onStartDirectMessage !== null && _onStartDirectMessage !== void 0 ? _onStartDirectMessage : _onUserProfileMessage;
    var _p = config.logLevel, logLevel = _p === void 0 ? '' : _p, _q = config.userMention, userMention = _q === void 0 ? {} : _q, _r = config.isREMUnitEnabled, isREMUnitEnabled = _r === void 0 ? false : _r, customPubSub = config.pubSub;
    var isMobile = useMediaQueryContext().isMobile;
    var _s = useState(LoggerFactory(logLevel)), logger = _s[0], setLogger = _s[1];
    var pubSub = useState(customPubSub !== null && customPubSub !== void 0 ? customPubSub : pubSubFactory())[0];
    var _t = useSendbirdStore(), state = _t.state, updateState = _t.updateState;
    var actions = useSendbird().actions;
    var _u = state.stores, sdkStore = _u.sdkStore, appInfoStore = _u.appInfoStore;
    var _v = useUIKitConfig(), configs = _v.configs, configsWithAppAttr = _v.configsWithAppAttr, initDashboardConfigs = _v.initDashboardConfigs;
    var sdkInitialized = sdkStore.initialized;
    var sdk = sdkStore === null || sdkStore === void 0 ? void 0 : sdkStore.sdk;
    var _w = (_b = sdk === null || sdk === void 0 ? void 0 : sdk.appInfo) !== null && _b !== void 0 ? _b : {}, uploadSizeLimit = _w.uploadSizeLimit, multipleFilesMessageFileCountLimit = _w.multipleFilesMessageFileCountLimit;
    useTheme(colorSet);
    var _x = useMessageTemplateUtils({
        sdk: sdk,
        logger: logger,
        appInfoStore: appInfoStore,
        actions: actions,
    }), getCachedTemplate = _x.getCachedTemplate, updateMessageTemplatesInfo = _x.updateMessageTemplatesInfo, initializeMessageTemplatesInfo = _x.initializeMessageTemplatesInfo;
    // Reconnect when necessary
    useEffect(function () {
        actions.connect({
            appId: appId,
            userId: userId,
            accessToken: accessToken,
            isUserIdUsedForNickname: isUserIdUsedForNickname,
            isMobile: isMobile,
            logger: logger,
            nickname: nickname,
            profileUrl: profileUrl,
            configureSession: configureSession,
            customApiHost: customApiHost,
            customWebSocketHost: customWebSocketHost,
            sdkInitParams: sdkInitParams,
            customExtensionParams: customExtensionParams,
            initDashboardConfigs: initDashboardConfigs,
            eventHandlers: eventHandlers,
            initializeMessageTemplatesInfo: initializeMessageTemplatesInfo,
        });
    }, [appId, userId]);
    // Disconnect on unmount
    useUnmount(function () {
        actions.disconnect({ logger: logger });
    });
    // to create a pubsub to communicate between parent and child
    useEffect(function () {
        setLogger(LoggerFactory(logLevel));
    }, [logLevel]);
    // should move to reducer
    var _y = useState(theme), currentTheme = _y[0], setCurrentTheme = _y[1];
    useEffect(function () {
        setCurrentTheme(theme);
    }, [theme]);
    useEffect(function () {
        var body = document.querySelector('body');
        body === null || body === void 0 ? void 0 : body.classList.remove('sendbird-experimental__rem__units');
        if (isREMUnitEnabled) {
            body === null || body === void 0 ? void 0 : body.classList.add('sendbird-experimental__rem__units');
        }
    }, [isREMUnitEnabled]);
    // add-remove theme from body
    useEffect(function () {
        logger.info('Setup theme', "Theme: ".concat(currentTheme));
        try {
            var body = document.querySelector('body');
            body === null || body === void 0 ? void 0 : body.classList.remove('sendbird-theme--light');
            body === null || body === void 0 ? void 0 : body.classList.remove('sendbird-theme--dark');
            body === null || body === void 0 ? void 0 : body.classList.add("sendbird-theme--".concat(currentTheme || 'light'));
            logger.info('Finish setup theme');
            // eslint-disable-next-line no-empty
        }
        catch (e) {
            logger.warning('Setup theme failed', "".concat(e));
        }
        return function () {
            try {
                var body = document.querySelector('body');
                body === null || body === void 0 ? void 0 : body.classList.remove('sendbird-theme--light');
                body === null || body === void 0 ? void 0 : body.classList.remove('sendbird-theme--dark');
                // eslint-disable-next-line no-empty
            }
            catch (_a) { }
        };
    }, [currentTheme]);
    useHTMLTextDirection(htmlTextDirection);
    var isOnline = useOnlineStatus(sdkStore.sdk, logger);
    var markAsReadScheduler = useMarkAsReadScheduler({ isConnected: isOnline }, { logger: logger });
    var markAsDeliveredScheduler = useMarkAsDeliveredScheduler({ isConnected: isOnline }, { logger: logger });
    /**
     * Feature Configuration - TODO
     * This will be moved into the UIKitConfigProvider, aftering Dashboard applies
     */
    var uikitMultipleFilesMessageLimit = useMemo(function () {
        return Math.min(DEFAULT_MULTIPLE_FILES_MESSAGE_LIMIT, multipleFilesMessageFileCountLimit !== null && multipleFilesMessageFileCountLimit !== void 0 ? multipleFilesMessageFileCountLimit : Number.MAX_SAFE_INTEGER);
    }, [multipleFilesMessageFileCountLimit]);
    // Emoji Manager
    var emojiManager = useMemo(function () {
        return new EmojiManager({
            sdk: sdk,
            logger: logger,
        });
    }, [sdkStore.initialized]);
    var uikitConfigs = useMemo(function () { return ({
        common: {
            enableUsingDefaultUserProfile: configs.common.enableUsingDefaultUserProfile,
        },
        groupChannel: {
            enableOgtag: sdkInitialized && configsWithAppAttr(sdk).groupChannel.channel.enableOgtag,
            enableTypingIndicator: configs.groupChannel.channel.enableTypingIndicator,
            enableReactions: sdkInitialized && configsWithAppAttr(sdk).groupChannel.channel.enableReactions,
            enableMention: configs.groupChannel.channel.enableMention,
            replyType: configs.groupChannel.channel.replyType,
            threadReplySelectType: configs.groupChannel.channel.threadReplySelectType,
            enableVoiceMessage: configs.groupChannel.channel.enableVoiceMessage,
            enableDocument: configs.groupChannel.channel.input.enableDocument,
            typingIndicatorTypes: configs.groupChannel.channel.typingIndicatorTypes,
            enableFeedback: configs.groupChannel.channel.enableFeedback,
            enableSuggestedReplies: configs.groupChannel.channel.enableSuggestedReplies,
            showSuggestedRepliesFor: configs.groupChannel.channel.showSuggestedRepliesFor,
            suggestedRepliesDirection: configs.groupChannel.channel.suggestedRepliesDirection,
            enableMarkdownForUserMessage: configs.groupChannel.channel.enableMarkdownForUserMessage,
            enableFormTypeMessage: configs.groupChannel.channel.enableFormTypeMessage,
            enableReactionsSupergroup: sdkInitialized && configsWithAppAttr(sdk).groupChannel.channel.enableReactionsSupergroup,
        },
        groupChannelList: {
            enableTypingIndicator: configs.groupChannel.channelList.enableTypingIndicator,
            enableMessageReceiptStatus: configs.groupChannel.channelList.enableMessageReceiptStatus,
        },
        groupChannelSettings: {
            enableMessageSearch: sdkInitialized && configsWithAppAttr(sdk).groupChannel.setting.enableMessageSearch,
        },
        openChannel: {
            enableOgtag: sdkInitialized && configsWithAppAttr(sdk).openChannel.channel.enableOgtag,
            enableDocument: configs.openChannel.channel.input.enableDocument,
        },
    }); }, [
        sdkInitialized,
        configs.common,
        configs.groupChannel.channel,
        configs.groupChannel.channelList,
        configs.groupChannel.setting,
        configs.openChannel.channel,
    ]);
    var storeState = useMemo(function () { return ({
        stores: {
            sdkStore: state.stores.sdkStore,
            userStore: state.stores.userStore,
            appInfoStore: state.stores.appInfoStore,
        },
    }); }, [
        state.stores.sdkStore,
        state.stores.userStore,
        state.stores.appInfoStore,
    ]);
    var uikitUploadSizeLimit = useMemo(function () { return (uploadSizeLimit !== null && uploadSizeLimit !== void 0 ? uploadSizeLimit : DEFAULT_UPLOAD_SIZE_LIMIT); }, [uploadSizeLimit, DEFAULT_UPLOAD_SIZE_LIMIT]);
    var configImageCompression = useMemo(function () { return (__assign({ compressionRate: 0.7, outputFormat: 'preserve' }, imageCompression)); }, [imageCompression]);
    var configVoiceRecord = useMemo(function () {
        var _a, _b;
        return ({
            maxRecordingTime: (_a = voiceRecord === null || voiceRecord === void 0 ? void 0 : voiceRecord.maxRecordingTime) !== null && _a !== void 0 ? _a : VOICE_RECORDER_DEFAULT_MAX,
            minRecordingTime: (_b = voiceRecord === null || voiceRecord === void 0 ? void 0 : voiceRecord.minRecordingTime) !== null && _b !== void 0 ? _b : VOICE_RECORDER_DEFAULT_MIN,
        });
    }, [
        voiceRecord === null || voiceRecord === void 0 ? void 0 : voiceRecord.maxRecordingTime,
        voiceRecord === null || voiceRecord === void 0 ? void 0 : voiceRecord.minRecordingTime,
    ]);
    var configUserMention = useMemo(function () { return ({
        maxMentionCount: (userMention === null || userMention === void 0 ? void 0 : userMention.maxMentionCount) || 10,
        maxSuggestionCount: (userMention === null || userMention === void 0 ? void 0 : userMention.maxSuggestionCount) || 15,
    }); }, [
        userMention === null || userMention === void 0 ? void 0 : userMention.maxMentionCount,
        userMention === null || userMention === void 0 ? void 0 : userMention.maxSuggestionCount,
    ]);
    var deprecatedConfigs = useMemo(function () { return ({
        disableUserProfile: !configs.common.enableUsingDefaultUserProfile,
        isReactionEnabled: sdkInitialized && configsWithAppAttr(sdk).groupChannel.channel.enableReactions,
        isMentionEnabled: configs.groupChannel.channel.enableMention,
        isVoiceMessageEnabled: configs.groupChannel.channel.enableVoiceMessage,
        replyType: getCaseResolvedReplyType(configs.groupChannel.channel.replyType).upperCase,
        isTypingIndicatorEnabledOnChannelList: configs.groupChannel.channelList.enableTypingIndicator,
        isMessageReceiptStatusEnabledOnChannelList: configs.groupChannel.channelList.enableMessageReceiptStatus,
        showSearchIcon: sdkInitialized && configsWithAppAttr(sdk).groupChannel.setting.enableMessageSearch,
    }); }, [
        sdkInitialized,
        configsWithAppAttr,
        configs.common.enableUsingDefaultUserProfile,
        configs.groupChannel.channel.enableReactions,
        configs.groupChannel.channel.enableMention,
        configs.groupChannel.channel.enableVoiceMessage,
        configs.groupChannel.channel.replyType,
        configs.groupChannel.channelList.enableTypingIndicator,
        configs.groupChannel.channelList.enableMessageReceiptStatus,
        configs.groupChannel.setting.enableMessageSearch,
    ]);
    var configState = useMemo(function () { return ({
        config: __assign(__assign({ disableMarkAsDelivered: disableMarkAsDelivered, renderUserProfile: renderUserProfile, onStartDirectMessage: onStartDirectMessage, onUserProfileMessage: onStartDirectMessage, // legacy of onStartDirectMessage
            allowProfileEdit: allowProfileEdit, isOnline: isOnline, userId: userId, appId: appId, accessToken: accessToken, theme: currentTheme, setCurrentTheme: setCurrentTheme, setCurrenttheme: setCurrentTheme, // deprecated: typo
            isMultipleFilesMessageEnabled: isMultipleFilesMessageEnabled, uikitMultipleFilesMessageLimit: uikitMultipleFilesMessageLimit, logger: logger, pubSub: pubSub, userListQuery: userListQuery, htmlTextDirection: htmlTextDirection, forceLeftToRightMessageLayout: forceLeftToRightMessageLayout, markAsReadScheduler: markAsReadScheduler, markAsDeliveredScheduler: markAsDeliveredScheduler, uikitUploadSizeLimit: uikitUploadSizeLimit, imageCompression: configImageCompression, voiceRecord: configVoiceRecord, userMention: configUserMention }, uikitConfigs), deprecatedConfigs),
    }); }, [
        disableMarkAsDelivered,
        renderUserProfile,
        onStartDirectMessage,
        allowProfileEdit,
        isOnline,
        userId,
        appId,
        accessToken,
        currentTheme,
        setCurrentTheme,
        isMultipleFilesMessageEnabled,
        uikitMultipleFilesMessageLimit,
        logger,
        pubSub,
        userListQuery,
        htmlTextDirection,
        forceLeftToRightMessageLayout,
        markAsReadScheduler,
        markAsDeliveredScheduler,
        uikitUploadSizeLimit,
        configImageCompression,
        configVoiceRecord,
        configUserMention,
        uikitConfigs,
        deprecatedConfigs,
    ]);
    var utilsState = useMemo(function () { return ({
        utils: {
            updateMessageTemplatesInfo: updateMessageTemplatesInfo,
            getCachedTemplate: getCachedTemplate,
        },
    }); }, [
        updateMessageTemplatesInfo,
        getCachedTemplate,
    ]);
    useDeepCompareEffect(function () {
        updateState(__assign(__assign(__assign(__assign({}, storeState), utilsState), configState), { eventHandlers: eventHandlers, emojiManager: emojiManager }));
    }, [
        storeState,
        configState,
        eventHandlers,
        emojiManager,
        utilsState,
    ]);
    return null;
};
var InternalSendbirdProvider = function (_a) {
    var children = _a.children, stringSet = _a.stringSet, breakpoint = _a.breakpoint, dateLocale = _a.dateLocale;
    var storeRef = useRef(createStore(initialState));
    var localeStringSet = useMemo(function () {
        return __assign(__assign({}, getStringSet('en')), stringSet);
    }, [stringSet]);
    return (React__default.createElement(SendbirdContext.Provider, { value: storeRef.current },
        React__default.createElement(MediaQueryProvider, { logger: storeRef.current.getState().config.logger, breakpoint: breakpoint },
            React__default.createElement(LocalizationProvider, { stringSet: localeStringSet, dateLocale: dateLocale },
                React__default.createElement(VoiceMessageProvider, null,
                    React__default.createElement(GlobalModalProvider, null, children)))),
        React__default.createElement(EmojiReactionListRoot, null),
        React__default.createElement(ModalRoot, null),
        React__default.createElement(MenuRoot, null)));
};
var SendbirdContextProvider = function (props) {
    var children = props.children;
    return (React__default.createElement(InternalSendbirdProvider, { stringSet: props.stringSet, breakpoint: props.breakpoint, dateLocale: props.dateLocale },
        React__default.createElement(SendbirdContextManager, __assign({}, props)),
        children));
};

// For Exportation
var SendbirdProvider = function (props) {
    var localConfigs = uikitConfigMapper({
        legacyConfig: {
            replyType: props.replyType,
            isMentionEnabled: props.isMentionEnabled,
            isReactionEnabled: props.isReactionEnabled,
            disableUserProfile: props.disableUserProfile,
            isVoiceMessageEnabled: props.isVoiceMessageEnabled,
            isTypingIndicatorEnabledOnChannelList: props.isTypingIndicatorEnabledOnChannelList,
            isMessageReceiptStatusEnabledOnChannelList: props.isMessageReceiptStatusEnabledOnChannelList,
            showSearchIcon: props.showSearchIcon,
        },
        uikitOptions: props.uikitOptions,
    });
    return (React__default.createElement(UIKitConfigProvider, { storage: uikitConfigStorage, localConfigs: {
            common: localConfigs === null || localConfigs === void 0 ? void 0 : localConfigs.common,
            groupChannel: {
                channel: localConfigs === null || localConfigs === void 0 ? void 0 : localConfigs.groupChannel,
                channelList: localConfigs === null || localConfigs === void 0 ? void 0 : localConfigs.groupChannelList,
                setting: localConfigs === null || localConfigs === void 0 ? void 0 : localConfigs.groupChannelSettings,
            },
            openChannel: {
                channel: localConfigs === null || localConfigs === void 0 ? void 0 : localConfigs.openChannel,
            },
        } },
        React__default.createElement(SendbirdContextProvider, __assign({}, props))));
};
var withSendbirdContext = function (OriginalComponent, mapStoreToProps) {
    var ContextAwareComponent = function (props) {
        var _a = useSendbird(), state = _a.state, actions = _a.actions;
        var context = __assign(__assign({}, state), actions);
        if (!mapStoreToProps || typeof mapStoreToProps !== 'function') {
            // eslint-disable-next-line no-console
            console.warn('Second parameter to withSendbirdContext must be a pure function');
        }
        var mergedProps = (mapStoreToProps && typeof mapStoreToProps === 'function')
            ? __assign(__assign({}, mapStoreToProps(context)), props) : __assign(__assign({}, context), props);
        return React__default.createElement(React__default.Fragment, null,
            React__default.createElement(OriginalComponent, __assign({}, mergedProps)));
    };
    var componentName = OriginalComponent.displayName || OriginalComponent.name || 'Component';
    ContextAwareComponent.displayName = "SendbirdAware".concat(componentName);
    return ContextAwareComponent;
};
/**
 * @deprecated This function is deprecated. Use `useSendbirdStateContext` instead.
 * */
var withSendBird = withSendbirdContext;

export { SendbirdProvider, SendbirdProvider as default, withSendBird };
//# sourceMappingURL=SendbirdProvider.js.map
