import { _ as __assign } from './bundle-BA7tv0JB.js';
import React__default, { useEffect, useState } from 'react';
import { useChannelContext } from '../Channel/context.js';
import { useSendbirdStateContext } from '../useSendbirdStateContext.js';
import { G as GroupChannelHeaderView, C as ChannelHeader } from './bundle-3GWXgoxj.js';
import { u as useGroupChannelContext } from './bundle-zKBdD-J6.js';
import { useIIFE, useGroupChannelHandler } from '@sendbird/uikit-tools';
import { T as TypingIndicatorType, M as MessageList$1 } from './bundle-1zn-WT_r.js';
import PlaceHolder, { PlaceHolderTypes } from '../ui/PlaceHolder.js';
import Icon, { IconTypes, IconColors } from '../ui/Icon.js';
import { L as getSuggestedReplies, Q as isSendableMessage } from './bundle-N9hMnIRl.js';
import { i as isDisabledBecauseFrozen, a as isDisabledBecauseMuted, c as getComponentKeyFromMessage } from './bundle-tPCzzoc1.js';
import { a as MessageView } from './bundle-beMggMMW.js';
import { a as FileViewerView } from './bundle-khgxDrnA.js';
import { a as RemoveMessageModalView } from './bundle-bAY1j7eP.js';
import { getMessagePartsInfo } from '../Channel/utils/getMessagePartsInfo.js';
import { U as UnreadCount } from './bundle-VbkO6hwH.js';
import { F as FrozenNotification } from './bundle-G7HnuZsw.js';
import { S as SCROLL_BUFFER } from './bundle-MBrlu_LK.js';
import { MessageProvider } from '../Message/context.js';
import TypingIndicatorBubble from '../ui/TypingIndicatorBubble.js';
import { T as TypingIndicator } from './bundle-uIetzCLw.js';
import ConnectionStatus from '../ui/ConnectionStatus.js';
import { M as MessageInputWrapperView } from './bundle-DSoowPBh.js';
import './bundle-BBjosDA0.js';
import './bundle-drww6xht.js';
import '../VoiceRecorder/context.js';
import '../withSendbird.js';
import './bundle-I8JFwttJ.js';
import './bundle-LWD0OLz8.js';
import 'react-dom';
import './bundle-r9j_eCHc.js';
import '../ui/IconButton.js';
import '../ui/Button.js';
import { MessageInputWrapper as MessageInputWrapper$1 } from '../Channel/components/MessageInput.js';

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

var FileViewer = function (props) {
    var deleteMessage = useGroupChannelContext().deleteMessage;
    return React__default.createElement(FileViewerView, __assign({}, props, { deleteMessage: deleteMessage }));
};

var RemoveMessageModal = function (props) {
    var deleteMessage = useGroupChannelContext().deleteMessage;
    return React__default.createElement(RemoveMessageModalView, __assign({}, props, { deleteMessage: deleteMessage }));
};

var Message = function (props) {
    var _a = useSendbirdStateContext(), config = _a.config, emojiManager = _a.emojiManager;
    var _b = 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 = 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 (getSuggestedReplies(message).length === 0)
            return false;
        var lastMessage = messages[messages.length - 1];
        if (lastMessage && isSendableMessage(lastMessage) && lastMessage.sendingStatus !== 'succeeded')
            return false;
        return true;
    });
    return (React__default.createElement(MessageView, __assign({}, props, { channel: currentChannel, emojiContainer: emojiManager.emojiContainer, editInputDisabled: !initialized || isDisabledBecauseFrozen(currentChannel) || 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__default.createElement(FileViewer, __assign({}, props)); }, renderRemoveMessageModal: function (props) { return React__default.createElement(RemoveMessageModal, __assign({}, props)); } })));
};

function useScrollBehavior() {
    var _a = useGroupChannelContext(), scrollRef = _a.scrollRef, _b = _a.scrollBehavior, scrollBehavior = _b === void 0 ? 'auto' : _b;
    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 = 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();
    var _j = useState(), unreadSinceDate = _j[0], setUnreadSinceDate = _j[1];
    useScrollBehavior();
    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 < 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__default.createElement(FrozenNotification, { className: "sendbird-conversation__messages__notification" });
        },
        unreadMessagesNotification: function () {
            if (isScrollBottomReached || !unreadSinceDate)
                return null;
            return (React__default.createElement(UnreadCount, { className: "sendbird-conversation__messages__notification", count: newMessages.length, lastReadAt: unreadSinceDate, onClick: scrollToBottom }));
        },
        scrollToBottomButton: function () {
            if (!hasNext() && isScrollBottomReached)
                return null;
            return (React__default.createElement("div", { className: "sendbird-conversation__scroll-bottom-button", onClick: scrollToBottom, onKeyDown: scrollToBottom, tabIndex: 0, role: "button" },
                React__default.createElement(Icon, { width: "24px", height: "24px", type: IconTypes.CHEVRON_DOWN, fillColor: IconColors.PRIMARY })));
        },
    };
    if (loading) {
        if (renderPlaceholderLoader)
            return renderPlaceholderLoader();
        return React__default.createElement(PlaceHolder, { type: PlaceHolderTypes.LOADING });
    }
    if (messages.length === 0) {
        if (renderPlaceholderEmpty)
            return renderPlaceholderEmpty();
        return React__default.createElement(PlaceHolder, { className: "sendbird-conversation__no-messages", type: PlaceHolderTypes.NO_MESSAGES });
    }
    return (React__default.createElement(React__default.Fragment, null,
        React__default.createElement("div", { className: "sendbird-conversation__messages ".concat(className) },
            React__default.createElement("div", { className: "sendbird-conversation__scroll-container" },
                React__default.createElement("div", { className: "sendbird-conversation__padding" }),
                React__default.createElement("div", { className: "sendbird-conversation__messages-padding", ref: scrollRef },
                    messages.map(function (message, idx) {
                        var _a = 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__default.createElement(MessageProvider, { message: message, key: getComponentKeyFromMessage(message), isByMe: isOutgoingMessage },
                            React__default.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(TypingIndicatorType.Bubble)) && (React__default.createElement(TypingIndicatorBubbleWrapper, { channelUrl: channelUrl, handleScroll: onMessageContentSizeChanged })))),
            React__default.createElement(React__default.Fragment, null, renderer.frozenNotification()),
            React__default.createElement(React__default.Fragment, null, renderer.unreadMessagesNotification()),
            React__default.createElement(React__default.Fragment, null, renderer.scrollToBottomButton()))));
};
var TypingIndicatorBubbleWrapper = function (props) {
    var stores = useSendbirdStateContext().stores;
    var _a = useState([]), typingMembers = _a[0], setTypingMembers = _a[1];
    useGroupChannelHandler(stores.sdkStore.sdk, {
        onTypingStatusUpdated: function (channel) {
            if (channel.url === props.channelUrl) {
                setTypingMembers(channel.getTypingUsers());
            }
        },
    });
    return React__default.createElement(TypingIndicatorBubble, { typingMembers: typingMembers, handleScroll: props.handleScroll });
};

var MessageInputWrapper = function (props) {
    var context = useGroupChannelContext();
    return (React__default.createElement(MessageInputWrapperView, __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__default.createElement(GroupChannelHeader, __assign({}, props))); } : _e, _f = props.renderMessageList, renderMessageList = _f === void 0 ? function (props) { return (React__default.createElement(MessageList, __assign({}, props, { className: "sendbird-conversation__message-list" }))); } : _f, _g = props.renderMessageInput, renderMessageInput = _g === void 0 ? function () { return React__default.createElement(MessageInputWrapper, null); } : _g, renderTypingIndicator = props.renderTypingIndicator, renderPlaceholderLoader = props.renderPlaceholderLoader, renderPlaceholderInvalid = props.renderPlaceholderInvalid;
    var _h = 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__default.createElement("div", { className: "sendbird-conversation" }, (renderPlaceholderLoader === null || renderPlaceholderLoader === void 0 ? void 0 : renderPlaceholderLoader()) || React__default.createElement(PlaceHolder, { type: PlaceHolderTypes.LOADING }));
    }
    if (!requestedChannelUrl) {
        return (React__default.createElement("div", { className: "sendbird-conversation" }, (renderPlaceholderInvalid === null || renderPlaceholderInvalid === void 0 ? void 0 : renderPlaceholderInvalid()) || React__default.createElement(PlaceHolder, { type: PlaceHolderTypes.NO_CHANNELS })));
    }
    if (isInvalid) {
        return React__default.createElement("div", { className: "sendbird-conversation" }, (renderPlaceholderInvalid === null || renderPlaceholderInvalid === void 0 ? void 0 : renderPlaceholderInvalid()) || React__default.createElement(PlaceHolder, { type: PlaceHolderTypes.WRONG }));
    }
    if (sdkError) {
        return (React__default.createElement("div", { className: "sendbird-conversation" }, (renderPlaceholderInvalid === null || renderPlaceholderInvalid === void 0 ? void 0 : renderPlaceholderInvalid()) || (React__default.createElement(PlaceHolder, { type: PlaceHolderTypes.WRONG, retryToConnect: function () {
                logger.info('Channel: reconnecting');
                // reconnect();
            } }))));
    }
    return (React__default.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__default.createElement("div", { className: "sendbird-conversation__footer" }, renderMessageInput === null || renderMessageInput === void 0 ? void 0 :
            renderMessageInput(),
            React__default.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(TypingIndicatorType.Text))
                        && (React__default.createElement(TypingIndicator, { channelUrl: requestedChannelUrl }))),
                !isOnline && React__default.createElement(ConnectionStatus, null)))));
};

var ChannelUI = function (props) {
    var _a;
    var context = useChannelContext();
    var channelUrl = context.channelUrl, isInvalid = context.isInvalid, loading = context.loading;
    return (React__default.createElement(GroupChannelUIView, __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__default.createElement(ChannelHeader, __assign({}, props))); }, renderMessageList: function (props) { return (React__default.createElement(MessageList$1, __assign({}, props))); }, renderMessageInput: function () { return (React__default.createElement(MessageInputWrapper$1, __assign({}, props))); } })));
};

export { ChannelUI as C, GroupChannelUIView as G };
//# sourceMappingURL=bundle-GnFOVDL2.js.map
