import React__default, { useState } from 'react';
import { c as compareMessagesForGrouping, u as useChannelContext, i as isAboutSame } from '../../ChannelProvider-205bb2b4.js';
import { P as PlaceHolder, a as PlaceHolderTypes } from '../../index-b26a2bcd.js';
import Icon, { IconTypes, IconColors } from '../../ui/Icon.js';
import Message from './Message.js';
import { i as isSameDay } from '../../index-1c8252a9.js';
import UnreadCount from './UnreadCount.js';
import FrozenNotification from './FrozenNotification.js';
import { S as SCROLL_BUFFER } from '../../consts-37c3d0a0.js';
import useSendbirdStateContext from '../../useSendbirdStateContext.js';
import { MessageProvider } from '../../Message/context.js';
import { u as useDebounce, a as useHandleOnScrollCallback } from '../../index-93228741.js';
import '../../UserProfileContext-96f68187.js';
import 'prop-types';
import '../../const-4bc8cbc7.js';
import '../../index-0e63045e.js';
import '../../index-26c66412.js';
import '../../topics-50ed8c29.js';
import '../../index-46da725e.js';
import '../../_rollupPluginBabelHelpers-52628376.js';
import '../../utils/message/getOutgoingMessageState.js';
import '../../compareIds-c483b4db.js';
import '@sendbird/chat/groupChannel';
import '../../uuid-9e3aeec6.js';
import '@sendbird/chat/message';
import '../../resolvedReplyType-bfdfe6bd.js';
import '../../LocalizationContext-bcaf447a.js';
import '../../stringSet-7f300d56.js';
import '../../index-208f60f9.js';
import '../../ui/Loader.js';
import './SuggestedMentionList.js';
import '../../ui/Avatar.js';
import '../../ui/ImageRenderer.js';
import '../../const-c64639fc.js';
import '../../ThreadProvider-7a96557d.js';
import '../../Thread/context/types.js';
import '@sendbird/chat';
import '../../ui/DateSeparator.js';
import '../../color-5dee2e2d.js';
import '../../ui/MessageInput.js';
import '../../ui/IconButton.js';
import '../../ui/Button.js';
import 'dompurify';
import '../../consts-acdc6c08.js';
import '../../consts-c99872c0.js';
import '../../consts-cf7328d6.js';
import '../../tokenize-aa91b5a4.js';
import '../../index.module-6fe8c3f8.js';
import '../../ui/MessageContent.js';
import '../../ui/UserProfile.js';
import '../../sendbirdSelectors.js';
import '../../utils-4ce9435a.js';
import '../../index-4e834e8c.js';
import '../../index-fb9203f4.js';
import '../../ui/MessageItemMenu.js';
import '../../ui/ContextMenu.js';
import 'react-dom';
import '../../ui/SortByRow.js';
import '../../types-061bedf1.js';
import '../../ui/MessageItemReactionMenu.js';
import '../../ui/ReactionButton.js';
import '../../useLongPress-8b46567a.js';
import '../../MediaQueryContext-0d6b7936.js';
import '../../ui/EmojiReactions.js';
import '../../ui/ReactionBadge.js';
import '../../ui/BottomSheet.js';
import '../../index-5ca598bf.js';
import '../../ui/UserListItem.js';
import '../../ui/MutedAvatarOverlay.js';
import '../../ui/Checkbox.js';
import '../../ui/Tooltip.js';
import '../../ui/TooltipWrapper.js';
import '../../ui/AdminMessage.js';
import '../../ui/TextMessageItemBody.js';
import '../../index-78f0d986.js';
import '../../ui/MentionLabel.js';
import '../../ui/LinkLabel.js';
import '../../ui/FileMessageItemBody.js';
import '../../ui/TextButton.js';
import '../../ui/ThumbnailMessageItemBody.js';
import '../../ui/OGMessageItemBody.js';
import '../../ui/UnknownMessageItemBody.js';
import '../../ui/QuoteMessage.js';
import '../../index-c216a28a.js';
import '../../ui/ThreadReplies.js';
import '../../ui/VoiceMessageItemBody.js';
import '../../ui/ProgressBar.js';
import '../../VoicePlayer/useVoicePlayer.js';
import '../../index-dea18b86.js';
import '../../VoiceRecorder/context.js';
import '../../ui/Modal.js';
import '../../withSendbird.js';
import '../../ui/PlaybackTime.js';
import './FileViewer.js';
import './RemoveMessageModal.js';
import '../../useDirtyGetMentions-8a3ab1ab.js';

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 ? 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 && isSameDay(currentCreatedAt, previousMessageCreatedAt));
  return {
    chainTop,
    chainBottom,
    hasSeparator
  };
};

const DELAY = 500;
function useSetScrollToBottom() {
  const [scrollBottom, setScrollBottom] = useState(0);
  const scrollCb = e => {
    const element = e.target;
    try {
      setScrollBottom(element.scrollHeight - element.scrollTop - element.offsetHeight);
    } catch (_unused) {
      //
    }
  };
  return {
    scrollBottom,
    scrollToBottomHandler: 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
  } = 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 (isAboutSame(scrollTop, 0, SCROLL_BUFFER)) {
      onScrollCallback(messages => {
      });
    }
    if (isAboutSame(clientHeight + scrollTop, scrollHeight, SCROLL_BUFFER) && hasMoreNext) {
      onScrollDownCallback(_ref2 => {
      });
    }
    if (!disableMarkAsRead && isAboutSame(clientHeight + scrollTop, scrollHeight, 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 <= 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 = useHandleOnScrollCallback({
    hasMore: hasMorePrev,
    hasNext: hasMoreNext,
    onScroll,
    scrollRef
  });
  const {
    scrollToBottomHandler,
    scrollBottom
  } = useSetScrollToBottom();
  if (loading) {
    return typeof renderPlaceholderLoader === 'function' ? renderPlaceholderLoader() : /*#__PURE__*/React__default.createElement(PlaceHolder, {
      type: PlaceHolderTypes.LOADING
    });
  }
  if (allMessagesFiltered.length < 1) {
    if (renderPlaceholderEmpty && typeof renderPlaceholderEmpty === 'function') {
      return renderPlaceholderEmpty();
    }
    return /*#__PURE__*/React__default.createElement(PlaceHolder, {
      className: "sendbird-conversation__no-messages",
      type: PlaceHolderTypes.NO_MESSAGES
    });
  }
  return /*#__PURE__*/React__default.createElement("div", {
    className: `sendbird-conversation__messages ${className}`
  }, /*#__PURE__*/React__default.createElement("div", {
    className: "sendbird-conversation__scroll-container"
  }, /*#__PURE__*/React__default.createElement("div", {
    className: "sendbird-conversation__padding"
  }), /*#__PURE__*/React__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.createElement(MessageProvider, {
      message: m,
      key: m === null || m === void 0 ? void 0 : m.messageId,
      isByMe: isByMe
    }, /*#__PURE__*/React__default.createElement(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.createElement(FrozenNotification, {
    className: "sendbird-conversation__messages__notification"
  }), /*#__PURE__*/React__default.createElement(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.createElement("div", {
    className: "sendbird-conversation__scroll-bottom-button",
    onClick: onClickScrollBot,
    onKeyDown: onClickScrollBot,
    tabIndex: 0,
    role: "button"
  }, /*#__PURE__*/React__default.createElement(Icon, {
    width: "24px",
    height: "24px",
    type: IconTypes.CHEVRON_DOWN,
    fillColor: IconColors.PRIMARY
  })));
};

export { MessageList as default };
//# sourceMappingURL=MessageList.js.map
