import React__default, { useState, useEffect } from 'react';
import { c as compareMessagesForGrouping, u as useChannelContext, i as isAboutSame } from '../../ChannelProvider-498954bf.js';
import { P as PlaceHolder, a as PlaceHolderTypes } from '../../index-49ff1ed1.js';
import Icon, { IconTypes, IconColors } from '../../ui/Icon.js';
import Message from './Message.js';
import { i as isSameDay } from '../../index-39306dfb.js';
import UnreadCount from './UnreadCount.js';
import FrozenNotification from './FrozenNotification.js';
import { S as SCROLL_BUFFER } from '../../consts-33537265.js';
import useSendbirdStateContext from '../../useSendbirdStateContext.js';
import { MessageProvider } from '../../Message/context.js';
import { u as useDebounce, a as useHandleOnScrollCallback } from '../../index-28ad85ee.js';
import '../../UserProfileContext-d5787c95.js';
import 'prop-types';
import '../../const-97fac210.js';
import '../../index-2dc53ac2.js';
import '../../index-67135027.js';
import '../../topics-f3629ea0.js';
import '../../index-eefb44ba.js';
import '../../_rollupPluginBabelHelpers-4f8ebde4.js';
import '../../utils/message/getOutgoingMessageState.js';
import '../../compareIds-7800035f.js';
import '@sendbird/chat/groupChannel';
import '../../uuid-a79b5ba8.js';
import '@sendbird/chat/message';
import '../../resolvedReplyType-e00d5fd9.js';
import '../../LocalizationContext-b2390bf8.js';
import '../../stringSet-eefbc798.js';
import '../../index-4372fcec.js';
import '../../ui/Loader.js';
import './SuggestedMentionList.js';
import '../../ui/Avatar.js';
import '../../ui/ImageRenderer.js';
import '../../const-922f4cc5.js';
import '../../ThreadProvider-2bdeb95d.js';
import '../../Thread/context/types.js';
import '@sendbird/chat';
import '../../ui/DateSeparator.js';
import '../../color-9519a526.js';
import '../../ui/MessageInput.js';
import '../../ui/IconButton.js';
import '../../ui/Button.js';
import 'dompurify';
import '../../consts-8ce876a0.js';
import '../../consts-e3e03145.js';
import '../../consts-cdccf171.js';
import '../../tokenize-b97bc343.js';
import '../../index.module-2885df8c.js';
import '../../ui/MessageContent.js';
import '../../ui/UserProfile.js';
import '../../sendbirdSelectors.js';
import '../../utils-b53fe532.js';
import '../../index-1d741554.js';
import '../../index-0d1114ee.js';
import '../../ui/MessageItemMenu.js';
import '../../ui/ContextMenu.js';
import 'react-dom';
import '../../ui/SortByRow.js';
import '../../types-234b17b9.js';
import '../../ui/MessageItemReactionMenu.js';
import '../../ui/ReactionButton.js';
import '../../useLongPress-cb2d23be.js';
import '../../MediaQueryContext-b4904a2e.js';
import '../../ui/EmojiReactions.js';
import '../../ui/ReactionBadge.js';
import '../../ui/BottomSheet.js';
import '../../index-896545a0.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-8aa7880e.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-484b4a5d.js';
import '../../ui/ThreadReplies.js';
import '../../ui/VoiceMessageItemBody.js';
import '../../ui/ProgressBar.js';
import '../../VoicePlayer/useVoicePlayer.js';
import '../../index-7d496661.js';
import '../../VoiceRecorder/context.js';
import '../../ui/Modal.js';
import '../../withSendbird.js';
import '../../ui/PlaybackTime.js';
import './FileViewer.js';
import './RemoveMessageModal.js';
import '../../useDirtyGetMentions-5f675b6c.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(_ref) {
  let {
    loading
  } = _ref;
  const [scrollBottom, setScrollBottom] = useState(0);
  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: useDebounce(scrollCb, DELAY)
  };
}

function useScrollBehavior() {
  const {
    scrollRef,
    scrollBehavior = 'auto'
  } = useChannelContext();
  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
  } = 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 (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);
    }
  };

  /**
   * 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 < SCROLL_BUFFER)) {
        // Move the scroll as much as the height of the message has changed
        current.scrollTop += bottom - scrollBottom;
      }
    }
  };
  const handleOnScroll = useHandleOnScrollCallback({
    hasMore: hasMorePrev,
    hasNext: hasMoreNext,
    onScroll,
    scrollRef
  });
  const {
    scrollToBottomHandler,
    scrollBottom
  } = useSetScrollToBottom({
    loading
  });
  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: 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.createElement(FrozenNotification, {
    className: "sendbird-conversation__messages__notification"
  }), unreadSince && /*#__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
