'use strict';

var React = require('react');
var useSendbirdStateContext = require('../../useSendbirdStateContext.js');
var LocalizationContext = require('../../LocalizationContext-44d2f61b.js');
var utils = require('../../utils-6a43371d.js');
var Thread_context = require('../../ThreadProvider-bac1bea8.js');
var Thread_components_ParentMessageInfo = require('./ParentMessageInfo.js');
var Thread_components_ThreadHeader = require('./ThreadHeader.js');
var Thread_components_ThreadList = require('./ThreadList.js');
var Thread_components_ThreadMessageInput = require('./ThreadMessageInput.js');
var Thread_context_types = require('../context/types.js');
var ui_PlaceHolder = require('../../index-9a5e4383.js');
var ui_Label = require('../../index-2bfd366f.js');
var Message_context = require('../../Message/context.js');
require('../../withSendbird.js');
require('../../_rollupPluginBabelHelpers-21ae158b.js');
require('../../stringSet-7aebf034.js');
require('../../index-88e8fdfa.js');
require('../../index-892b4b7f.js');
require('../../utils/message/getOutgoingMessageState.js');
require('../../UserProfileContext-9d843d68.js');
require('prop-types');
require('@sendbird/chat');
require('../../topics-373d2156.js');
require('@sendbird/chat/groupChannel');
require('../../uuid-dee74248.js');
require('@sendbird/chat/message');
require('../../consts-900e72b9.js');
require('../../RemoveMessageModal-81daa8a0.js');
require('../../ui/Modal.js');
require('react-dom');
require('../../index-0a446cca.js');
require('../../ui/Button.js');
require('../../ui/Icon.js');
require('../../ui/IconButton.js');
require('../../MediaQueryContext-5d311a86.js');
require('./ParentMessageInfoItem.js');
require('../../index-1b3c69da.js');
require('../../ui/ImageRenderer.js');
require('../../ui/TextButton.js');
require('../../color-0c04efbd.js');
require('../../ui/EmojiReactions.js');
require('../../ui/ReactionBadge.js');
require('../../ui/ReactionButton.js');
require('../../useLongPress-83b6a2f1.js');
require('../../utils-6a748c02.js');
require('../../ui/ContextMenu.js');
require('../../ui/SortByRow.js');
require('../../ui/BottomSheet.js');
require('../../ui/UserListItem.js');
require('../../ui/Avatar.js');
require('../../ui/MutedAvatarOverlay.js');
require('../../ui/Checkbox.js');
require('../../ui/UserProfile.js');
require('../../sendbirdSelectors.js');
require('../../ui/Tooltip.js');
require('../../ui/TooltipWrapper.js');
require('../../ui/VoiceMessageItemBody.js');
require('../../ui/ProgressBar.js');
require('../../VoicePlayer/useVoicePlayer.js');
require('../../index-50c4a83b.js');
require('../../VoiceRecorder/context.js');
require('../../ui/PlaybackTime.js');
require('../../ui/Loader.js');
require('../../index-8cd9b25d.js');
require('../../index.module-5a6a79b6.js');
require('../../tokenize-44139f1e.js');
require('../../ui/MentionLabel.js');
require('../../ui/LinkLabel.js');
require('../../ChannelProvider-a05d259f.js');
require('../../const-1ea78727.js');
require('../../compareIds-a846891d.js');
require('../../resolvedReplyType-14fa0f85.js');
require('../../Channel/components/SuggestedMentionList.js');
require('../../const-bd02657f.js');
require('../../ui/FileViewer.js');
require('../../ui/MessageItemMenu.js');
require('../../types-df5bd4e5.js');
require('../../ui/MessageItemReactionMenu.js');
require('../../ui/MessageInput.js');
require('dompurify');
require('../../consts-867f1ae6.js');
require('../../consts-b93ef9ea.js');
require('../../consts-bce71b24.js');
require('../../index-78a1037e.js');
require('../../useDirtyGetMentions-1500af53.js');
require('./ThreadListItem.js');
require('../../ui/DateSeparator.js');
require('../../index-b6657c80.js');
require('../../index-24f791d1.js');
require('../../index-a3268370.js');
require('../../ui/TextMessageItemBody.js');
require('../../ui/OGMessageItemBody.js');
require('../../ui/FileMessageItemBody.js');
require('../../ui/ThumbnailMessageItemBody.js');
require('../../ui/UnknownMessageItemBody.js');
require('date-fns');
require('../../VoiceMessageInputWrapper-6625f53a.js');
require('../../VoiceRecorder/useVoiceRecorder.js');
require('../../index-4d2879d6.js');

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

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

const useMemorizedHeader = _ref => {
  let {
    renderHeader
  } = _ref;
  return React.useMemo(() => {
    if (typeof renderHeader === 'function') {
      return renderHeader();
    }
    return null;
  }, [renderHeader]);
};

const useMemorizedParentMessageInfo = _ref => {
  let {
    parentMessage,
    parentMessageState,
    renderParentMessageInfo,
    renderParentMessageInfoPlaceholder
  } = _ref;
  return React.useMemo(() => {
    if (parentMessageState === Thread_context_types.ParentMessageStateTypes.NIL || parentMessageState === Thread_context_types.ParentMessageStateTypes.LOADING || parentMessageState === Thread_context_types.ParentMessageStateTypes.INVALID) {
      if (typeof renderParentMessageInfoPlaceholder === 'function') {
        return renderParentMessageInfoPlaceholder(parentMessageState);
      }
      switch (parentMessageState) {
        case Thread_context_types.ParentMessageStateTypes.NIL:
          {
            return /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
              className: "sendbird-thread-ui__parent-message-info placeholder-nil",
              type: ui_PlaceHolder.PlaceHolderTypes.NO_RESULTS,
              iconSize: "64px"
            });
          }
        case Thread_context_types.ParentMessageStateTypes.LOADING:
          {
            return /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
              className: "sendbird-thread-ui__parent-message-info placeholder-loading",
              type: ui_PlaceHolder.PlaceHolderTypes.LOADING,
              iconSize: "64px"
            });
          }
        case Thread_context_types.ParentMessageStateTypes.INVALID:
          {
            return /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
              className: "sendbird-thread-ui__parent-message-info placeholder-invalid",
              type: ui_PlaceHolder.PlaceHolderTypes.WRONG,
              iconSize: "64px"
            });
          }
        default:
          {
            return null;
          }
      }
    } else if (parentMessageState === Thread_context_types.ParentMessageStateTypes.INITIALIZED) {
      if (typeof renderParentMessageInfo === 'function') {
        return renderParentMessageInfo();
      }
    }
    return null;
  }, [parentMessage, parentMessageState, renderParentMessageInfo, renderParentMessageInfoPlaceholder]);
};

const useMemorizedThreadList = _ref => {
  let {
    threadListState,
    renderThreadListPlaceHolder
  } = _ref;
  return React.useMemo(() => {
    if (threadListState === Thread_context_types.ThreadListStateTypes.NIL || threadListState === Thread_context_types.ThreadListStateTypes.LOADING || threadListState === Thread_context_types.ThreadListStateTypes.INVALID) {
      if (typeof renderThreadListPlaceHolder === 'function') {
        return renderThreadListPlaceHolder(threadListState);
      }
      switch (threadListState) {
        case Thread_context_types.ThreadListStateTypes.LOADING:
          {
            return /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
              className: "sendbird-thread-ui__thread-list placeholder-loading",
              type: ui_PlaceHolder.PlaceHolderTypes.LOADING,
              iconSize: "64px"
            });
          }
        case Thread_context_types.ThreadListStateTypes.INVALID:
          {
            return /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
              className: "sendbird-thread-ui__thread-list placeholder-invalid",
              type: ui_PlaceHolder.PlaceHolderTypes.WRONG,
              iconSize: "64px"
            });
          }
        case Thread_context_types.ThreadListStateTypes.NIL:
          {
            return /*#__PURE__*/React__default["default"].createElement(React__default["default"].Fragment, null);
          }
        default:
          {
            return null;
          }
      }
    }
    return null;
  }, [threadListState, renderThreadListPlaceHolder]);
};

const ThreadUI = _ref => {
  var _stores$sdkStore, _stores$sdkStore$sdk, _stores$sdkStore$sdk$, _parentMessage$sender;
  let {
    renderHeader,
    renderParentMessageInfo,
    renderMessage,
    renderMessageInput,
    renderCustomSeparator,
    renderParentMessageInfoPlaceholder,
    renderThreadListPlaceHolder,
    renderFileUploadIcon,
    renderVoiceMessageIcon,
    renderSendMessageIcon
  } = _ref;
  const {
    stores
  } = useSendbirdStateContext();
  const currentUserId = stores === null || stores === void 0 ? void 0 : (_stores$sdkStore = stores.sdkStore) === null || _stores$sdkStore === void 0 ? void 0 : (_stores$sdkStore$sdk = _stores$sdkStore.sdk) === null || _stores$sdkStore$sdk === void 0 ? void 0 : (_stores$sdkStore$sdk$ = _stores$sdkStore$sdk.currentUser) === null || _stores$sdkStore$sdk$ === void 0 ? void 0 : _stores$sdkStore$sdk$.userId;
  const {
    stringSet
  } = LocalizationContext.useLocalization();
  const {
    currentChannel,
    allThreadMessages,
    parentMessage,
    parentMessageState,
    threadListState,
    hasMorePrev,
    hasMoreNext,
    fetchPrevThreads,
    fetchNextThreads,
    onHeaderActionClick,
    onMoveToParentMessage
  } = Thread_context.useThreadContext();
  const replyCount = allThreadMessages.length;
  const isByMe = currentUserId === (parentMessage === null || parentMessage === void 0 ? void 0 : (_parentMessage$sender = parentMessage.sender) === null || _parentMessage$sender === void 0 ? void 0 : _parentMessage$sender.userId);

  // Memoized custom components
  const MemorizedHeader = useMemorizedHeader({
    renderHeader
  });
  const MemorizedParentMessageInfo = useMemorizedParentMessageInfo({
    parentMessage,
    parentMessageState,
    renderParentMessageInfo,
    renderParentMessageInfoPlaceholder // nil, loading, invalid
  });

  const MemorizedThreadList = useMemorizedThreadList({
    threadListState,
    renderThreadListPlaceHolder
  });

  // scroll
  const [scrollBottom, setScrollBottom] = React.useState(0);
  const scrollRef = React.useRef(null);
  const onScroll = e => {
    var _scrollRef$current;
    const element = e.target;
    const {
      scrollTop,
      clientHeight,
      scrollHeight
    } = element;
    const threadItemNodes = (_scrollRef$current = scrollRef.current) === null || _scrollRef$current === void 0 ? void 0 : _scrollRef$current.querySelectorAll('.sendbird-thread-list-item');
    const firstNode = threadItemNodes === null || threadItemNodes === void 0 ? void 0 : threadItemNodes[0];
    if (Thread_context.isAboutSame(scrollTop, 0, 10) && hasMorePrev) {
      fetchPrevThreads(messages => {
        if (messages) {
          try {
            var _firstNode$scrollInto;
            firstNode === null || firstNode === void 0 ? void 0 : (_firstNode$scrollInto = firstNode.scrollIntoView) === null || _firstNode$scrollInto === void 0 ? void 0 : _firstNode$scrollInto.call(firstNode, {
              block: 'start',
              inline: 'nearest'
            });
          } catch (error) {
            //
          }
        }
      });
    }
    if (Thread_context.isAboutSame(clientHeight + scrollTop, scrollHeight, 10) && hasMoreNext) {
      const scrollTop_ = scrollTop;
      fetchNextThreads(messages => {
        if (messages) {
          try {
            element.scrollTop = scrollTop_;
            scrollRef.current.scrollTop = scrollTop_;
          } catch (error) {
            //
          }
        }
      });
    }

    // save the lastest scroll bottom value
    if (scrollRef !== null && scrollRef !== void 0 && scrollRef.current) {
      const current = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current;
      setScrollBottom(current.scrollHeight - current.scrollTop - current.offsetHeight);
    }
  };
  return /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-thread-ui"
  }, MemorizedHeader || /*#__PURE__*/React__default["default"].createElement(Thread_components_ThreadHeader, {
    className: "sendbird-thread-ui__header",
    channelName: utils.getChannelTitle(currentChannel, currentUserId, stringSet),
    onActionIconClick: onHeaderActionClick,
    onChannelNameClick: () => {
      onMoveToParentMessage === null || onMoveToParentMessage === void 0 ? void 0 : onMoveToParentMessage({
        message: parentMessage,
        channel: currentChannel
      });
    }
  }), /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-thread-ui--scroll",
    ref: scrollRef,
    onScroll: onScroll
  }, /*#__PURE__*/React__default["default"].createElement(Message_context.MessageProvider, {
    message: parentMessage,
    isByMe: isByMe
  }, MemorizedParentMessageInfo || /*#__PURE__*/React__default["default"].createElement(Thread_components_ParentMessageInfo, {
    className: "sendbird-thread-ui__parent-message-info"
  })), replyCount > 0 && /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-thread-ui__reply-counts"
  }, /*#__PURE__*/React__default["default"].createElement(ui_Label.Label, {
    type: ui_Label.LabelTypography.BODY_1,
    color: ui_Label.LabelColors.ONBACKGROUND_3
  }, `${replyCount} ${replyCount > 1 ? stringSet.THREAD__THREAD_REPLIES : stringSet.THREAD__THREAD_REPLY}`)), MemorizedThreadList || /*#__PURE__*/React__default["default"].createElement(Thread_components_ThreadList, {
    className: "sendbird-thread-ui__thread-list",
    allThreadMessages: allThreadMessages,
    renderMessage: renderMessage,
    renderCustomSeparator: renderCustomSeparator,
    scrollRef: scrollRef,
    scrollBottom: scrollBottom
  })), (renderMessageInput === null || renderMessageInput === void 0 ? void 0 : renderMessageInput()) || /*#__PURE__*/React__default["default"].createElement(Thread_components_ThreadMessageInput, {
    className: "sendbird-thread-ui__message-input",
    renderFileUploadIcon: renderFileUploadIcon,
    renderVoiceMessageIcon: renderVoiceMessageIcon,
    renderSendMessageIcon: renderSendMessageIcon
  }));
};

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