import { _ as __assign, a as __spreadArray, b as __awaiter, c as __generator } from './bundle-B8Grfnrx.js';
import React__default, { useState, useRef, useEffect, useContext, useMemo } from 'react';
import { GroupChannelHandler } from '@sendbird/chat/groupChannel';
import { GroupChannel } from '../GroupChannel.js';
import { u as useGroupChannelList, c as GroupChannelListProvider } from './bundle-Bc6hXWJF.js';
import { GroupChannelListHeader } from '../GroupChannelList/components/GroupChannelListHeader.js';
import EditUserProfile from '../EditUserProfile.js';
import PlaceHolder, { PlaceHolderTypes } from '../ui/PlaceHolder.js';
import { u as useOnScrollPositionChangeDetector } from './bundle-DqR5RvpV.js';
import { u as useSendbird } from './bundle-I25ah_Bv.js';
import { GroupChannelPreviewAction } from '../GroupChannelList/components/GroupChannelPreviewAction.js';
import { GroupChannelListItem } from '../GroupChannelList/components/GroupChannelListItem.js';
import IconButton from '../ui/IconButton.js';
import Icon, { IconTypes, IconColors } from '../ui/Icon.js';
import { L as LocalizationContext } from './bundle-l_QLKq1Y.js';
import { u as useMediaQueryContext } from './bundle-yKqHFFfz.js';
import { M as Modal } from './bundle-LnGQMQVt.js';
import { L as Label, b as LabelColors, a as LabelTypography } from './bundle-HspRRkmy.js';
import { ButtonTypes } from '../ui/Button.js';
import { UserListItem } from '../ui/UserListItem.js';
import { n as noop } from './bundle-CDcu1I4f.js';
import { c as createStore, u as useStore, s as shimExports } from './bundle-C4OmfIXk.js';
import { getCreateGroupChannel, getSdk } from '../sendbirdSelectors.js';
import '@sendbird/uikit-tools';
import { u as useVoicePlayerContext, b as ALL } from './bundle-zOZq2Vpt.js';
import '../VoiceRecorder/context.js';
import '../hooks/useModal.js';
import './bundle-Dkmv9H3b.js';
import 'css-vars-ponyfill';
import '@sendbird/chat';
import { A as APP_LAYOUT_ROOT } from './bundle-QCH8CZT8.js';
import '@sendbird/chat/openChannel';
import 'react-dom';
import './bundle-CgLhYjm5.js';
import './bundle-D4BlmM5H.js';
import './bundle-DZJe3dCn.js';
import './bundle-DgFzcADJ.js';
import '../ui/Header.js';
import './bundle-BciLDE6M.js';
import './bundle-DED6q4Ti.js';
import '../ui/MessageInput.js';
import './bundle-Dd7rgmeQ.js';
import '../ui/ReactionButton.js';
import '../ui/ReactionBadge.js';
import './bundle-BYqblmEM.js';
import '../Message/context.js';
import './bundle-De-3zaYV.js';
import '@sendbird/chat/message';
import '../ui/ThreadReplies.js';
import './bundle-CwHldvb8.js';
import '../ui/TemplateMessageItemBody.js';
import '../ui/FeedbackIconButton.js';
import '../ui/Input.js';
import '../ui/MessageContent.js';
import './bundle--1cImOGd.js';
import '../GroupChannel/components/MessageList.js';
import './bundle-uthnB1Zu.js';
import '../EditUserProfile/context.js';
import '../Channel/context.js';
import { u as useChannelListContext, S as SET_CURRENT_CHANNEL, L as LEAVE_CHANNEL_SUCCESS, C as ChannelListProvider } from './bundle-CGOt5cwH.js';
import './bundle-BkZBhjs8.js';
import '../ChannelSettings/hooks/useMenuList.js';
import './bundle-fYlljM7o.js';
import './bundle-CinANGYQ.js';
import './bundle-CVS5Kfg_.js';
import '../Thread/context/types.js';
import '../utils/message/getOutgoingMessageState.js';
import 'date-fns';
import '../Thread/components/ThreadMessageInput.js';
import Channel from '../Channel.js';
import ChannelPreview from '../ChannelList/components/ChannelPreview.js';
import ChannelSettings from '../ChannelSettings.js';
import MessageSearchPannel from '../MessageSearch.js';
import Thread from '../Thread.js';
import { u as uuidv4 } from './bundle-CTkGIdt8.js';
import './bundle-BoZwl2OL.js';
import '../OpenChannel/components/OpenChannelInput.js';
import '../OpenChannel/components/OpenChannelMessageList.js';
import '../OpenChannelSettings/context.js';
import '../ui/AccordionGroup.js';

var GroupChannelListUIView = function (_a) {
    var renderHeader = _a.renderHeader, renderPlaceHolderError = _a.renderPlaceHolderError, renderPlaceHolderLoading = _a.renderPlaceHolderLoading, renderPlaceHolderEmptyList = _a.renderPlaceHolderEmptyList, onChangeTheme = _a.onChangeTheme, onUserProfileUpdated = _a.onUserProfileUpdated, allowProfileEdit = _a.allowProfileEdit, channels = _a.channels, onLoadMore = _a.onLoadMore, initialized = _a.initialized, renderChannel = _a.renderChannel, renderAddChannel = _a.renderAddChannel, scrollRef = _a.scrollRef;
    var _b = useState(false), showProfileEdit = _b[0], setShowProfileEdit = _b[1];
    var stores = useSendbird().state.stores;
    var renderer = {
        addChannel: renderAddChannel,
        channel: renderChannel,
        placeholder: {
            loading: function () {
                if (initialized)
                    return null;
                if (renderPlaceHolderLoading)
                    return renderPlaceHolderLoading();
                return React__default.createElement(PlaceHolder, { type: PlaceHolderTypes.LOADING });
            },
            empty: function () {
                if (!initialized)
                    return null;
                if (renderPlaceHolderEmptyList)
                    return renderPlaceHolderEmptyList();
                return React__default.createElement(PlaceHolder, { type: PlaceHolderTypes.NO_CHANNELS });
            },
            error: function () {
                if (!initialized || !stores.sdkStore.error)
                    return null;
                if (renderPlaceHolderError)
                    return renderPlaceHolderError();
                return React__default.createElement(PlaceHolder, { type: PlaceHolderTypes.WRONG });
            },
        },
    };
    return (React__default.createElement(React__default.Fragment, null,
        React__default.createElement("div", { className: "sendbird-channel-list__header" }, (renderHeader === null || renderHeader === void 0 ? void 0 : renderHeader()) || (React__default.createElement(GroupChannelListHeader, { onEdit: function () { return allowProfileEdit && setShowProfileEdit(true); }, allowProfileEdit: allowProfileEdit, renderIconButton: function () { return renderer.addChannel(); } }))),
        showProfileEdit && (React__default.createElement(EditUserProfile, { onThemeChange: onChangeTheme, onCancel: function () { return setShowProfileEdit(false); }, onEditProfile: function (user) {
                setShowProfileEdit(false);
                onUserProfileUpdated(user);
            } })),
        React__default.createElement(ChannelListComponent, { data: channels, renderItem: renderer.channel, onLoadMore: onLoadMore, placeholderLoading: renderer.placeholder.loading(), placeholderEmpty: renderer.placeholder.empty(), placeholderError: renderer.placeholder.error(), scrollRef: scrollRef })));
};
/**
 * To do: Implement windowing
 * Implement windowing if you are dealing with large number of messages/channels
 * https://github.com/bvaughn/react-window -> recommendation
 * We hesitate to bring one more dependency to our library,
 * we are planning to implement it inside the library
 * */
var ChannelListComponent = function (props) {
    var data = props.data, renderItem = props.renderItem, onLoadMore = props.onLoadMore, placeholderLoading = props.placeholderLoading, placeholderError = props.placeholderError, placeholderEmpty = props.placeholderEmpty, scrollRef = props.scrollRef;
    var onScroll = useOnScrollPositionChangeDetector({
        onReachedBottom: function () { return onLoadMore === null || onLoadMore === void 0 ? void 0 : onLoadMore(); },
    });
    return (React__default.createElement("div", { className: 'sendbird-channel-list__body', onScroll: onScroll, ref: scrollRef },
        placeholderError,
        React__default.createElement("div", null, data.map(function (item, index) { return renderItem({ item: item, index: index }); })),
        placeholderLoading,
        data.length === 0 && placeholderEmpty));
};

var filterUser = function (idsToFilter) { return function (currentId) { return idsToFilter === null || idsToFilter === void 0 ? void 0 : idsToFilter.includes(currentId); }; };
var setChannelType = function (params, type) {
    if (type === 'broadcast') {
        // eslint-disable-next-line no-param-reassign
        params.isBroadcast = true;
    }
    if (type === 'supergroup') {
        // eslint-disable-next-line no-param-reassign
        params.isSuper = true;
    }
    return params;
};
var createDefaultUserListQuery = function (_a) {
    var sdk = _a.sdk, userFilledApplicationUserListQuery = _a.userFilledApplicationUserListQuery;
    var params = sdk.createApplicationUserListQuery();
    if (userFilledApplicationUserListQuery) {
        Object.keys(userFilledApplicationUserListQuery).forEach(function (key) {
            // @ts-ignore
            params[key] = userFilledApplicationUserListQuery[key];
        });
    }
    return params;
};

var CHANNEL_TYPE;
(function (CHANNEL_TYPE) {
    CHANNEL_TYPE["GROUP"] = "group";
    CHANNEL_TYPE["SUPERGROUP"] = "supergroup";
    CHANNEL_TYPE["BROADCAST"] = "broadcast";
})(CHANNEL_TYPE || (CHANNEL_TYPE = {}));

var CreateChannelContext = React__default.createContext(null);
var initialState = {
    sdk: undefined,
    userListQuery: undefined,
    onCreateChannelClick: undefined,
    onChannelCreated: undefined,
    onBeforeCreateChannel: undefined,
    pageStep: 0,
    type: CHANNEL_TYPE.GROUP,
    onCreateChannel: undefined,
    overrideInviteUser: undefined,
};
var CreateChannelManager = function (props) {
    var onCreateChannelClick = props.onCreateChannelClick, onBeforeCreateChannel = props.onBeforeCreateChannel, onChannelCreated = props.onChannelCreated, userListQuery = props.userListQuery, onCreateChannel = props.onCreateChannel, overrideInviteUser = props.overrideInviteUser;
    var updateState = useCreateChannelStore().updateState;
    var config = useSendbird().state.config;
    var _userListQuery = userListQuery !== null && userListQuery !== void 0 ? userListQuery : config === null || config === void 0 ? void 0 : config.userListQuery;
    useEffect(function () {
        updateState({
            onCreateChannelClick: onCreateChannelClick,
            onBeforeCreateChannel: onBeforeCreateChannel,
            onChannelCreated: onChannelCreated,
            userListQuery: _userListQuery,
            onCreateChannel: onCreateChannel,
            overrideInviteUser: overrideInviteUser,
        });
    }, [
        onCreateChannelClick,
        onBeforeCreateChannel,
        onChannelCreated,
        userListQuery,
        onCreateChannel,
        overrideInviteUser,
        _userListQuery,
    ]);
    return null;
};
var CreateChannelProvider = function (props) {
    var children = props.children;
    return (React__default.createElement(InternalCreateChannelProvider, null,
        React__default.createElement(CreateChannelManager, __assign({}, props)),
        children));
};
var createCreateChannelStore = function () { return createStore(initialState); };
var InternalCreateChannelProvider = function (_a) {
    var children = _a.children;
    var storeRef = useRef(createCreateChannelStore());
    return (React__default.createElement(CreateChannelContext.Provider, { value: storeRef.current }, children));
};
var useCreateChannelStore = function () {
    return useStore(CreateChannelContext, function (state) { return state; }, initialState);
};
var useCreateChannelContext = function () {
    var _a = useCreateChannel(), state = _a.state, actions = _a.actions;
    return __assign(__assign({}, state), actions);
};

var useCreateChannel = function () {
    var store = useContext(CreateChannelContext);
    var sendbirdStore = useSendbirdStateContext();
    if (!store)
        throw new Error('useCreateChannel must be used within a CreateChannelProvider');
    var state = shimExports.useSyncExternalStore(store.subscribe, store.getState);
    var actions = useMemo(function () { return ({
        setPageStep: function (pageStep) { return store.setState(function (state) { return (__assign(__assign({}, state), { pageStep: pageStep })); }); },
        setType: function (type) { return store.setState(function (state) { return (__assign(__assign({}, state), { type: type })); }); },
        createChannel: getCreateGroupChannel(sendbirdStore),
    }); }, [store]);
    return { state: state, actions: actions };
};

var BUFFER = 50;
var InviteUsers = function (_a) {
    var onCancel = _a.onCancel, userListQuery = _a.userListQuery;
    var _b = useCreateChannel(), _c = _b.state, onCreateChannelClick = _c.onCreateChannelClick, onBeforeCreateChannel = _c.onBeforeCreateChannel, onChannelCreated = _c.onChannelCreated, onCreateChannel = _c.onCreateChannel, overrideInviteUser = _c.overrideInviteUser, type = _c.type, createChannel = _b.actions.createChannel;
    var _d = useSendbird().state, userId = _d.config.userId, sdk = _d.stores.sdkStore.sdk;
    var idsToFilter = [userId];
    var _e = useState([]), users = _e[0], setUsers = _e[1];
    var _f = useState({}), selectedUsers = _f[0], setSelectedUsers = _f[1];
    var stringSet = useContext(LocalizationContext).stringSet;
    var _g = useState(null), usersDataSource = _g[0], setUsersDataSource = _g[1];
    var selectedCount = Object.keys(selectedUsers).length;
    var titleText = stringSet.MODAL__CREATE_CHANNEL__TITLE;
    var submitText = stringSet.BUTTON__CREATE;
    var isMobile = useMediaQueryContext().isMobile;
    var _h = useState(window.innerHeight), scrollableAreaHeight = _h[0], setScrollableAreaHeight = _h[1];
    useEffect(function () {
        var applicationUserListQuery = userListQuery ? userListQuery() : createDefaultUserListQuery({ sdk: sdk });
        setUsersDataSource(applicationUserListQuery);
        if (!(applicationUserListQuery === null || applicationUserListQuery === void 0 ? void 0 : applicationUserListQuery.isLoading)) {
            applicationUserListQuery.next().then(function (it) {
                setUsers(it);
            });
        }
    }, []);
    // To fix navbar break in mobile we set dynamic height to the scrollable area
    useEffect(function () {
        var scrollableAreaHeight = function () {
            setScrollableAreaHeight(window.innerHeight);
        };
        window.addEventListener('resize', scrollableAreaHeight);
        return function () {
            window.removeEventListener('resize', scrollableAreaHeight);
        };
    }, []);
    return (React__default.createElement(Modal, { isFullScreenOnMobile: true, titleText: titleText, submitText: submitText, type: ButtonTypes.PRIMARY, 
        // Disable the create button if no users are selected,
        // but if there's only the logged-in user in the user list,
        // then the create button should be enabled
        disabled: users.length > 1 && Object.keys(selectedUsers).length === 0, onCancel: onCancel, onSubmit: function () {
            var selectedUserList = Object.keys(selectedUsers).length > 0
                ? Object.keys(selectedUsers)
                : [userId];
            var _onChannelCreated = onChannelCreated !== null && onChannelCreated !== void 0 ? onChannelCreated : onCreateChannel;
            var _onCreateChannelClick = onCreateChannelClick !== null && onCreateChannelClick !== void 0 ? onCreateChannelClick : overrideInviteUser;
            if (typeof _onCreateChannelClick === 'function') {
                _onCreateChannelClick({
                    users: selectedUserList,
                    onClose: onCancel !== null && onCancel !== void 0 ? onCancel : noop,
                    channelType: type,
                });
                return;
            }
            if (onBeforeCreateChannel) {
                var params = onBeforeCreateChannel(selectedUserList);
                setChannelType(params, type);
                createChannel(params).then(function (channel) { return _onChannelCreated === null || _onChannelCreated === void 0 ? void 0 : _onChannelCreated(channel); });
            }
            else {
                var params = {};
                params.invitedUserIds = selectedUserList;
                params.isDistinct = false;
                if (userId) {
                    params.operatorUserIds = [userId];
                }
                setChannelType(params, type);
                // do not have custom params
                createChannel(params).then(function (channel) { return _onChannelCreated === null || _onChannelCreated === void 0 ? void 0 : _onChannelCreated(channel); });
            }
            onCancel === null || onCancel === void 0 ? void 0 : onCancel();
        } },
        React__default.createElement("div", null,
            React__default.createElement(Label, { color: (selectedCount > 0) ? LabelColors.PRIMARY : LabelColors.ONBACKGROUND_3, type: LabelTypography.CAPTION_1 }, "".concat(selectedCount, " ").concat(stringSet.MODAL__INVITE_MEMBER__SELECTED)),
            React__default.createElement("div", { className: "sendbird-create-channel--scroll", style: isMobile ? { height: "calc(".concat(scrollableAreaHeight, "px - 200px)") } : {}, onScroll: function (e) {
                    if (!usersDataSource)
                        return;
                    var eventTarget = e.target;
                    var hasNext = usersDataSource.hasNext, isLoading = usersDataSource.isLoading;
                    var fetchMore = ((eventTarget.clientHeight + eventTarget.scrollTop + BUFFER) > eventTarget.scrollHeight);
                    if (hasNext && fetchMore && !isLoading) {
                        usersDataSource.next().then(function (usersBatch) {
                            setUsers(__spreadArray(__spreadArray([], users, true), usersBatch, true));
                        });
                    }
                } }, users.map(function (user) { return (!filterUser(idsToFilter)(user.userId)) && (React__default.createElement(UserListItem, { key: user.userId, user: user, checkBox: true, checked: selectedUsers[user.userId], onChange: function (event) {
                    var _a;
                    var modifiedSelectedUsers = __assign(__assign({}, selectedUsers), (_a = {}, _a[event.target.id] = event.target.checked, _a));
                    if (!event.target.checked) {
                        delete modifiedSelectedUsers[event.target.id];
                    }
                    setSelectedUsers(modifiedSelectedUsers);
                } })); })))));
};

var isBroadcastChannelEnabled = function (sdk) {
    var _a;
    var ALLOW_BROADCAST_CHANNEL = 'allow_broadcast_channel';
    var applicationAttributes = (_a = sdk === null || sdk === void 0 ? void 0 : sdk.appInfo) === null || _a === void 0 ? void 0 : _a.applicationAttributes;
    if (Array.isArray(applicationAttributes)) {
        return applicationAttributes.includes(ALLOW_BROADCAST_CHANNEL);
    }
    return false;
};
var isSuperGroupChannelEnabled = function (sdk) {
    var _a;
    var ALLOW_SUPER_GROUP_CHANNEL = 'allow_super_group_channel';
    var applicationAttributes = (_a = sdk === null || sdk === void 0 ? void 0 : sdk.appInfo) === null || _a === void 0 ? void 0 : _a.applicationAttributes;
    if (Array.isArray(applicationAttributes)) {
        return applicationAttributes.includes(ALLOW_SUPER_GROUP_CHANNEL);
    }
    return false;
};

var SelectChannelType = function (props) {
    var onCancel = props.onCancel;
    var state = useSendbird().state;
    var sdk = getSdk(state);
    var _a = useCreateChannel().actions, setPageStep = _a.setPageStep, setType = _a.setType;
    var stringSet = useContext(LocalizationContext).stringSet;
    var isBroadcastAvailable = isBroadcastChannelEnabled(sdk);
    var isSupergroupAvailable = isSuperGroupChannelEnabled(sdk);
    return (React__default.createElement(Modal, { titleText: stringSet === null || stringSet === void 0 ? void 0 : stringSet.MODAL__CREATE_CHANNEL__TITLE, hideFooter: true, onCancel: function () { onCancel === null || onCancel === void 0 ? void 0 : onCancel(); }, className: "sendbird-add-channel__modal" },
        React__default.createElement("div", { className: "sendbird-add-channel__rectangle-wrap" },
            React__default.createElement("div", { className: "sendbird-add-channel__rectangle", onClick: function () {
                    setType(CHANNEL_TYPE.GROUP);
                    setPageStep(1);
                }, role: "button", tabIndex: 0, onKeyDown: function () {
                    setType(CHANNEL_TYPE.GROUP);
                    setPageStep(1);
                } },
                React__default.createElement(Icon, { className: "sendbird-add-channel__rectangle__chat-icon", type: IconTypes.CHAT, fillColor: IconColors.PRIMARY, width: "28px", height: "28px" }),
                React__default.createElement(Label, { type: LabelTypography.SUBTITLE_1, color: LabelColors.ONBACKGROUND_1 }, stringSet.MODAL__CREATE_CHANNEL__GROUP)),
            isSupergroupAvailable && (React__default.createElement("div", { className: "sendbird-add-channel__rectangle", onClick: function () {
                    setType(CHANNEL_TYPE.SUPERGROUP);
                    setPageStep(1);
                }, role: "button", tabIndex: 0, onKeyDown: function () {
                    setType(CHANNEL_TYPE.SUPERGROUP);
                    setPageStep(1);
                } },
                React__default.createElement(Icon, { className: "sendbird-add-channel__rectangle__supergroup-icon", type: IconTypes.SUPERGROUP, fillColor: IconColors.PRIMARY, width: "28px", height: "28px" }),
                React__default.createElement(Label, { type: LabelTypography.SUBTITLE_1, color: LabelColors.ONBACKGROUND_1 }, stringSet.MODAL__CREATE_CHANNEL__SUPER))),
            isBroadcastAvailable && (React__default.createElement("div", { className: "sendbird-add-channel__rectangle", onClick: function () {
                    setType(CHANNEL_TYPE.BROADCAST);
                    setPageStep(1);
                }, role: "button", tabIndex: 0, onKeyDown: function () {
                    setType(CHANNEL_TYPE.BROADCAST);
                    setPageStep(1);
                } },
                React__default.createElement(Icon, { className: "sendbird-add-channel__rectangle__broadcast-icon", type: IconTypes.BROADCAST, fillColor: IconColors.PRIMARY, width: "28px", height: "28px" }),
                React__default.createElement(Label, { type: LabelTypography.SUBTITLE_1, color: LabelColors.ONBACKGROUND_1 }, stringSet.MODAL__CREATE_CHANNEL__BROADCAST))))));
};

var CreateChannel$1 = function (props) {
    var onCancel = props.onCancel, renderStepOne = props.renderStepOne;
    var _a = useCreateChannel(), _b = _a.state, pageStep = _b.pageStep, userListQuery = _b.userListQuery, setPageStep = _a.actions.setPageStep;
    return (React__default.createElement(React__default.Fragment, null,
        pageStep === 0 && ((renderStepOne === null || renderStepOne === void 0 ? void 0 : renderStepOne()) || (React__default.createElement(SelectChannelType, { onCancel: onCancel }))),
        pageStep === 1 && (React__default.createElement(InviteUsers, { userListQuery: userListQuery, onCancel: function () {
                setPageStep(0);
                onCancel === null || onCancel === void 0 ? void 0 : onCancel();
            } }))));
};

var CreateChannel = function (props) {
    return (React__default.createElement(CreateChannelProvider, __assign({}, props),
        React__default.createElement(CreateChannel$1, __assign({}, props))));
};

var AddGroupChannelView = function (_a) {
    var createChannelVisible = _a.createChannelVisible, onChangeCreateChannelVisible = _a.onChangeCreateChannelVisible, onBeforeCreateChannel = _a.onBeforeCreateChannel, onCreateChannelClick = _a.onCreateChannelClick, onChannelCreated = _a.onChannelCreated;
    var config = useSendbird().state.config;
    return (React__default.createElement(React__default.Fragment, null,
        React__default.createElement(IconButton, { height: '32px', width: '32px', disabled: !config.isOnline, onClick: function () { return onChangeCreateChannelVisible(true); } },
            React__default.createElement(Icon, { type: IconTypes.CREATE, fillColor: IconColors.PRIMARY, width: '24px', height: '24px' })),
        createChannelVisible && (React__default.createElement(CreateChannel, { onCancel: function () { return onChangeCreateChannelVisible(false); }, onChannelCreated: function (channel) {
                onChannelCreated === null || onChannelCreated === void 0 ? void 0 : onChannelCreated(channel);
                onChangeCreateChannelVisible(false);
            }, onBeforeCreateChannel: onBeforeCreateChannel, onCreateChannelClick: onCreateChannelClick }))));
};

var AddGroupChannel = function () {
    var _a = useState(false), createChannelVisible = _a[0], setCreateChannelVisible = _a[1];
    var _b = useGroupChannelList().state, onChannelCreated = _b.onChannelCreated, onBeforeCreateChannel = _b.onBeforeCreateChannel, onCreateChannelClick = _b.onCreateChannelClick;
    return (React__default.createElement(AddGroupChannelView, { createChannelVisible: createChannelVisible, onChangeCreateChannelVisible: setCreateChannelVisible, onCreateChannelClick: onCreateChannelClick, onBeforeCreateChannel: onBeforeCreateChannel, onChannelCreated: onChannelCreated }));
};

var GroupChannelListUI = function (props) {
    var renderHeader = props.renderHeader, renderChannelPreview = props.renderChannelPreview, renderPlaceHolderError = props.renderPlaceHolderError, renderPlaceHolderLoading = props.renderPlaceHolderLoading, renderPlaceHolderEmptyList = props.renderPlaceHolderEmptyList;
    var _a = useGroupChannelList().state, onChannelSelect = _a.onChannelSelect, onThemeChange = _a.onThemeChange, allowProfileEdit = _a.allowProfileEdit, typingChannelUrls = _a.typingChannelUrls, groupChannels = _a.groupChannels, initialized = _a.initialized, selectedChannelUrl = _a.selectedChannelUrl, loadMore = _a.loadMore, onUserProfileUpdated = _a.onUserProfileUpdated, scrollRef = _a.scrollRef;
    var _b = useSendbird().state, stores = _b.stores, _c = _b.config, logger = _c.logger, isOnline = _c.isOnline;
    var sdk = stores.sdkStore.sdk;
    var renderListItem = function (renderProps) {
        var channel = renderProps.item, index = renderProps.index;
        var itemProps = {
            channel: channel,
            tabIndex: index,
            isSelected: channel.url === selectedChannelUrl,
            isTyping: typingChannelUrls.includes(channel.url),
            renderChannelAction: function (props) { return React__default.createElement(GroupChannelPreviewAction, __assign({}, props)); },
            onClick: function () {
                if (isOnline || (sdk === null || sdk === void 0 ? void 0 : sdk.isCacheEnabled)) {
                    logger.info('ChannelList: Clicked on channel:', channel);
                    onChannelSelect(channel);
                }
                else {
                    logger.warning('ChannelList: Inactivated clicking channel item during offline.');
                }
            },
            onLeaveChannel: function () {
                return __awaiter(this, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                logger.info('ChannelList: Leaving channel', channel);
                                return [4 /*yield*/, channel.leave()];
                            case 1:
                                _a.sent();
                                logger.info('ChannelList: Leaving channel success');
                                return [2 /*return*/];
                        }
                    });
                });
            },
        };
        if (renderChannelPreview) {
            return (React__default.createElement("div", { key: channel.url, onClick: itemProps.onClick }, renderChannelPreview(itemProps)));
        }
        return React__default.createElement(GroupChannelListItem, __assign({ key: channel.url }, itemProps));
    };
    return (React__default.createElement(GroupChannelListUIView, { renderHeader: renderHeader, renderChannel: renderListItem, renderPlaceHolderError: renderPlaceHolderError, renderPlaceHolderLoading: renderPlaceHolderLoading, renderPlaceHolderEmptyList: renderPlaceHolderEmptyList, onChangeTheme: onThemeChange !== null && onThemeChange !== void 0 ? onThemeChange : noop, allowProfileEdit: allowProfileEdit, onUserProfileUpdated: onUserProfileUpdated !== null && onUserProfileUpdated !== void 0 ? onUserProfileUpdated : noop, channels: groupChannels, onLoadMore: loadMore, initialized: initialized, renderAddChannel: function () { return React__default.createElement(AddGroupChannel, null); }, scrollRef: scrollRef }));
};

var GroupChannelList = function (props) {
    return (React__default.createElement(GroupChannelListProvider, __assign({}, props),
        React__default.createElement(GroupChannelListUI, __assign({}, props))));
};

var AddChannel = function () {
    var _a = useState(false), showModal = _a[0], setShowModal = _a[1];
    var _b = useChannelListContext(), overrideInviteUser = _b.overrideInviteUser, onBeforeCreateChannel = _b.onBeforeCreateChannel, onChannelSelect = _b.onChannelSelect;
    return (React__default.createElement(AddGroupChannelView, { createChannelVisible: showModal, onChangeCreateChannelVisible: setShowModal, onCreateChannelClick: overrideInviteUser, onBeforeCreateChannel: onBeforeCreateChannel, onChannelCreated: function (it) { return onChannelSelect === null || onChannelSelect === void 0 ? void 0 : onChannelSelect(it); } }));
};

/**
 * @deprecated This component is deprecated and will be removed in the next major update.
 * Please use the `GroupChannel` component from '@sendbird/uikit-react/GroupChannel' instead.
 * For more information, please refer to the migration guide:
 * https://docs.sendbird.com/docs/chat/uikit/v3/react/introduction/group-channel-migration-guide
 */
var ChannelListUI = function (props) {
    var renderHeader = props.renderHeader, renderChannelPreview = props.renderChannelPreview, renderPlaceHolderError = props.renderPlaceHolderError, renderPlaceHolderLoading = props.renderPlaceHolderLoading, renderPlaceHolderEmptyList = props.renderPlaceHolderEmptyList;
    var _a = useChannelListContext(), onThemeChange = _a.onThemeChange, allowProfileEdit = _a.allowProfileEdit, allChannels = _a.allChannels, currentChannel = _a.currentChannel, channelListDispatcher = _a.channelListDispatcher, typingChannels = _a.typingChannels, initialized = _a.initialized, fetchChannelList = _a.fetchChannelList, onProfileEditSuccess = _a.onProfileEditSuccess;
    var state = useSendbird().state;
    var stores = state.stores, config = state.config;
    var logger = config.logger, _b = config.isOnline, isOnline = _b === void 0 ? false : _b;
    var sdk = stores.sdkStore.sdk;
    var renderListItem = function (props) {
        var channel = props.item, index = props.index;
        var previewProps = {
            channel: channel,
            tabIndex: index,
            isSelected: (channel === null || channel === void 0 ? void 0 : channel.url) === (currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url),
            isTyping: typingChannels === null || typingChannels === void 0 ? void 0 : typingChannels.some(function (_a) {
                var url = _a.url;
                return url === (channel === null || channel === void 0 ? void 0 : channel.url);
            }),
            renderChannelAction: function (props) { return React__default.createElement(GroupChannelPreviewAction, __assign({}, props)); },
            onClick: function () {
                if (!isOnline && !(sdk === null || sdk === void 0 ? void 0 : sdk.isCacheEnabled)) {
                    logger.warning('ChannelList: Inactivated clicking channel item during offline.');
                    return;
                }
                logger.info('ChannelList: Clicked on channel:', channel);
                channelListDispatcher({
                    type: SET_CURRENT_CHANNEL,
                    payload: channel,
                });
            },
            onLeaveChannel: function (channel, cb) {
                return __awaiter(this, void 0, void 0, function () {
                    var response, err_1;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                logger.info('ChannelList: Leaving channel', channel);
                                if (!channel) return [3 /*break*/, 4];
                                _a.label = 1;
                            case 1:
                                _a.trys.push([1, 3, , 4]);
                                return [4 /*yield*/, channel.leave()];
                            case 2:
                                response = _a.sent();
                                logger.info('ChannelList: Leaving channel success', response);
                                if (cb && typeof cb === 'function')
                                    cb(channel, null);
                                channelListDispatcher({
                                    type: LEAVE_CHANNEL_SUCCESS,
                                    payload: channel.url,
                                });
                                return [3 /*break*/, 4];
                            case 3:
                                err_1 = _a.sent();
                                logger.error('ChannelList: Leaving channel failed', err_1);
                                if (cb && typeof cb === 'function')
                                    cb(channel, err_1);
                                return [3 /*break*/, 4];
                            case 4: return [2 /*return*/];
                        }
                    });
                });
            },
        };
        if (renderChannelPreview) {
            return (React__default.createElement("div", { key: channel === null || channel === void 0 ? void 0 : channel.url, onClick: previewProps.onClick }, renderChannelPreview(previewProps)));
        }
        return React__default.createElement(ChannelPreview, __assign({ key: channel === null || channel === void 0 ? void 0 : channel.url }, previewProps));
    };
    return (React__default.createElement(GroupChannelListUIView, { renderHeader: renderHeader, renderChannel: renderListItem, renderPlaceHolderError: renderPlaceHolderError, renderPlaceHolderLoading: renderPlaceHolderLoading, renderPlaceHolderEmptyList: renderPlaceHolderEmptyList, onChangeTheme: onThemeChange !== null && onThemeChange !== void 0 ? onThemeChange : noop, allowProfileEdit: allowProfileEdit, onUserProfileUpdated: onProfileEditSuccess !== null && onProfileEditSuccess !== void 0 ? onProfileEditSuccess : noop, channels: allChannels, onLoadMore: fetchChannelList, initialized: initialized, renderAddChannel: function () { return React__default.createElement(AddChannel, null); } }));
};

/**
 * @deprecated This component is deprecated and will be removed in the next major update.
 * Please use the `GroupChannelList` component from '@sendbird/uikit-react/GroupChannelList' instead.
 * For more information, please refer to the migration guide:
 * https://docs.sendbird.com/docs/chat/uikit/v3/react/introduction/group-channel-migration-guide
 */
var ChannelList = function (props) {
    return (React__default.createElement(ChannelListProvider, __assign({}, props),
        React__default.createElement(ChannelListUI, __assign({}, props))));
};

var PANELS;
(function (PANELS) {
    PANELS["CHANNEL_LIST"] = "CHANNEL_LIST";
    PANELS["CHANNEL"] = "CHANNEL";
    PANELS["CHANNEL_SETTINGS"] = "CHANNEL_SETTINGS";
    PANELS["MESSAGE_SEARCH"] = "MESSAGE_SEARCH";
    PANELS["THREAD"] = "THREAD";
})(PANELS || (PANELS = {}));
var MobileLayout = function (props) {
    var _a, _b, _c;
    var replyType = props.replyType, isMessageGroupingEnabled = props.isMessageGroupingEnabled, isMultipleFilesMessageEnabled = props.isMultipleFilesMessageEnabled, allowProfileEdit = props.allowProfileEdit, isReactionEnabled = props.isReactionEnabled, showSearchIcon = props.showSearchIcon, onProfileEditSuccess = props.onProfileEditSuccess, currentChannel = props.currentChannel, setCurrentChannel = props.setCurrentChannel, startingPoint = props.startingPoint, setStartingPoint = props.setStartingPoint, threadTargetMessage = props.threadTargetMessage, setThreadTargetMessage = props.setThreadTargetMessage, highlightedMessage = props.highlightedMessage, setHighlightedMessage = props.setHighlightedMessage, enableLegacyChannelModules = props.enableLegacyChannelModules;
    var _d = useState(PANELS.CHANNEL_LIST), panel = _d[0], setPanel = _d[1];
    var store = useSendbird().state;
    var sdk = (_b = (_a = store === null || store === void 0 ? void 0 : store.stores) === null || _a === void 0 ? void 0 : _a.sdkStore) === null || _b === void 0 ? void 0 : _b.sdk;
    var userId = (_c = store === null || store === void 0 ? void 0 : store.config) === null || _c === void 0 ? void 0 : _c.userId;
    var pause = useVoicePlayerContext().pause;
    var goToMessage = function (message, timeoutCb) {
        setStartingPoint === null || setStartingPoint === void 0 ? void 0 : setStartingPoint((message === null || message === void 0 ? void 0 : message.createdAt) || null);
        setTimeout(function () {
            timeoutCb === null || timeoutCb === void 0 ? void 0 : timeoutCb((message === null || message === void 0 ? void 0 : message.messageId) || null);
        }, 500);
    };
    useEffect(function () {
        if (panel !== PANELS.CHANNEL) {
            goToMessage(null, function () { return setHighlightedMessage === null || setHighlightedMessage === void 0 ? void 0 : setHighlightedMessage(null); });
        }
    }, [panel]);
    useEffect(function () {
        var _a, _b;
        var handlerId = uuidv4();
        if ((_a = sdk === null || sdk === void 0 ? void 0 : sdk.groupChannel) === null || _a === void 0 ? void 0 : _a.addGroupChannelHandler) {
            var handler = new GroupChannelHandler({
                onUserBanned: function (groupChannel, user) {
                    if (groupChannel.url === (currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url) && (user === null || user === void 0 ? void 0 : user.userId) === userId) {
                        setPanel(PANELS.CHANNEL_LIST);
                    }
                },
                onChannelDeleted: function (channelUrl) {
                    if (channelUrl === (currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url)) {
                        setPanel(PANELS.CHANNEL_LIST);
                    }
                },
                onUserLeft: function (groupChannel, user) {
                    if (groupChannel.url === (currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url) && (user === null || user === void 0 ? void 0 : user.userId) === userId) {
                        setPanel(PANELS.CHANNEL_LIST);
                    }
                },
            });
            (_b = sdk === null || sdk === void 0 ? void 0 : sdk.groupChannel) === null || _b === void 0 ? void 0 : _b.addGroupChannelHandler(handlerId, handler);
        }
        return function () {
            var _a, _b;
            (_b = (_a = sdk === null || sdk === void 0 ? void 0 : sdk.groupChannel) === null || _a === void 0 ? void 0 : _a.removeGroupChannelHandler) === null || _b === void 0 ? void 0 : _b.call(_a, handlerId);
        };
    }, [sdk, currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url]);
    // if currentChannel is changed while on Thread
    // then change panel type to CHANNEL
    useEffect(function () {
        if (panel === PANELS.THREAD) {
            setPanel(PANELS.CHANNEL);
        }
    }, [currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url]);
    var channelListProps = {
        allowProfileEdit: allowProfileEdit,
        onProfileEditSuccess: onProfileEditSuccess,
        disableAutoSelect: true,
        onChannelSelect: function (channel) {
            setCurrentChannel(channel !== null && channel !== void 0 ? channel : undefined);
            if (channel) {
                setPanel(PANELS.CHANNEL);
            }
            else {
                setPanel(PANELS.CHANNEL_LIST);
            }
        },
        // for GroupChannelList
        onChannelCreated: function (channel) {
            setCurrentChannel(channel);
            setPanel(PANELS.CHANNEL);
        },
        onUserProfileUpdated: onProfileEditSuccess,
    };
    var channelProps = {
        channelUrl: (currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url) || '',
        onChatHeaderActionClick: function () {
            setPanel(PANELS.CHANNEL_SETTINGS);
        },
        onBackClick: function () {
            setPanel(PANELS.CHANNEL_LIST);
            pause(ALL);
        },
        onSearchClick: function () {
            setPanel(PANELS.MESSAGE_SEARCH);
        },
        onReplyInThread: function (_a) {
            var message = _a.message;
            if (replyType === 'THREAD') {
                setPanel(PANELS.THREAD);
                setThreadTargetMessage(message);
            }
        },
        onQuoteMessageClick: function (_a) {
            var message = _a.message;
            // thread message
            if (replyType === 'THREAD') {
                setThreadTargetMessage(message);
                setPanel(PANELS.THREAD);
            }
        },
        animatedMessage: highlightedMessage,
        onMessageAnimated: function () { return setHighlightedMessage === null || setHighlightedMessage === void 0 ? void 0 : setHighlightedMessage(null); },
        showSearchIcon: showSearchIcon,
        startingPoint: startingPoint !== null && startingPoint !== void 0 ? startingPoint : undefined,
        isReactionEnabled: isReactionEnabled,
        replyType: replyType,
        isMessageGroupingEnabled: isMessageGroupingEnabled,
        isMultipleFilesMessageEnabled: isMultipleFilesMessageEnabled,
        // for GroupChannel
        animatedMessageId: highlightedMessage,
        onReplyInThreadClick: function (_a) {
            var message = _a.message;
            if (replyType === 'THREAD') {
                setPanel(PANELS.THREAD);
                setThreadTargetMessage(message);
            }
        },
    };
    return (React__default.createElement("div", { className: "sb_mobile", id: APP_LAYOUT_ROOT },
        panel === PANELS.CHANNEL_LIST && (React__default.createElement("div", { className: "sb_mobile__panelwrap" }, enableLegacyChannelModules ? React__default.createElement(ChannelList, __assign({}, channelListProps)) : React__default.createElement(GroupChannelList, __assign({}, channelListProps)))),
        panel === PANELS.CHANNEL && (React__default.createElement("div", { className: "sb_mobile__panelwrap" }, enableLegacyChannelModules ? React__default.createElement(Channel, __assign({}, channelProps)) : React__default.createElement(GroupChannel, __assign({}, channelProps)))),
        panel === PANELS.CHANNEL_SETTINGS && (React__default.createElement("div", { className: "sb_mobile__panelwrap" },
            React__default.createElement(ChannelSettings, { channelUrl: (currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url) || '', onCloseClick: function () {
                    setPanel(PANELS.CHANNEL);
                }, onLeaveChannel: function () {
                    setPanel(PANELS.CHANNEL_LIST);
                } }))),
        panel === PANELS.MESSAGE_SEARCH && (React__default.createElement("div", { className: "sb_mobile__panelwrap" },
            React__default.createElement(MessageSearchPannel, { channelUrl: (currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url) || '', onCloseClick: function () {
                    setPanel(PANELS.CHANNEL);
                }, onResultClick: function (message) {
                    setPanel(PANELS.CHANNEL);
                    goToMessage(message, function (messageId) {
                        setHighlightedMessage === null || setHighlightedMessage === void 0 ? void 0 : setHighlightedMessage(messageId);
                    });
                } }))),
        panel === PANELS.THREAD && (React__default.createElement("div", { className: "sb_mobile__panelwrap" },
            React__default.createElement(Thread, { channelUrl: (currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url) || '', message: threadTargetMessage, onHeaderActionClick: function () {
                    setPanel(PANELS.CHANNEL);
                    pause(ALL);
                }, onMoveToParentMessage: function (_a) {
                    var message = _a.message, channel = _a.channel;
                    setCurrentChannel(channel);
                    goToMessage(message, function (messageId) {
                        setPanel(PANELS.CHANNEL);
                        setHighlightedMessage === null || setHighlightedMessage === void 0 ? void 0 : setHighlightedMessage(messageId);
                    });
                } })))));
};

// NOTE: Do not use this hook internally.
// This hook is exported to support backward compatibility.
// Keep this function for backward compatibility.
function useSendbirdStateContext() {
    var _a = useSendbird(), state = _a.state, actions = _a.actions;
    return __assign(__assign({}, state), actions);
}

export { AddGroupChannel as A, ChannelList as C, GroupChannelList as G, InviteUsers as I, MobileLayout as M, SelectChannelType as S, useCreateChannel as a, CreateChannelProvider as b, CreateChannelContext as c, useCreateChannelContext as d, CreateChannel$1 as e, CreateChannel as f, GroupChannelListUI as g, AddChannel as h, ChannelListUI as i, useSendbirdStateContext as u };
//# sourceMappingURL=bundle-Dupd7RPQ.js.map
