import { a as __spreadArray } from '../../tslib.es6-e1c2b6be.js';
import React__default, { useState, useEffect, useRef, useLayoutEffect, useMemo } from 'react';
import { f as format } from '../../index-99933718.js';
import SuggestedMentionList from './SuggestedMentionList.js';
import useSendbirdStateContext from '../../useSendbirdStateContext.js';
import { u as useChannelContext, a as isDisabledBecauseFrozen, b as isDisabledBecauseMuted } from '../../ChannelProvider-c1c00018.js';
import { j as getClassName } from '../../index-43834bc0.js';
import { a as MAX_USER_MENTION_COUNT, b as MAX_USER_SUGGESTION_COUNT } from '../../const-85535a89.js';
import DateSeparator from '../../ui/DateSeparator.js';
import { L as Label, a as LabelTypography, b as LabelColors } from '../../index-e121c395.js';
import MessageInput from '../../ui/MessageInput.js';
import MessageContent from '../../ui/MessageContent.js';
import FileViewer from './FileViewer.js';
import RemoveMessage from './RemoveMessageModal.js';
import { M as MessageInputKeys } from '../../const-0f759572.js';
import { u as useLocalization } from '../../LocalizationContext-8725e9b2.js';
import '../../index-c10fcd31.js';
import '../../ui/Icon.js';
import 'prop-types';
import '../../ui/Avatar.js';
import '../../ui/ImageRenderer.js';
import '../../uuid-d072af26.js';
import '../../ThreadProvider-e64f95cc.js';
import '../../utils/message/getOutgoingMessageState.js';
import '../../UserProfileContext-cc71f901.js';
import '../../Thread/context/types.js';
import '@sendbird/chat';
import '../../topics-a581acbb.js';
import '@sendbird/chat/groupChannel';
import '@sendbird/chat/message';
import '../../consts-59f719d8.js';
import '../../withSendbird.js';
import '../../_rollupPluginBabelHelpers-945410b2.js';
import '../../compareIds-87972c5f.js';
import '../../ui/ContextMenu.js';
import 'react-dom';
import '../../ui/SortByRow.js';
import '../../stringSet-a513039b.js';
import '../../ui/ReactionButton.js';
import '../../color-f6b2bdb7.js';
import 'react-dom/server';
import '../../ui/IconButton.js';
import '../../ui/Button.js';
import '../../ui/MentionUserLabel.js';
import 'dompurify';
import '../../ui/UserProfile.js';
import '../../sendbirdSelectors.js';
import '../../utils-b439eac3.js';
import '../../index-1ac4456b.js';
import '../../ui/Loader.js';
import '../../index-a1a19702.js';
import '../../index-2988897b.js';
import '../../ui/MessageItemMenu.js';
import '../../types-5cc94910.js';
import '../../ui/MessageItemReactionMenu.js';
import '../../ui/EmojiReactions.js';
import '../../ui/Tooltip.js';
import '../../ui/TooltipWrapper.js';
import '../../ui/ReactionBadge.js';
import '../../ui/AdminMessage.js';
import '../../ui/TextMessageItemBody.js';
import '../../ui/Word.js';
import '../../ui/LinkLabel.js';
import '../../ui/MentionLabel.js';
import '../../ui/FileMessageItemBody.js';
import '../../ui/TextButton.js';
import '../../MediaQueryContext-ceb727c7.js';
import '../../ui/ThumbnailMessageItemBody.js';
import '../../ui/OGMessageItemBody.js';
import '../../ui/UnknownMessageItemBody.js';
import '../../ui/QuoteMessage.js';
import '../../useLongPress-d942e028.js';
import '../../ui/BottomSheet.js';
import '../../index-10a05022.js';
import '../../ui/ThreadReplies.js';
import '../../ui/VoiceMessageItemBody.js';
import '../../ui/ProgressBar.js';
import '../../VoicePlayer/useVoicePlayer.js';
import '../../index-ac5a0725.js';
import '../../VoiceRecorder/context.js';
import '../../lame.all.js';
import '../../ui/PlaybackTime.js';
import '../../ui/Modal.js';

var useDidMountEffect = function (func, deps) {
  var _a = useState(false),
      didMount = _a[0],
      setDidmount = _a[1];

  useEffect(function () {
    if (didMount) {
      func();
    } else {
      setDidmount(true);
    }
  }, deps);
};

var Message = function (_a) {
  var _b, _c;

  var message = _a.message,
      hasSeparator = _a.hasSeparator,
      chainTop = _a.chainTop,
      chainBottom = _a.chainBottom,
      handleScroll = _a.handleScroll,
      renderCustomSeparator = _a.renderCustomSeparator,
      renderEditInput = _a.renderEditInput,
      renderMessage = _a.renderMessage,
      renderMessageContent = _a.renderMessageContent;
  var dateLocale = useLocalization().dateLocale;
  var globalStore = useSendbirdStateContext();

  var _d = globalStore === null || globalStore === void 0 ? void 0 : globalStore.config,
      userId = _d.userId,
      isOnline = _d.isOnline,
      isMentionEnabled = _d.isMentionEnabled,
      userMention = _d.userMention;

  var maxUserMentionCount = (userMention === null || userMention === void 0 ? void 0 : userMention.maxMentionCount) || MAX_USER_MENTION_COUNT;
  var maxUserSuggestionCount = (userMention === null || userMention === void 0 ? void 0 : userMention.maxSuggestionCount) || MAX_USER_SUGGESTION_COUNT;

  var _e = useChannelContext(),
      initialized = _e.initialized,
      currentGroupChannel = _e.currentGroupChannel,
      highLightedMessageId = _e.highLightedMessageId,
      setHighLightedMessageId = _e.setHighLightedMessageId,
      animatedMessageId = _e.animatedMessageId,
      setAnimatedMessageId = _e.setAnimatedMessageId,
      updateMessage = _e.updateMessage,
      scrollToMessage = _e.scrollToMessage,
      replyType = _e.replyType,
      threadReplySelectType = _e.threadReplySelectType,
      isReactionEnabled = _e.isReactionEnabled,
      toggleReaction = _e.toggleReaction,
      emojiContainer = _e.emojiContainer,
      nicknamesMap = _e.nicknamesMap,
      setQuoteMessage = _e.setQuoteMessage,
      resendMessage = _e.resendMessage,
      renderUserMentionItem = _e.renderUserMentionItem,
      onReplyInThread = _e.onReplyInThread,
      onQuoteMessageClick = _e.onQuoteMessageClick,
      onMessageAnimated = _e.onMessageAnimated,
      onMessageHighlighted = _e.onMessageHighlighted;

  var _f = useState(false),
      showEdit = _f[0],
      setShowEdit = _f[1];

  var _g = useState(false),
      showRemove = _g[0],
      setShowRemove = _g[1];

  var _h = useState(false),
      showFileViewer = _h[0],
      setShowFileViewer = _h[1];

  var _j = useState(false),
      isAnimated = _j[0],
      setIsAnimated = _j[1];

  var _k = useState(false),
      isHighlighted = _k[0],
      setIsHighlighted = _k[1];

  var _l = useState(''),
      mentionNickname = _l[0],
      setMentionNickname = _l[1];

  var _m = useState([]),
      mentionedUsers = _m[0],
      setMentionedUsers = _m[1];

  var _o = useState([]),
      mentionedUserIds = _o[0],
      setMentionedUserIds = _o[1];

  var _p = useState(null),
      messageInputEvent = _p[0],
      setMessageInputEvent = _p[1];

  var _q = useState(null),
      selectedUser = _q[0],
      setSelectedUser = _q[1];

  var _r = useState([]),
      mentionSuggestedUsers = _r[0],
      setMentionSuggestedUsers = _r[1];

  var _s = useState(true),
      ableMention = _s[0],
      setAbleMention = _s[1];

  var editMessageInputRef = useRef(null);
  var useMessageScrollRef = useRef(null);
  var displaySuggestedMentionList = isOnline && isMentionEnabled && mentionNickname.length > 0 && !isDisabledBecauseFrozen(currentGroupChannel) && !isDisabledBecauseMuted(currentGroupChannel);
  var disabled = !initialized || isDisabledBecauseFrozen(currentGroupChannel) || isDisabledBecauseMuted(currentGroupChannel) || !isOnline;
  useEffect(function () {
    if ((mentionedUsers === null || mentionedUsers === void 0 ? void 0 : mentionedUsers.length) >= maxUserMentionCount) {
      setAbleMention(false);
    } else {
      setAbleMention(true);
    }
  }, [mentionedUsers]);
  useEffect(function () {
    setMentionedUsers(mentionedUsers.filter(function (_a) {
      var userId = _a.userId;
      var i = mentionedUserIds.indexOf(userId);

      if (i < 0) {
        return false;
      } else {
        mentionedUserIds.splice(i, 1);
        return true;
      }
    }));
  }, [mentionedUserIds]);
  useDidMountEffect(function () {
    var _a;

    if (((_a = currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.lastMessage) === null || _a === void 0 ? void 0 : _a.messageId) === (message === null || message === void 0 ? void 0 : message.messageId)) {
      handleScroll === null || handleScroll === void 0 ? void 0 : handleScroll();
    }
  }, [showEdit, (_b = message === null || message === void 0 ? void 0 : message.reactions) === null || _b === void 0 ? void 0 : _b.length]);
  useLayoutEffect(function () {
    var animationTimeout = null;
    var messageHighlightedTimeout = null;

    if (highLightedMessageId === message.messageId && (useMessageScrollRef === null || useMessageScrollRef === void 0 ? void 0 : useMessageScrollRef.current)) {
      useMessageScrollRef.current.scrollIntoView({
        block: 'center',
        inline: 'center'
      });
      setIsAnimated(false);
      animationTimeout = setTimeout(function () {
        setIsHighlighted(true);
      }, 500);
      messageHighlightedTimeout = setTimeout(function () {
        setHighLightedMessageId(0);
        onMessageHighlighted === null || onMessageHighlighted === void 0 ? void 0 : onMessageHighlighted();
      }, 1600);
    } else {
      setIsHighlighted(false);
    }

    return function () {
      clearTimeout(animationTimeout);
      clearTimeout(messageHighlightedTimeout);
    };
  }, [highLightedMessageId, useMessageScrollRef.current, message.messageId]);
  useLayoutEffect(function () {
    var animationTimeout = null;
    var messageAnimatedTimeout = null;

    if (animatedMessageId === message.messageId && (useMessageScrollRef === null || useMessageScrollRef === void 0 ? void 0 : useMessageScrollRef.current)) {
      useMessageScrollRef.current.scrollIntoView({
        block: 'center',
        inline: 'center'
      });
      setIsHighlighted(false);
      animationTimeout = setTimeout(function () {
        setIsAnimated(true);
      }, 500);
      messageAnimatedTimeout = setTimeout(function () {
        setAnimatedMessageId(0);
        onMessageAnimated === null || onMessageAnimated === void 0 ? void 0 : onMessageAnimated();
      }, 1600);
    } else {
      setIsAnimated(false);
    }

    return function () {
      clearTimeout(animationTimeout);
      clearTimeout(messageAnimatedTimeout);
    };
  }, [animatedMessageId, useMessageScrollRef.current, message.messageId, onMessageAnimated]);
  var renderedMessage = useMemo(function () {
    return renderMessage === null || renderMessage === void 0 ? void 0 : renderMessage({
      message: message,
      chainTop: chainTop,
      chainBottom: chainBottom
    });
  }, [message, renderMessage]);
  var renderedCustomSeparator = useMemo(function () {
    if (renderCustomSeparator) {
      return renderCustomSeparator === null || renderCustomSeparator === void 0 ? void 0 : renderCustomSeparator({
        message: message
      });
    }

    return null;
  }, [message, renderCustomSeparator]);

  if (renderedMessage) {
    return /*#__PURE__*/React__default.createElement("div", {
      ref: useMessageScrollRef,
      className: getClassName(['sendbird-msg-hoc sendbird-msg--scroll-ref', isAnimated ? 'sendbird-msg-hoc__animated' : '', isHighlighted ? 'sendbird-msg-hoc__highlighted' : ''])
    }, // TODO: Add message instance as a function parameter
    hasSeparator && (renderedCustomSeparator || /*#__PURE__*/React__default.createElement(DateSeparator, null, /*#__PURE__*/React__default.createElement(Label, {
      type: LabelTypography.CAPTION_2,
      color: LabelColors.ONBACKGROUND_2
    }, format(message.createdAt, 'MMMM dd, yyyy', {
      locale: dateLocale
    })))), renderedMessage);
  }

  if (showEdit && ((_c = message === null || message === void 0 ? void 0 : message.isUserMessage) === null || _c === void 0 ? void 0 : _c.call(message))) {
    return (renderEditInput === null || renderEditInput === void 0 ? void 0 : renderEditInput()) || /*#__PURE__*/React__default.createElement(React__default.Fragment, null, displaySuggestedMentionList && /*#__PURE__*/React__default.createElement(SuggestedMentionList, {
      targetNickname: mentionNickname,
      inputEvent: messageInputEvent,
      renderUserMentionItem: renderUserMentionItem,
      onUserItemClick: function (user) {
        if (user) {
          setMentionedUsers(__spreadArray(__spreadArray([], mentionedUsers, true), [user], false));
        }

        setMentionNickname('');
        setSelectedUser(user);
        setMessageInputEvent(null);
      },
      onFocusItemChange: function () {
        setMessageInputEvent(null);
      },
      onFetchUsers: function (users) {
        setMentionSuggestedUsers(users);
      },
      ableAddMention: ableMention,
      maxMentionCount: maxUserMentionCount,
      maxSuggestionCount: maxUserSuggestionCount
    }), /*#__PURE__*/React__default.createElement(MessageInput, {
      isEdit: true,
      disabled: disabled,
      ref: editMessageInputRef,
      mentionSelectedUser: selectedUser,
      isMentionEnabled: isMentionEnabled,
      message: message,
      onStartTyping: function () {
        var _a;

        (_a = currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.startTyping) === null || _a === void 0 ? void 0 : _a.call(currentGroupChannel);
      },
      onUpdateMessage: function (_a) {
        var _b;

        var messageId = _a.messageId,
            message = _a.message,
            mentionTemplate = _a.mentionTemplate;
        updateMessage({
          messageId: messageId,
          message: message,
          mentionedUsers: mentionedUsers,
          mentionTemplate: mentionTemplate
        });
        setShowEdit(false);
        (_b = currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.endTyping) === null || _b === void 0 ? void 0 : _b.call(currentGroupChannel);
      },
      onCancelEdit: function () {
        var _a;

        setMentionNickname('');
        setMentionedUsers([]);
        setMentionedUserIds([]);
        setMentionSuggestedUsers([]);
        setShowEdit(false);
        (_a = currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.endTyping) === null || _a === void 0 ? void 0 : _a.call(currentGroupChannel);
      },
      onUserMentioned: function (user) {
        if ((selectedUser === null || selectedUser === void 0 ? void 0 : selectedUser.userId) === (user === null || user === void 0 ? void 0 : user.userId)) {
          setSelectedUser(null);
          setMentionNickname('');
        }
      },
      onMentionStringChange: function (mentionText) {
        setMentionNickname(mentionText);
      },
      onMentionedUserIdsUpdated: function (userIds) {
        setMentionedUserIds(userIds);
      },
      onKeyDown: function (e) {
        if (displaySuggestedMentionList && (mentionSuggestedUsers === null || mentionSuggestedUsers === void 0 ? void 0 : mentionSuggestedUsers.length) > 0 && (e.key === MessageInputKeys.Enter && ableMention || e.key === MessageInputKeys.ArrowUp || e.key === MessageInputKeys.ArrowDown)) {
          setMessageInputEvent(e);
          return true;
        }

        return false;
      }
    }));
  }

  return /*#__PURE__*/React__default.createElement("div", {
    className: getClassName(['sendbird-msg-hoc sendbird-msg--scroll-ref', isAnimated ? 'sendbird-msg-hoc__animated' : '', isHighlighted ? 'sendbird-msg-hoc__highlighted' : '']),
    style: {
      marginBottom: '2px'
    },
    ref: useMessageScrollRef
  }, hasSeparator && (renderedCustomSeparator || /*#__PURE__*/React__default.createElement(DateSeparator, null, /*#__PURE__*/React__default.createElement(Label, {
    type: LabelTypography.CAPTION_2,
    color: LabelColors.ONBACKGROUND_2
  }, format(message.createdAt, 'MMMM dd, yyyy', {
    locale: dateLocale
  })))), (renderMessageContent === null || renderMessageContent === void 0 ? void 0 : renderMessageContent()) || /*#__PURE__*/React__default.createElement(MessageContent, {
    className: "sendbird-message-hoc__message-content",
    userId: userId,
    scrollToMessage: scrollToMessage,
    channel: currentGroupChannel,
    message: message,
    disabled: !isOnline,
    chainTop: chainTop,
    chainBottom: chainBottom,
    isReactionEnabled: isReactionEnabled,
    replyType: replyType,
    threadReplySelectType: threadReplySelectType,
    nicknamesMap: nicknamesMap,
    emojiContainer: emojiContainer,
    showEdit: setShowEdit,
    showRemove: setShowRemove,
    showFileViewer: setShowFileViewer,
    resendMessage: resendMessage,
    toggleReaction: toggleReaction,
    setQuoteMessage: setQuoteMessage,
    onReplyInThread: onReplyInThread,
    onQuoteMessageClick: onQuoteMessageClick
  }), showRemove && /*#__PURE__*/React__default.createElement(RemoveMessage, {
    message: message,
    onCancel: function () {
      return setShowRemove(false);
    }
  }), showFileViewer && /*#__PURE__*/React__default.createElement(FileViewer, {
    message: message,
    onCancel: function () {
      return setShowFileViewer(false);
    }
  }));
};

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