'use strict';

var React = require('react');
var Channel_context = require('../../ChannelProvider-39d1e9a4.js');
var ui_PlaceHolder = require('../../index-985a1afb.js');
var ui_Icon = require('../../ui/Icon.js');
var Channel_components_Message = require('./Message.js');
var index = require('../../index-bf8f9551.js');
var Channel_components_UnreadCount = require('./UnreadCount.js');
var Channel_components_FrozenNotification = require('./FrozenNotification.js');
var consts = require('../../consts-9641990e.js');
var useSendbirdStateContext = require('../../useSendbirdStateContext.js');
var Message_context = require('../../Message/context.js');
var index$1 = require('../../index-f6c6728e.js');
require('../../UserProfileContext-d993c96b.js');
require('prop-types');
require('../../const-a3e169f4.js');
require('../../index-3fc4f7d7.js');
require('../../index-d749c4c2.js');
require('../../topics-e24ef339.js');
require('../../index-a91b85d9.js');
require('../../_rollupPluginBabelHelpers-acf412a3.js');
require('../../utils/message/getOutgoingMessageState.js');
require('../../compareIds-784d9a4e.js');
require('@sendbird/chat/groupChannel');
require('../../uuid-1eceb0c8.js');
require('@sendbird/chat/message');
require('../../resolvedReplyType-930f5b54.js');
require('../../LocalizationContext-8cc9717d.js');
require('../../stringSet-ce782136.js');
require('../../index-35633fb6.js');
require('../../ui/Loader.js');
require('./SuggestedMentionList.js');
require('../../ui/Avatar.js');
require('../../ui/ImageRenderer.js');
require('../../const-b19292fd.js');
require('../../ThreadProvider-c83249cf.js');
require('../../Thread/context/types.js');
require('@sendbird/chat');
require('../../ui/DateSeparator.js');
require('../../color-5cfb41c7.js');
require('../../ui/MessageInput.js');
require('../../ui/IconButton.js');
require('../../ui/Button.js');
require('dompurify');
require('../../consts-d04401ad.js');
require('../../consts-016f07ac.js');
require('../../consts-eb163887.js');
require('../../tokenize-88b021e0.js');
require('../../index.module-e3392caa.js');
require('../../ui/MessageContent.js');
require('../../ui/UserProfile.js');
require('../../sendbirdSelectors.js');
require('../../utils-5aa0708e.js');
require('../../index-0a0a6c08.js');
require('../../index-0e24aca4.js');
require('../../ui/MessageItemMenu.js');
require('../../ui/ContextMenu.js');
require('react-dom');
require('../../ui/SortByRow.js');
require('../../types-9466af03.js');
require('../../ui/MessageItemReactionMenu.js');
require('../../ui/ReactionButton.js');
require('../../useLongPress-cf56e64a.js');
require('../../MediaQueryContext-fad211ad.js');
require('../../ui/EmojiReactions.js');
require('../../ui/ReactionBadge.js');
require('../../ui/BottomSheet.js');
require('../../index-8029e07a.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-db8116c0.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-ff7b4cb6.js');
require('../../ui/ThreadReplies.js');
require('../../ui/VoiceMessageItemBody.js');
require('../../ui/ProgressBar.js');
require('../../VoicePlayer/useVoicePlayer.js');
require('../../index-90711a57.js');
require('../../VoiceRecorder/context.js');
require('../../ui/Modal.js');
require('../../withSendbird.js');
require('../../ui/PlaybackTime.js');
require('./FileViewer.js');
require('./RemoveMessageModal.js');
require('../../useDirtyGetMentions-cc476482.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
