"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _Composing = _interopRequireDefault(require("../styled/StyledInputComponents/Composing"));
var _TreadLabel = _interopRequireDefault(require("../styled/TreadLabel"));
var _MessageContainer = require("./MessageContainer");
var _useRoomState = require("../../hooks/useRoomState");
var _Loader = _interopRequireDefault(require("../styled/Loader"));
var _icons = require("../../assets/icons");
var _CustomTypingIndicator = _interopRequireDefault(require("../styled/StyledInputComponents/CustomTypingIndicator"));
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
/** @format */

const MessageList = ({
  CustomMessage,
  CustomDaySeparator,
  CustomNewMessageLabel,
  user,
  loadMoreMessages,
  roomJID,
  config,
  loading,
  isReply,
  activeMessage
}) => {
  const {
    composing,
    messages,
    composingList
  } = (0, _useRoomState.useRoomState)(roomJID).room;
  const [isUserAtBottom, setIsUserAtBottom] = (0, _react.useState)(true);
  const [showNewMessageIndicator, setShowNewMessageIndicator] = (0, _react.useState)(false);
  const [isContentOffset, setIsContentOffset] = (0, _react.useState)(false);
  const [isLoadingMore, setIsLoadingMore] = (0, _react.useState)(false);
  const [isScrollBlocked, setIsScrollBlocked] = (0, _react.useState)(false);
  const [hasUserScrolled, setHasUserScrolled] = (0, _react.useState)(false);
  const flatListRef = (0, _react.useRef)(null);
  const addReplyMessages = (0, _react.useMemo)(() => {
    return messages.map(message => {
      const newMessage = {
        ...message,
        reply: messages.filter(mess => !!mess.mainMessage && JSON.parse(mess.mainMessage).id === message.id && !mess.isDeleted)
      };
      return newMessage;
    });
  }, [messages]);
  const memoizedMessages = (0, _react.useMemo)(() => {
    const nonDeletedMessages = addReplyMessages.filter(item => !item.isDeleted);
    let filtered;
    if (isReply) {
      filtered = nonDeletedMessages.filter(item => item.roomJid === roomJID && item.isReply && item.isReply === 'true' && item.mainMessage && JSON.parse(item.mainMessage).id === activeMessage?.id);
    } else {
      filtered = nonDeletedMessages.filter(item => item.showInChannel === 'true' || (!item.isReply || item.isReply === 'false') && !item.mainMessage);
    }

    // Explicit chronological sort by stanza-id timestamp (microseconds-
    // since-epoch encoded in the id). Without this, MAM history that
    // streams in across multiple ticks visibly reorders itself:
    // insertMessageWithDelimiter inserts new arrivals at the slot
    // matching their date.toString() comparison, but redux state can
    // emit intermediate snapshots between dispatches, so the FlatList
    // briefly renders messages out-of-order until the final batch
    // settles. Sorting here makes each render a stable, ordered view —
    // even mid-stream — so the user sees them appear from oldest to
    // newest with no swap animation.
    const sorted = filtered.slice().sort((a, b) => {
      const aNum = new Date(a?.date).getTime() || 0;
      const bNum = new Date(b?.date).getTime() || 0;
      return aNum - bNum;
    });
    return sorted;
  }, [addReplyMessages, isReply, roomJID, activeMessage]);
  const handleLoadMore = (0, _react.useCallback)(async () => {
    if (loading || isLoadingMore || !memoizedMessages.length || isScrollBlocked) {
      return;
    }
    const oldestMessage = memoizedMessages[0];
    if (!oldestMessage || !oldestMessage.id) {
      return;
    }
    setIsLoadingMore(true);
    setIsScrollBlocked(true);
    try {
      await loadMoreMessages(oldestMessage.roomJid || roomJID, 15, Number(oldestMessage.id));
    } catch (error) {
      console.error(error);
    } finally {
      setTimeout(() => {
        setIsLoadingMore(false);
        setIsScrollBlocked(false);
      }, 500);
    }
  }, [memoizedMessages, loadMoreMessages, loading, isLoadingMore, isScrollBlocked, roomJID]);
  const dataMessages = (0, _react.useMemo)(() => {
    return memoizedMessages.slice().reverse();
  }, [memoizedMessages]);
  const renderMessage = (0, _react.useCallback)(({
    item,
    index
  }) => {
    const messageDate = new Date(item.date).toDateString();
    let showDateLabel = false;
    const nextMessage = index < dataMessages.length - 1 ? dataMessages[index + 1] : null;
    const nextMessageDate = nextMessage ? new Date(nextMessage.date).toDateString() : null;
    if (!nextMessage || messageDate !== nextMessageDate) {
      showDateLabel = true;
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_MessageContainer.MessageContainer, {
      CustomMessage: CustomMessage,
      CustomDaySeparator: CustomDaySeparator,
      CustomNewMessageLabel: CustomNewMessageLabel,
      message: item,
      activeMessage: activeMessage,
      config: config,
      walletAddress: user.xmppUsername || user.walletAddress,
      isReply: isReply,
      showDateLabel: showDateLabel
    });
  }, [activeMessage, config, user.xmppUsername, user.walletAddress, isReply, memoizedMessages.length]);
  const scrollToBottom = (0, _react.useCallback)(() => {
    if (flatListRef.current) {
      flatListRef.current.scrollToOffset({
        offset: 0,
        animated: true
      });
    }
  }, [flatListRef]);
  const handleContentSizeChange = (0, _react.useCallback)(() => {
    if (isContentOffset) {
      scrollToBottom();
      setIsContentOffset(false);
    }
    if (!isLoadingMore && flatListRef.current && isUserAtBottom) {
      scrollToBottom();
    } else if (!isLoadingMore && hasUserScrolled) {
      setShowNewMessageIndicator(true);
    }
  }, [isUserAtBottom, scrollToBottom, isLoadingMore, hasUserScrolled]);
  const handleScroll = (0, _react.useCallback)(event => {
    const contentOffset = event.nativeEvent.contentOffset.y;
    _reactNative.Keyboard.dismiss();
    if (contentOffset > 150 && !hasUserScrolled) {
      setHasUserScrolled(true);
    }
    if (contentOffset < 150) {
      setIsContentOffset(true);
      setShowNewMessageIndicator(false);
      setIsUserAtBottom(true);
    } else {
      setIsContentOffset(false);
      if (hasUserScrolled) {
        setShowNewMessageIndicator(true);
      }
      setIsUserAtBottom(false);
    }
  }, [hasUserScrolled]);
  const handleLayout = () => {
    setIsContentOffset(true);
    setIsUserAtBottom(true);
  };
  const handleNewMessageIndicatorPress = () => {
    setShowNewMessageIndicator(false);
    setIsUserAtBottom(true);
    scrollToBottom();
  };
  (0, _react.useEffect)(() => {
    setHasUserScrolled(false);
    setShowNewMessageIndicator(false);
    setIsUserAtBottom(true);
  }, [roomJID]);
  const BackgroundImage = (0, _react.useMemo)(() => {
    const image = config?.backgroundChat?.image;
    if (image) {
      if (typeof image === 'function') {
        const SvgComponent = image;
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(SvgComponent, {
          width: "100%"
        });
      } else {
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Image, {
          source: image
        });
      }
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {});
  }, [config?.backgroundChat?.image]);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
    style: [styles.container, {
      backgroundColor: config?.backgroundChat?.color || '#F3F6FC'
    }],
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
      style: styles.backgroundImageContainer,
      children: BackgroundImage
    }), activeMessage && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
      children: [CustomMessage && /*#__PURE__*/(0, _jsxRuntime.jsx)(CustomMessage, {
        message: activeMessage,
        isUser: activeMessage.user.id === user.walletAddress,
        isReply: isReply
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_TreadLabel.default, {
        reply: memoizedMessages.length,
        colors: config?.colors
      })]
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.FlatList, {
      ref: flatListRef,
      data: memoizedMessages.slice().reverse(),
      renderItem: renderMessage,
      keyExtractor: item => item.id.toString(),
      onEndReached: handleLoadMore,
      onScroll: handleScroll,
      onContentSizeChange: handleContentSizeChange,
      onEndReachedThreshold: 0.1,
      scrollEventThrottle: 16,
      onLayout: handleLayout,
      inverted: true,
      contentContainerStyle: styles.flatListContent,
      ListFooterComponent: loading && memoizedMessages.length > 15 ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_Loader.default, {
        color: config?.colors?.primary
      }) : null
    }), showNewMessageIndicator && /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.TouchableOpacity, {
      style: [styles.newMessageIndicator, {
        backgroundColor: config?.colors?.secondary
      }],
      onPress: handleNewMessageIndicatorPress,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.ArowDownIcon, {})
    }), config?.customTypingIndicator?.enabled && composing && /*#__PURE__*/(0, _jsxRuntime.jsx)(_CustomTypingIndicator.default, {
      usersTyping: composingList || ['User'],
      text: config.customTypingIndicator.text,
      position: config.customTypingIndicator.position || 'bottom',
      styles: config.customTypingIndicator.styles,
      customComponent: config.customTypingIndicator.customComponent,
      isVisible: composing
    }), !config?.customTypingIndicator?.enabled && config?.disableHeader && composing && /*#__PURE__*/(0, _jsxRuntime.jsx)(_Composing.default, {
      usersTyping: composingList || ['User']
    })]
  });
};
var _default = exports.default = MessageList;
const styles = _reactNative.StyleSheet.create({
  container: {
    flex: 1,
    width: '100%'
  },
  flatListContent: {
    paddingHorizontal: 10,
    paddingBottom: 10
  },
  messageList: {
    paddingHorizontal: 10,
    flexGrow: 1,
    backgroundColor: '#434343'
  },
  backgroundImageContainer: {
    width: '100%',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: -1
  },
  image: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: '100%',
    height: '100%'
  },
  newMessageIndicator: {
    position: 'absolute',
    width: 40,
    height: 40,
    bottom: 20,
    right: 20,
    backgroundColor: '#007AFF',
    padding: 10,
    borderRadius: 20
  },
  newMessageText: {
    color: '#fff',
    fontWeight: 'bold'
  }
});
//# sourceMappingURL=MessageList.js.map