'use strict';

var _tslib = require('./bundle-DhtZdKsr.js');
var React = require('react');
var Channel_context = require('../Channel/context.js');
var useSendbirdStateContext = require('../useSendbirdStateContext.js');
var Channel_components_ChannelHeader = require('./bundle-zRJE2NjU.js');
var GroupChannelProvider = require('./bundle--1R8Yp9p.js');
var uikitTools = require('@sendbird/uikit-tools');
var Channel_components_MessageList = require('./bundle-fTMJH5JE.js');
var ui_PlaceHolder = require('../ui/PlaceHolder.js');
var ui_Icon = require('../ui/Icon.js');
var index = require('./bundle-nox41MG6.js');
var utils = require('./bundle-jcgWT1ad.js');
var Channel_components_Message = require('./bundle-Eqd9bAds.js');
var Channel_components_FileViewer = require('./bundle-LsJ9u7uN.js');
var Channel_components_RemoveMessageModal = require('./bundle--t85OO-4.js');
var Channel_utils_getMessagePartsInfo = require('../Channel/utils/getMessagePartsInfo.js');
var index$2 = require('./bundle-DfMlIvtm.js');
var index$1 = require('./bundle-u7wWilEW.js');
var consts = require('./bundle-UAspU0bH.js');
var Message_context = require('../Message/context.js');
var ui_TypingIndicatorBubble = require('../ui/TypingIndicatorBubble.js');
var TypingIndicator = require('./bundle-5UyAossc.js');
var ui_ConnectionStatus = require('../ui/ConnectionStatus.js');
var MessageInputWrapperView = require('./bundle-ZvLEz_GA.js');
require('./bundle-6SzyBwQ5.js');
require('./bundle-zAQuo6rI.js');
require('../VoiceRecorder/context.js');
require('../withSendbird.js');
require('./bundle-VxcYXhwp.js');
require('./bundle-vMF9NM5u.js');
require('react-dom');
require('./bundle-6zBNmPOP.js');
require('../ui/IconButton.js');
require('../ui/Button.js');
var Channel_components_MessageInput = require('../Channel/components/MessageInput.js');

var GroupChannelHeader = function (_a) {
    var className = _a.className;
    var context = GroupChannelProvider.useGroupChannelContext();
    return (React.createElement(Channel_components_ChannelHeader.GroupChannelHeaderView, _tslib.__assign({}, context, { className: className, currentChannel: context.currentChannel })));
};

var FileViewer = function (props) {
    var deleteMessage = GroupChannelProvider.useGroupChannelContext().deleteMessage;
    return React.createElement(Channel_components_FileViewer.FileViewerView, _tslib.__assign({}, props, { deleteMessage: deleteMessage }));
};

var RemoveMessageModal = function (props) {
    var deleteMessage = GroupChannelProvider.useGroupChannelContext().deleteMessage;
    return React.createElement(Channel_components_RemoveMessageModal.RemoveMessageModalView, _tslib.__assign({}, props, { deleteMessage: deleteMessage }));
};

var Message = function (props) {
    var _a = useSendbirdStateContext.useSendbirdStateContext(), config = _a.config, emojiManager = _a.emojiManager;
    var _b = GroupChannelProvider.useGroupChannelContext(), loading = _b.loading, currentChannel = _b.currentChannel, animatedMessageId = _b.animatedMessageId, setAnimatedMessageId = _b.setAnimatedMessageId, scrollToMessage = _b.scrollToMessage, replyType = _b.replyType, threadReplySelectType = _b.threadReplySelectType, isReactionEnabled = _b.isReactionEnabled, toggleReaction = _b.toggleReaction, nicknamesMap = _b.nicknamesMap, setQuoteMessage = _b.setQuoteMessage, renderUserMentionItem = _b.renderUserMentionItem, onQuoteMessageClick = _b.onQuoteMessageClick, onReplyInThreadClick = _b.onReplyInThreadClick, onMessageAnimated = _b.onMessageAnimated, messages = _b.messages, updateUserMessage = _b.updateUserMessage, sendUserMessage = _b.sendUserMessage, resendMessage = _b.resendMessage, deleteMessage = _b.deleteMessage;
    var message = props.message;
    var initialized = !loading && Boolean(currentChannel);
    var shouldRenderSuggestedReplies = uikitTools.useIIFE(function () {
        var _a;
        if (message.messageId !== ((_a = currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.lastMessage) === null || _a === void 0 ? void 0 : _a.messageId))
            return false;
        if (index.getSuggestedReplies(message).length === 0)
            return false;
        var lastMessage = messages[messages.length - 1];
        if (lastMessage && index.isSendableMessage(lastMessage) && lastMessage.sendingStatus !== 'succeeded')
            return false;
        return true;
    });
    return (React.createElement(Channel_components_Message.MessageView, _tslib.__assign({}, props, { channel: currentChannel, emojiContainer: emojiManager.emojiContainer, editInputDisabled: !initialized || utils.isDisabledBecauseFrozen(currentChannel) || utils.isDisabledBecauseMuted(currentChannel) || !config.isOnline, shouldRenderSuggestedReplies: shouldRenderSuggestedReplies, isReactionEnabled: isReactionEnabled, replyType: replyType, threadReplySelectType: threadReplySelectType, nicknamesMap: nicknamesMap, renderUserMentionItem: renderUserMentionItem, scrollToMessage: scrollToMessage, toggleReaction: toggleReaction, setQuoteMessage: setQuoteMessage, onQuoteMessageClick: onQuoteMessageClick, onReplyInThreadClick: onReplyInThreadClick, sendUserMessage: sendUserMessage, updateUserMessage: updateUserMessage, resendMessage: resendMessage, deleteMessage: deleteMessage, animatedMessageId: animatedMessageId, setAnimatedMessageId: setAnimatedMessageId, onMessageAnimated: onMessageAnimated, renderFileViewer: function (props) { return React.createElement(FileViewer, _tslib.__assign({}, props)); }, renderRemoveMessageModal: function (props) { return React.createElement(RemoveMessageModal, _tslib.__assign({}, props)); } })));
};

function useScrollBehavior() {
    var _a = GroupChannelProvider.useGroupChannelContext(), scrollRef = _a.scrollRef, _b = _a.scrollBehavior, scrollBehavior = _b === void 0 ? 'auto' : _b;
    React.useEffect(function () {
        if (scrollRef.current) {
            scrollRef.current.style.scrollBehavior = scrollBehavior;
        }
    }, [scrollRef.current]);
    return null;
}

var MessageList = function (_a) {
    var _b, _c, _d, _e, _f;
    var _g = _a.className, className = _g === void 0 ? '' : _g, renderMessage = _a.renderMessage, renderPlaceholderEmpty = _a.renderPlaceholderEmpty, renderCustomSeparator = _a.renderCustomSeparator, renderPlaceholderLoader = _a.renderPlaceholderLoader, renderFrozenNotification = _a.renderFrozenNotification;
    var _h = GroupChannelProvider.useGroupChannelContext(), channelUrl = _h.channelUrl, hasNext = _h.hasNext, loading = _h.loading, messages = _h.messages, newMessages = _h.newMessages, scrollToBottom = _h.scrollToBottom, isScrollBottomReached = _h.isScrollBottomReached, isMessageGroupingEnabled = _h.isMessageGroupingEnabled, scrollRef = _h.scrollRef, scrollDistanceFromBottomRef = _h.scrollDistanceFromBottomRef, currentChannel = _h.currentChannel, replyType = _h.replyType, scrollPubSub = _h.scrollPubSub;
    var store = useSendbirdStateContext.useSendbirdStateContext();
    var _j = React.useState(), unreadSinceDate = _j[0], setUnreadSinceDate = _j[1];
    useScrollBehavior();
    React.useEffect(function () {
        if (isScrollBottomReached) {
            setUnreadSinceDate(undefined);
        }
        else {
            setUnreadSinceDate(new Date());
        }
    }, [isScrollBottomReached]);
    /**
     * 1. Move the message list scroll
     *    when each message's height is changed by `reactions` OR `showEdit`
     * 2. Keep the scrollBottom value after fetching new message list
     */
    var onMessageContentSizeChanged = function (isBottomMessageAffected) {
        if (isBottomMessageAffected === void 0) { isBottomMessageAffected = false; }
        var elem = scrollRef.current;
        if (elem) {
            var latestDistance = scrollDistanceFromBottomRef.current;
            var currentDistance = elem.scrollHeight - elem.scrollTop - elem.offsetHeight;
            if (latestDistance < currentDistance && (!isBottomMessageAffected || latestDistance < consts.SCROLL_BUFFER)) {
                var diff = currentDistance - latestDistance;
                // Move the scroll as much as the height of the message has changed
                scrollPubSub.publish('scroll', { top: elem.scrollTop + diff, lazy: false });
            }
        }
    };
    var renderer = {
        frozenNotification: function () {
            if (!currentChannel || !currentChannel.isFrozen)
                return null;
            if (renderFrozenNotification)
                return renderFrozenNotification();
            return React.createElement(index$1.FrozenNotification, { className: "sendbird-conversation__messages__notification" });
        },
        unreadMessagesNotification: function () {
            if (isScrollBottomReached || !unreadSinceDate)
                return null;
            return (React.createElement(index$2.UnreadCount, { className: "sendbird-conversation__messages__notification", count: newMessages.length, lastReadAt: unreadSinceDate, onClick: scrollToBottom }));
        },
        scrollToBottomButton: function () {
            if (!hasNext() && isScrollBottomReached)
                return null;
            return (React.createElement("div", { className: "sendbird-conversation__scroll-bottom-button", onClick: scrollToBottom, onKeyDown: scrollToBottom, tabIndex: 0, role: "button" },
                React.createElement(ui_Icon.default, { width: "24px", height: "24px", type: ui_Icon.IconTypes.CHEVRON_DOWN, fillColor: ui_Icon.IconColors.PRIMARY })));
        },
    };
    if (loading) {
        if (renderPlaceholderLoader)
            return renderPlaceholderLoader();
        return React.createElement(ui_PlaceHolder.default, { type: ui_PlaceHolder.PlaceHolderTypes.LOADING });
    }
    if (messages.length === 0) {
        if (renderPlaceholderEmpty)
            return renderPlaceholderEmpty();
        return React.createElement(ui_PlaceHolder.default, { className: "sendbird-conversation__no-messages", type: ui_PlaceHolder.PlaceHolderTypes.NO_MESSAGES });
    }
    return (React.createElement(React.Fragment, null,
        React.createElement("div", { className: "sendbird-conversation__messages ".concat(className) },
            React.createElement("div", { className: "sendbird-conversation__scroll-container" },
                React.createElement("div", { className: "sendbird-conversation__padding" }),
                React.createElement("div", { className: "sendbird-conversation__messages-padding", ref: scrollRef },
                    messages.map(function (message, idx) {
                        var _a = Channel_utils_getMessagePartsInfo.getMessagePartsInfo({
                            allMessages: messages,
                            replyType: replyType,
                            isMessageGroupingEnabled: isMessageGroupingEnabled,
                            currentIndex: idx,
                            currentMessage: message,
                            currentChannel: currentChannel,
                        }), chainTop = _a.chainTop, chainBottom = _a.chainBottom, hasSeparator = _a.hasSeparator;
                        var isOutgoingMessage = message.isUserMessage() && message.sender.userId === store.config.userId;
                        return (React.createElement(Message_context.MessageProvider, { message: message, key: utils.getComponentKeyFromMessage(message), isByMe: isOutgoingMessage },
                            React.createElement(Message, { handleScroll: onMessageContentSizeChanged, renderMessage: renderMessage, message: message, hasSeparator: hasSeparator, chainTop: chainTop, chainBottom: chainBottom, renderCustomSeparator: renderCustomSeparator })));
                    }),
                    !hasNext()
                        && ((_c = (_b = store === null || store === void 0 ? void 0 : store.config) === null || _b === void 0 ? void 0 : _b.groupChannel) === null || _c === void 0 ? void 0 : _c.enableTypingIndicator)
                        && ((_f = (_e = (_d = store === null || store === void 0 ? void 0 : store.config) === null || _d === void 0 ? void 0 : _d.groupChannel) === null || _e === void 0 ? void 0 : _e.typingIndicatorTypes) === null || _f === void 0 ? void 0 : _f.has(Channel_components_MessageList.TypingIndicatorType.Bubble)) && (React.createElement(TypingIndicatorBubbleWrapper, { channelUrl: channelUrl, handleScroll: onMessageContentSizeChanged })))),
            React.createElement(React.Fragment, null, renderer.frozenNotification()),
            React.createElement(React.Fragment, null, renderer.unreadMessagesNotification()),
            React.createElement(React.Fragment, null, renderer.scrollToBottomButton()))));
};
var TypingIndicatorBubbleWrapper = function (props) {
    var stores = useSendbirdStateContext.useSendbirdStateContext().stores;
    var _a = React.useState([]), typingMembers = _a[0], setTypingMembers = _a[1];
    uikitTools.useGroupChannelHandler(stores.sdkStore.sdk, {
        onTypingStatusUpdated: function (channel) {
            if (channel.url === props.channelUrl) {
                setTypingMembers(channel.getTypingUsers());
            }
        },
    });
    return React.createElement(ui_TypingIndicatorBubble, { typingMembers: typingMembers, handleScroll: props.handleScroll });
};

var MessageInputWrapper = function (props) {
    var context = GroupChannelProvider.useGroupChannelContext();
    return (React.createElement(MessageInputWrapperView.MessageInputWrapperView, _tslib.__assign({}, props, context)));
};

var GroupChannelUIView = function (props) {
    var _a, _b, _c, _d;
    var requestedChannelUrl = props.requestedChannelUrl, loading = props.loading, isInvalid = props.isInvalid, _e = props.renderChannelHeader, renderChannelHeader = _e === void 0 ? function (props) { return (React.createElement(GroupChannelHeader, _tslib.__assign({}, props))); } : _e, _f = props.renderMessageList, renderMessageList = _f === void 0 ? function (props) { return (React.createElement(MessageList, _tslib.__assign({}, props, { className: "sendbird-conversation__message-list" }))); } : _f, _g = props.renderMessageInput, renderMessageInput = _g === void 0 ? function () { return React.createElement(MessageInputWrapper, null); } : _g, renderTypingIndicator = props.renderTypingIndicator, renderPlaceholderLoader = props.renderPlaceholderLoader, renderPlaceholderInvalid = props.renderPlaceholderInvalid;
    var _h = useSendbirdStateContext.useSendbirdStateContext(), stores = _h.stores, config = _h.config;
    var sdkError = (_a = stores === null || stores === void 0 ? void 0 : stores.sdkStore) === null || _a === void 0 ? void 0 : _a.error;
    var logger = config.logger, isOnline = config.isOnline;
    if (loading) {
        return React.createElement("div", { className: "sendbird-conversation" }, (renderPlaceholderLoader === null || renderPlaceholderLoader === void 0 ? void 0 : renderPlaceholderLoader()) || React.createElement(ui_PlaceHolder.default, { type: ui_PlaceHolder.PlaceHolderTypes.LOADING }));
    }
    if (!requestedChannelUrl) {
        return (React.createElement("div", { className: "sendbird-conversation" }, (renderPlaceholderInvalid === null || renderPlaceholderInvalid === void 0 ? void 0 : renderPlaceholderInvalid()) || React.createElement(ui_PlaceHolder.default, { type: ui_PlaceHolder.PlaceHolderTypes.NO_CHANNELS })));
    }
    if (isInvalid) {
        return React.createElement("div", { className: "sendbird-conversation" }, (renderPlaceholderInvalid === null || renderPlaceholderInvalid === void 0 ? void 0 : renderPlaceholderInvalid()) || React.createElement(ui_PlaceHolder.default, { type: ui_PlaceHolder.PlaceHolderTypes.WRONG }));
    }
    if (sdkError) {
        return (React.createElement("div", { className: "sendbird-conversation" }, (renderPlaceholderInvalid === null || renderPlaceholderInvalid === void 0 ? void 0 : renderPlaceholderInvalid()) || (React.createElement(ui_PlaceHolder.default, { type: ui_PlaceHolder.PlaceHolderTypes.WRONG, retryToConnect: function () {
                logger.info('Channel: reconnecting');
                // reconnect();
            } }))));
    }
    return (React.createElement("div", { className: 'sendbird-conversation' }, renderChannelHeader === null || renderChannelHeader === void 0 ? void 0 :
        renderChannelHeader({ className: 'sendbird-conversation__channel-header' }), renderMessageList === null || renderMessageList === void 0 ? void 0 :
        renderMessageList(props),
        React.createElement("div", { className: "sendbird-conversation__footer" }, renderMessageInput === null || renderMessageInput === void 0 ? void 0 :
            renderMessageInput(),
            React.createElement("div", { className: "sendbird-conversation__footer__typing-indicator" },
                (renderTypingIndicator === null || renderTypingIndicator === void 0 ? void 0 : renderTypingIndicator())
                    || (((_b = config === null || config === void 0 ? void 0 : config.groupChannel) === null || _b === void 0 ? void 0 : _b.enableTypingIndicator)
                        && ((_d = (_c = config === null || config === void 0 ? void 0 : config.groupChannel) === null || _c === void 0 ? void 0 : _c.typingIndicatorTypes) === null || _d === void 0 ? void 0 : _d.has(Channel_components_MessageList.TypingIndicatorType.Text))
                        && (React.createElement(TypingIndicator.TypingIndicator, { channelUrl: requestedChannelUrl }))),
                !isOnline && React.createElement(ui_ConnectionStatus, null)))));
};

var ChannelUI = function (props) {
    var _a;
    var context = Channel_context.useChannelContext();
    var channelUrl = context.channelUrl, isInvalid = context.isInvalid, loading = context.loading;
    return (React.createElement(GroupChannelUIView, _tslib.__assign({}, props, context, { requestedChannelUrl: channelUrl, loading: (_a = props === null || props === void 0 ? void 0 : props.isLoading) !== null && _a !== void 0 ? _a : loading, isInvalid: isInvalid, renderChannelHeader: function (props) { return (React.createElement(Channel_components_ChannelHeader.ChannelHeader, _tslib.__assign({}, props))); }, renderMessageList: function (props) { return (React.createElement(Channel_components_MessageList.MessageList, _tslib.__assign({}, props))); }, renderMessageInput: function () { return (React.createElement(Channel_components_MessageInput.MessageInputWrapper, _tslib.__assign({}, props))); } })));
};

exports.ChannelUI = ChannelUI;
exports.GroupChannelUIView = GroupChannelUIView;
//# sourceMappingURL=bundle-Cbklvbls.js.map
