"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _Search = require("../InputComponents/Search");
var _icons = require("../../assets/icons");
var _ChatRoomItem = _interopRequireDefault(require("../RoomComponents/ChatRoomItem"));
var _useChatSettingState = require("../../hooks/useChatSettingState");
var _Button = _interopRequireDefault(require("../styled/Button"));
var _HeaderRoomList = require("../Header/HeaderRoomList");
var _HeaderRoomListMenu = require("../Menu/HeaderRoomListMenu");
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 LONG_PRESS_THRESHOLD = 200;
const RoomList = ({
  chats,
  burgerMenu = false,
  onRoomClick
}) => {
  const {
    config
  } = (0, _useChatSettingState.useChatSettingState)();
  const [open, setOpen] = (0, _react.useState)(false);
  const [searchTerm, setSearchTerm] = (0, _react.useState)('');
  const [isLongPress, setIsLongPress] = (0, _react.useState)(false);
  const [isDrawerOpen, setDrawerOpen] = (0, _react.useState)(false);
  const pressTimer = (0, _react.useRef)(null);
  const containerRef = (0, _react.useRef)(null);
  const drawerAnimation = (0, _react.useRef)(new _reactNative.Animated.Value(0)).current;
  const overlayAnimation = (0, _react.useRef)(new _reactNative.Animated.Value(0)).current;
  const handlePressIn = (0, _react.useCallback)(() => {
    setIsLongPress(false);
    pressTimer.current = setTimeout(() => {
      setIsLongPress(true);
    }, LONG_PRESS_THRESHOLD);
  }, []);
  const handlePressOut = (0, _react.useCallback)(() => {
    if (pressTimer.current) {
      clearTimeout(pressTimer.current);
    }
  }, []);
  const performClick = (0, _react.useCallback)(chat => {
    if (!isLongPress) {
      onRoomClick?.(chat);
    }
    setOpen(false);
  }, [onRoomClick, isLongPress]);
  const handleSearchChange = (0, _react.useCallback)(text => {
    setSearchTerm(text);
  }, []);
  const getLastMessage = (0, _react.useCallback)(chat => chat?.messages?.[chat?.messages.length - 1], []);
  const filteredChats = (0, _react.useMemo)(() => {
    const lowerCaseSearchTerm = searchTerm.toLowerCase();
    const chatsMap = new Map();
    if (!chatsMap.has(lowerCaseSearchTerm)) {
      const result = chats.filter(chat => {
        const hay = `${chat?.title || ''} ${chat?.name || ''}`.toLowerCase();
        return hay.includes(lowerCaseSearchTerm);
      }).sort((a, b) => {
        if (getLastMessage(a)?.id && getLastMessage(b)?.id) {
          return Number(getLastMessage(b).id) - Number(getLastMessage(a).id);
        } else if (getLastMessage(a)?.id) {
          return -1;
        } else if (getLastMessage(b)?.id) {
          return 1;
        }
        return -1;
      });
      chatsMap.set(lowerCaseSearchTerm, result);
    }
    return chatsMap.get(lowerCaseSearchTerm) || [];
  }, [chats, searchTerm]);
  (0, _react.useEffect)(() => {
    if (burgerMenu) {
      // Since React Native doesn't have a native mouse event, we won't use `mousedown`
      // A listener for "blur" event (on touch outside) or "TouchableWithoutFeedback" may be used for mobile
    }
  }, [burgerMenu]);
  const toggleDrawer = () => {
    if (isDrawerOpen) {
      closeDrawer();
    } else {
      setDrawerOpen(true);
      _reactNative.Animated.parallel([_reactNative.Animated.timing(drawerAnimation, {
        toValue: 1,
        duration: 300,
        useNativeDriver: true
      }), _reactNative.Animated.timing(overlayAnimation, {
        toValue: 1,
        duration: 300,
        useNativeDriver: true
      })]).start();
    }
  };
  const closeDrawer = () => {
    _reactNative.Animated.parallel([_reactNative.Animated.timing(drawerAnimation, {
      toValue: 0,
      duration: 300,
      useNativeDriver: true
    }), _reactNative.Animated.timing(overlayAnimation, {
      toValue: 0,
      duration: 300,
      useNativeDriver: true
    })]).start(() => {
      setDrawerOpen(false);
    });
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [burgerMenu && !open && /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
      style: {
        padding: 8,
        borderRadius: 16,
        backgroundColor: 'transparent'
      },
      color: "black",
      unstyled: true,
      EndIcon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.BurgerMenuIcon, {
        color: config?.colors?.primary
      }),
      onPress: () => setOpen(!open)
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
      ref: containerRef,
      style: [styles.container, config?.roomListStyles],
      children: (open || !burgerMenu) && /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
          style: styles.scrollContainer,
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_HeaderRoomList.HeaderRoomList, {
            setDrawerOpen: toggleDrawer
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.FlatList, {
            data: filteredChats,
            keyExtractor: item => item.jid,
            renderItem: ({
              item
            }) => /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Pressable
            // Stable testID so e2e drivers can target a room
            // row by its jid local-part (e.g. Main chat under
            // app id `..._...759` → testID `room-...759`).
            , {
              testID: `room-${(item.jid || '').split('@')[0]}`,
              accessibilityLabel: `room-${item.title || item.name}`,
              onPress: () => performClick(item),
              onPressIn: handlePressIn,
              onPressOut: handlePressOut,
              children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_ChatRoomItem.default, {
                chat: item,
                config: config
              })
            }),
            ListHeaderComponent: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Search.SearchInput, {
              icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.SearchIcon, {
                height: 20
              }),
              value: searchTerm,
              onChangeText: handleSearchChange,
              placeholder: "Search..."
            }),
            style: styles.chatList
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_HeaderRoomListMenu.HeaderRoomListMenu, {
            closeDrawer: closeDrawer,
            drawerAnimation: drawerAnimation,
            overlayAnimation: overlayAnimation,
            isDrawerOpen: isDrawerOpen
          })]
        })
      })
    })]
  });
};
const styles = _reactNative.StyleSheet.create({
  burgerButton: {
    fontSize: 24,
    padding: 10,
    color: '#333'
  },
  container: {
    width: '100%',
    height: '100%',
    flex: 1,
    backgroundColor: '#fff'
  },
  scrollContainer: {
    flexGrow: 1
  },
  headerContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    justifyContent: 'space-between'
  },
  chatList: {
    flex: 1,
    paddingTop: 8,
    paddingHorizontal: 16,
    backgroundColor: '#FAFAFA'
  }
});
var _default = exports.default = RoomList;
//# sourceMappingURL=RoomList.js.map