'use strict';

var React = require('react');
var Channel_context = require('../../ChannelProvider-2bfafa25.js');
var ui_PlaceHolder = require('../../index-9d9e563e.js');
var ui_Icon = require('../../ui/Icon.js');
var Channel_components_Message = require('./Message.js');
var index = require('../../index-afada680.js');
var Channel_components_UnreadCount = require('./UnreadCount.js');
var Channel_components_FrozenNotification = require('./FrozenNotification.js');
var consts = require('../../consts-f71467c8.js');
var useSendbirdStateContext = require('../../useSendbirdStateContext.js');
var Message_context = require('../../Message/context.js');
var index$1 = require('../../index-c38404d2.js');
require('../../UserProfileContext-c87514d3.js');
require('prop-types');
require('../../index-849f44b0.js');
require('../../index-97005534.js');
require('../../topics-3226c6ee.js');
require('../../index-0b8a1074.js');
require('../../_rollupPluginBabelHelpers-3a9d1641.js');
require('../../utils/message/getOutgoingMessageState.js');
require('../../compareIds-a7029d6a.js');
require('../../const-68cf2709.js');
require('@sendbird/chat/groupChannel');
require('../../uuid-5ab4f88b.js');
require('@sendbird/chat/message');
require('../../LocalizationContext-b42fa07d.js');
require('../../stringSet-4f30313f.js');
require('../../index-72e412f7.js');
require('../../ui/Loader.js');
require('./SuggestedMentionList.js');
require('../../ui/Avatar.js');
require('../../ui/ImageRenderer.js');
require('../../const-3ab3e45c.js');
require('../../ThreadProvider-3ff0ff63.js');
require('../../Thread/context/types.js');
require('@sendbird/chat');
require('../../ui/DateSeparator.js');
require('../../color-a4e73e6f.js');
require('../../ui/MessageInput.js');
require('../../ui/IconButton.js');
require('../../ui/Button.js');
require('dompurify');
require('../../consts-bb2a67c7.js');
require('../../consts-ad8ba629.js');
require('../../consts-26d4668c.js');
require('../../tokenize-e944d548.js');
require('../../ui/MessageContent.js');
require('../../ui/UserProfile.js');
require('../../sendbirdSelectors.js');
require('../../utils-146517a9.js');
require('../../index-e1d69370.js');
require('../../index-7ec4fe06.js');
require('../../ui/MessageItemMenu.js');
require('../../ui/ContextMenu.js');
require('react-dom');
require('../../ui/SortByRow.js');
require('../../types-31174fcc.js');
require('../../ui/MessageItemReactionMenu.js');
require('../../ui/ReactionButton.js');
require('../../useLongPress-bf1e8eee.js');
require('../../MediaQueryContext-372b55a6.js');
require('../../ui/EmojiReactions.js');
require('../../ui/ReactionBadge.js');
require('../../ui/BottomSheet.js');
require('../../index-e8b83547.js');
require('../../ui/UserListItem.js');
require('../../ui/MutedAvatarOverlay.js');
require('../../ui/Checkbox.js');
require('../../ui/Tooltip.js');
require('../../ui/TooltipWrapper.js');
require('../../ui/AdminMessage.js');
require('../../ui/TextMessageItemBody.js');
require('../../index-1c18afa8.js');
require('../../index.module-d2876b1c.js');
require('../../ui/MentionLabel.js');
require('../../ui/LinkLabel.js');
require('../../ui/FileMessageItemBody.js');
require('../../ui/TextButton.js');
require('../../ui/ThumbnailMessageItemBody.js');
require('../../ui/OGMessageItemBody.js');
require('../../ui/UnknownMessageItemBody.js');
require('../../ui/QuoteMessage.js');
require('../../index-a401f2b6.js');
require('../../ui/ThreadReplies.js');
require('../../ui/VoiceMessageItemBody.js');
require('../../ui/ProgressBar.js');
require('../../VoicePlayer/useVoicePlayer.js');
require('../../index-cb1d7ac4.js');
require('../../VoiceRecorder/context.js');
require('../../withSendbird.js');
require('../../ui/PlaybackTime.js');
require('./FileViewer.js');
require('./RemoveMessageModal.js');
require('../../ui/Modal.js');
require('../../useDirtyGetMentions-97c6e05a.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

const getMessagePartsInfo = _ref => {
  let {
    allMessages = [],
    isMessageGroupingEnabled = true,
    currentIndex = 0,
    currentMessage = null,
    currentChannel = null,
    replyType = ''
  } = _ref;
  const previousMessage = allMessages[currentIndex - 1];
  const nextMessage = allMessages[currentIndex + 1];
  const [chainTop, chainBottom] = isMessageGroupingEnabled ? Channel_context.compareMessagesForGrouping(previousMessage, currentMessage, nextMessage, currentChannel, replyType) : [false, false];
  const previousMessageCreatedAt = previousMessage === null || previousMessage === void 0 ? void 0 : previousMessage.createdAt;
  const currentCreatedAt = currentMessage.createdAt;
  // https://stackoverflow.com/a/41855608
  const hasSeparator = !(previousMessageCreatedAt && index.isSameDay(currentCreatedAt, previousMessageCreatedAt));
  return {
    chainTop,
    chainBottom,
    hasSeparator
  };
};

const DELAY = 500;
function useSetScrollToBottom() {
  const [scrollBottom, setScrollBottom] = React.useState(0);
  const scrollCb = e => {
    const element = e.target;
    try {
      setScrollBottom(element.scrollHeight - element.scrollTop - element.offsetHeight);
    } catch (_unused) {
      //
    }
  };
  return {
    scrollBottom,
    scrollToBottomHandler: index$1.useDebounce(scrollCb, DELAY)
  };
}

const SCROLL_BOTTOM_PADDING = 50;
const MessageList = _ref => {
  let {
    className = '',
    renderMessage,
    renderPlaceholderEmpty,
    renderCustomSeparator,
    renderPlaceholderLoader
  } = _ref;
  const {
    allMessages,
    hasMorePrev,
    hasMoreNext,
    setInitialTimeStamp,
    setAnimatedMessageId,
    setHighLightedMessageId,
    isMessageGroupingEnabled,
    scrollRef,
    onScrollCallback,
    onScrollDownCallback,
    messagesDispatcher,
    messageActionTypes,
    currentGroupChannel,
    disableMarkAsRead,
    filterMessageList,
    replyType,
    loading,
    unreadSince
  } = Channel_context.useChannelContext();
  const store = useSendbirdStateContext();
  const allMessagesFiltered = typeof filterMessageList === 'function' ? allMessages.filter(filterMessageList) : allMessages;
  const markAsReadScheduler = store.config.markAsReadScheduler;
  const onScroll = () => {
    const element = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current;
    if (element == null) {
      return;
    }
    const {
      scrollTop,
      clientHeight,
      scrollHeight
    } = element;
    if (Channel_context.isAboutSame(scrollTop, 0, consts.SCROLL_BUFFER)) {
      onScrollCallback(messages => {
      });
    }
    if (Channel_context.isAboutSame(clientHeight + scrollTop, scrollHeight, consts.SCROLL_BUFFER) && hasMoreNext) {
      onScrollDownCallback(_ref2 => {
      });
    }
    if (!disableMarkAsRead && Channel_context.isAboutSame(clientHeight + scrollTop, scrollHeight, consts.SCROLL_BUFFER) && !!currentGroupChannel) {
      messagesDispatcher({
        type: messageActionTypes.MARK_AS_READ,
        payload: {
          channel: currentGroupChannel
        }
      });
      markAsReadScheduler.push(currentGroupChannel);
    }
  };
  const onClickScrollBot = () => {
    var _scrollRef$current;
    setInitialTimeStamp === null || setInitialTimeStamp === void 0 ? void 0 : setInitialTimeStamp(null);
    setAnimatedMessageId === null || setAnimatedMessageId === void 0 ? void 0 : setAnimatedMessageId(null);
    setHighLightedMessageId === null || setHighLightedMessageId === void 0 ? void 0 : setHighLightedMessageId(null);
    if ((scrollRef === null || scrollRef === void 0 ? void 0 : (_scrollRef$current = scrollRef.current) === null || _scrollRef$current === void 0 ? void 0 : _scrollRef$current.scrollTop) > -1) {
      var _scrollRef$current$sc, _scrollRef$current2, _scrollRef$current$of, _scrollRef$current3;
      scrollRef.current.scrollTop = ((_scrollRef$current$sc = scrollRef === null || scrollRef === void 0 ? void 0 : (_scrollRef$current2 = scrollRef.current) === null || _scrollRef$current2 === void 0 ? void 0 : _scrollRef$current2.scrollHeight) !== null && _scrollRef$current$sc !== void 0 ? _scrollRef$current$sc : 0) - ((_scrollRef$current$of = scrollRef === null || scrollRef === void 0 ? void 0 : (_scrollRef$current3 = scrollRef.current) === null || _scrollRef$current3 === void 0 ? void 0 : _scrollRef$current3.offsetHeight) !== null && _scrollRef$current$of !== void 0 ? _scrollRef$current$of : 0);
    }
  };

  // Move the messsage list scroll when the last message's height is changed by reactions
  const handleMessageHeightChange = () => {
    const current = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current;
    if (current) {
      const bottom = current.scrollHeight - current.scrollTop - current.offsetHeight;
      if (scrollBottom < bottom && scrollBottom <= consts.SCROLL_BUFFER) {
        current.scrollTop += bottom - scrollBottom;
      }
    }
  };
  // Keep the scrollBottom value after fetching new message list
  const handleMessageListHeightChange = () => {
    const current = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current;
    if (current) {
      const bottom = current.scrollHeight - current.scrollTop - current.offsetHeight;
      if (scrollBottom < bottom) {
        current.scrollTop += bottom - scrollBottom;
      }
    }
  };
  const handleOnScroll = index$1.useHandleOnScrollCallback({
    hasMore: hasMorePrev,
    hasNext: hasMoreNext,
    onScroll,
    scrollRef
  });
  const {
    scrollToBottomHandler,
    scrollBottom
  } = useSetScrollToBottom();
  if (loading) {
    return typeof renderPlaceholderLoader === 'function' ? renderPlaceholderLoader() : /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
      type: ui_PlaceHolder.PlaceHolderTypes.LOADING
    });
  }
  if (allMessagesFiltered.length < 1) {
    if (renderPlaceholderEmpty && typeof renderPlaceholderEmpty === 'function') {
      return renderPlaceholderEmpty();
    }
    return /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
      className: "sendbird-conversation__no-messages",
      type: ui_PlaceHolder.PlaceHolderTypes.NO_MESSAGES
    });
  }
  return /*#__PURE__*/React__default["default"].createElement("div", {
    className: `sendbird-conversation__messages ${className}`
  }, /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-conversation__scroll-container"
  }, /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-conversation__padding"
  }), /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-conversation__messages-padding",
    ref: scrollRef,
    onScroll: e => {
      handleOnScroll();
      scrollToBottomHandler(e);
    }
  }, allMessagesFiltered.map((m, idx) => {
    var _sender, _store$config;
    const {
      chainTop,
      chainBottom,
      hasSeparator
    } = getMessagePartsInfo({
      allMessages: allMessagesFiltered,
      replyType,
      isMessageGroupingEnabled,
      currentIndex: idx,
      currentMessage: m,
      currentChannel: currentGroupChannel
    });
    const isByMe = (m === null || m === void 0 ? void 0 : (_sender = m.sender) === null || _sender === void 0 ? void 0 : _sender.userId) === (store === null || store === void 0 ? void 0 : (_store$config = store.config) === null || _store$config === void 0 ? void 0 : _store$config.userId);
    return /*#__PURE__*/React__default["default"].createElement(Message_context.MessageProvider, {
      message: m,
      key: m === null || m === void 0 ? void 0 : m.messageId,
      isByMe: isByMe
    }, /*#__PURE__*/React__default["default"].createElement(Channel_components_Message, {
      handleScroll: handleMessageHeightChange,
      handleMessageListHeightChange: handleMessageListHeightChange,
      renderMessage: renderMessage,
      message: m,
      hasSeparator: hasSeparator,
      chainTop: chainTop,
      chainBottom: chainBottom,
      renderCustomSeparator: renderCustomSeparator
    }));
  }))), (currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.isFrozen) && /*#__PURE__*/React__default["default"].createElement(Channel_components_FrozenNotification, {
    className: "sendbird-conversation__messages__notification"
  }), /*#__PURE__*/React__default["default"].createElement(Channel_components_UnreadCount, {
    className: "sendbird-conversation__messages__notification",
    count: currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.unreadMessageCount,
    time: unreadSince,
    onClick: () => {
      var _scrollRef$current4;
      if (scrollRef !== null && scrollRef !== void 0 && (_scrollRef$current4 = scrollRef.current) !== null && _scrollRef$current4 !== void 0 && _scrollRef$current4.scrollTop) {
        var _scrollRef$current$sc2, _scrollRef$current5, _scrollRef$current$of2, _scrollRef$current6;
        scrollRef.current.scrollTop = ((_scrollRef$current$sc2 = scrollRef === null || scrollRef === void 0 ? void 0 : (_scrollRef$current5 = scrollRef.current) === null || _scrollRef$current5 === void 0 ? void 0 : _scrollRef$current5.scrollHeight) !== null && _scrollRef$current$sc2 !== void 0 ? _scrollRef$current$sc2 : 0) - ((_scrollRef$current$of2 = scrollRef === null || scrollRef === void 0 ? void 0 : (_scrollRef$current6 = scrollRef.current) === null || _scrollRef$current6 === void 0 ? void 0 : _scrollRef$current6.offsetHeight) !== null && _scrollRef$current$of2 !== void 0 ? _scrollRef$current$of2 : 0);
      }
      if (!disableMarkAsRead && !!currentGroupChannel) {
        markAsReadScheduler.push(currentGroupChannel);
        messagesDispatcher({
          type: messageActionTypes.MARK_AS_READ,
          payload: {
            channel: currentGroupChannel
          }
        });
      }
      setInitialTimeStamp(null);
      setAnimatedMessageId(null);
      setHighLightedMessageId(null);
    }
  }),
  // This flag is an unmatched variable
  scrollBottom > SCROLL_BOTTOM_PADDING && /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-conversation__scroll-bottom-button",
    onClick: onClickScrollBot,
    onKeyDown: onClickScrollBot,
    tabIndex: 0,
    role: "button"
  }, /*#__PURE__*/React__default["default"].createElement(ui_Icon["default"], {
    width: "24px",
    height: "24px",
    type: ui_Icon.IconTypes.CHEVRON_DOWN,
    fillColor: ui_Icon.IconColors.PRIMARY
  })));
};

module.exports = MessageList;
//# sourceMappingURL=MessageList.js.map
