'use strict';

var React = require('react');
var Channel_context = require('../../ChannelProvider-a05d259f.js');
var ui_PlaceHolder = require('../../index-9a5e4383.js');
var ui_Icon = require('../../ui/Icon.js');
var Channel_components_Message = require('./Message.js');
var index = require('../../index-a3268370.js');
var Channel_components_UnreadCount = require('./UnreadCount.js');
var Channel_components_FrozenNotification = require('./FrozenNotification.js');
var consts = require('../../consts-900e72b9.js');
var useSendbirdStateContext = require('../../useSendbirdStateContext.js');
var Message_context = require('../../Message/context.js');
var index$1 = require('../../index-c08f5bf5.js');
require('../../UserProfileContext-9d843d68.js');
require('prop-types');
require('../../const-1ea78727.js');
require('../../index-892b4b7f.js');
require('../../index-88e8fdfa.js');
require('../../topics-373d2156.js');
require('../../index-1b3c69da.js');
require('../../_rollupPluginBabelHelpers-21ae158b.js');
require('../../utils/message/getOutgoingMessageState.js');
require('../../compareIds-a846891d.js');
require('@sendbird/chat/groupChannel');
require('../../uuid-dee74248.js');
require('@sendbird/chat/message');
require('../../resolvedReplyType-14fa0f85.js');
require('../../LocalizationContext-44d2f61b.js');
require('../../stringSet-7aebf034.js');
require('../../index-2bfd366f.js');
require('../../ui/Loader.js');
require('./SuggestedMentionList.js');
require('../../ui/Avatar.js');
require('../../ui/ImageRenderer.js');
require('../../const-bd02657f.js');
require('../../ThreadProvider-bac1bea8.js');
require('../../Thread/context/types.js');
require('@sendbird/chat');
require('../../ui/DateSeparator.js');
require('../../color-0c04efbd.js');
require('../../ui/MessageInput.js');
require('../../ui/IconButton.js');
require('../../ui/Button.js');
require('dompurify');
require('../../consts-867f1ae6.js');
require('../../consts-b93ef9ea.js');
require('../../consts-bce71b24.js');
require('../../tokenize-44139f1e.js');
require('../../index.module-5a6a79b6.js');
require('../../ui/MessageContent.js');
require('../../ui/UserProfile.js');
require('../../sendbirdSelectors.js');
require('../../utils-6a748c02.js');
require('../../index-b6657c80.js');
require('../../index-24f791d1.js');
require('../../ui/MessageItemMenu.js');
require('../../ui/ContextMenu.js');
require('react-dom');
require('../../ui/SortByRow.js');
require('../../types-df5bd4e5.js');
require('../../ui/MessageItemReactionMenu.js');
require('../../ui/ReactionButton.js');
require('../../useLongPress-83b6a2f1.js');
require('../../MediaQueryContext-5d311a86.js');
require('../../ui/EmojiReactions.js');
require('../../ui/ReactionBadge.js');
require('../../ui/BottomSheet.js');
require('../../index-0a446cca.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-8cd9b25d.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-78a1037e.js');
require('../../ui/ThreadReplies.js');
require('../../ui/VoiceMessageItemBody.js');
require('../../ui/ProgressBar.js');
require('../../VoicePlayer/useVoicePlayer.js');
require('../../index-50c4a83b.js');
require('../../VoiceRecorder/context.js');
require('../../ui/Modal.js');
require('../../withSendbird.js');
require('../../ui/PlaybackTime.js');
require('./FileViewer.js');
require('./RemoveMessageModal.js');
require('../../useDirtyGetMentions-1500af53.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(_ref) {
  let {
    loading
  } = _ref;
  const [scrollBottom, setScrollBottom] = React.useState(0);
  React.useEffect(() => {
    if (loading) {
      setScrollBottom(0);
    }
  }, [loading]);
  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)
  };
}

function useScrollBehavior() {
  const {
    scrollRef,
    scrollBehavior = 'auto'
  } = Channel_context.useChannelContext();
  React.useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.style.scrollBehavior = scrollBehavior;
    }
  }, [scrollRef.current]);
  return null;
}

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;
  useScrollBehavior();
  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);
    }
  };

  /**
   * 1. Move the messsage list scroll
   *    when each message's height is changed by `reactions` OR `showEdit`
   * 2. Keep the scrollBottom value after fetching new message list
   */
  const moveScroll = function () {
    let isBottomMessageAffected = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    const current = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current;
    if (current) {
      const bottom = current.scrollHeight - current.scrollTop - current.offsetHeight;
      if (scrollBottom < bottom && (!isBottomMessageAffected || scrollBottom < consts.SCROLL_BUFFER)) {
        // Move the scroll as much as the height of the message has changed
        current.scrollTop += bottom - scrollBottom;
      }
    }
  };
  const handleOnScroll = index$1.useHandleOnScrollCallback({
    hasMore: hasMorePrev,
    hasNext: hasMoreNext,
    onScroll,
    scrollRef
  });
  const {
    scrollToBottomHandler,
    scrollBottom
  } = useSetScrollToBottom({
    loading
  });
  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: moveScroll,
      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"
  }), unreadSince && /*#__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
