"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _reactNative = require("react-native");
var _react = require("react");
var _enums = require("../../../enums");
var _hooks = require("../../../hooks");
var _styles = require("./styles");
var _BackButtonIconElement = _interopRequireDefault(require("../../../elements/BackButtonIconElement/BackButtonIconElement"));
var _native = require("@react-navigation/native");
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _Content = _interopRequireDefault(require("../components/Content/Content"));
var _AmityPostContentComponentStyle = require("../../../enums/AmityPostContentComponentStyle");
var _PostComment = _interopRequireDefault(require("../../comment/components/PostComment"));
var _xml = require("../../../../core/assets/icons/xml");
var _reactNativeSvg = require("react-native-svg");
var _netinfo = _interopRequireDefault(require("@react-native-community/netinfo"));
var _toastSlice = require("../../../../core/stores/slices/toastSlice");
var _MyAvatar = _interopRequireDefault(require("../../../components/MyAvatar/MyAvatar"));
var _constants = require("../../../../core/constants");
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
var _ErrorComponent = _interopRequireDefault(require("../../../components/ErrorComponent/ErrorComponent"));
var _color = require("../../../../core/utils/color");
var _native2 = _interopRequireWildcard(require("react-content-loader/native"));
var _PostMenu = require("../../../components/PostMenu");
var _useMention = _interopRequireDefault(require("../../../hooks/useMention"));
var _reactNativeControlledMentions = require("react-native-controlled-mentions");
var _comment = require("../../../../core/legacy/comment");
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); }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
const AmityPostDetailPage = ({
  postId,
  isFromComponent,
  showEndPopup,
  category,
  isDeleted
}) => {
  var _postData$targetCommu;
  const pageId = _enums.PageID.post_detail_page;
  const componentId = _enums.ComponentID.WildCardComponent;
  const disabledInteraction = false;
  const navigation = (0, _native.useNavigation)();
  const {
    isExcluded,
    themeStyles,
    accessibilityId
  } = (0, _hooks.useAmityPage)({
    pageId
  });
  const styles = (0, _styles.useStyles)(themeStyles);
  const {
    showToast,
    showCommentErrorToast
  } = (0, _toastSlice.useToast)();
  const [postData, setPostData] = (0, _react.useState)(null);
  const [loading, setLoading] = (0, _react.useState)(true);
  const [replyUserName, setReplyUserName] = (0, _react.useState)('');
  const [replyCommentId, setReplyCommentId] = (0, _react.useState)('');
  const [inputMessage, setInputMessage] = (0, _react.useState)('');
  const [mentionNames, setMentionNames] = (0, _react.useState)([]);
  const [mentionsPosition, setMentionsPosition] = (0, _react.useState)([]);
  const [inputBarHeight, setInputBarHeight] = (0, _react.useState)(0);
  const [showLivestreamEndPopup, setShowLivestreamEndPopup] = (0, _react.useState)(showEndPopup || false);

  // Restrict @mention list to community members when the post belongs to a
  // private community. postData.targetCommunity is populated after the post loads.
  const privateCommunityId = (postData === null || postData === void 0 ? void 0 : postData.targetType) === 'community' && !(postData !== null && postData !== void 0 && (_postData$targetCommu = postData.targetCommunity) !== null && _postData$targetCommu !== void 0 && _postData$targetCommu.isPublic) ? postData === null || postData === void 0 ? void 0 : postData.targetId : undefined;
  const {
    renderInput,
    renderSuggestions
  } = (0, _useMention.default)({
    value: inputMessage,
    onChange: setInputMessage,
    communityId: privateCommunityId,
    setMentionUsers: user => {
      setMentionNames(prev => {
        if (prev.length >= _constants.MAX_MENTION_USERS) {
          _reactNative.Alert.alert('Too many users mentioned', 'You can only mention up to 30 users per post.', [{
            text: 'OK'
          }]);
          return prev;
        }
        return [...prev, user];
      });
    },
    setMentionPosition: position => {
      setMentionsPosition(prev => [...prev, position]);
    }
  });
  (0, _react.useEffect)(() => {
    const unsubscribe = _netinfo.default.addEventListener(state => {
      if (!state.isConnected) {
        showToast({
          type: 'failed',
          message: 'No internet connection.',
          duration: 3000,
          bottomPosition: 96
        });
      }
    });
    return () => unsubscribe();
  }, [showToast]);
  (0, _react.useLayoutEffect)(() => {
    if (!postId) return () => {};
    setLoading(true);
    let unsub;
    let hasSubscribed = false;
    const postUnsub = _tsSdkReactNative.PostRepository.getPost(postId, async ({
      error,
      loading: postLoading,
      data
    }) => {
      if (!error && !postLoading) {
        if (!hasSubscribed) {
          unsub = (0, _tsSdkReactNative.subscribeTopic)((0, _tsSdkReactNative.getPostTopic)(data, _tsSdkReactNative.SubscriptionLevels.COMMENT));
          hasSubscribed = true;
        }
        setPostData(data);
      }
      setLoading(postLoading);
    });
    return () => {
      postUnsub();
      unsub && unsub();
    };
  }, [postId]);
  (0, _react.useEffect)(() => {
    // Parse active mention user IDs directly from the controlled-mentions
    // value format: {@}[DisplayName](userId)
    // Using displayName.includes() is unreliable — the same name can appear as
    // plain text, and deletions may not remove the entry correctly.
    const mentionTokenRegex = /\{@\}\[([^\]]*)\]\(([^)]*)\)/g;
    const activeUserIds = new Set();
    let match;
    while ((match = mentionTokenRegex.exec(inputMessage)) !== null) {
      activeUserIds.add(match[2]); // userId is capture group 2
    }
    setMentionNames(prev => prev.filter(item => activeUserIds.has(item.id)));
    setMentionsPosition(prev => prev.filter(item => activeUserIds.has(item.userId)));
  }, [inputMessage]);
  const onPressBack = (0, _react.useCallback)(() => {
    const routes = navigation.getState().routes;
    if (isFromComponent && routes.length === 1) {
      navigation.navigate('AmitySocialHomePage');
      navigation.dispatch(_native.CommonActions.reset({
        index: 0,
        routes: [{
          name: 'AmitySocialHomePage'
        }]
      }));
    } else {
      var _routes;
      if (((_routes = routes[routes.length - 2]) === null || _routes === void 0 ? void 0 : _routes.name) === 'CreateLivestream') return navigation.pop(3);
      navigation.goBack();
    }
    // if the previous screen is CreateLivestream, skip createLivestream and selectTarget screen
  }, [navigation, isFromComponent]);
  const onCloseReply = () => {
    setReplyUserName('');
    setReplyCommentId('');
  };
  const handleSend = async () => {
    if (inputMessage.trim() === '') {
      return;
    }
    const uniqueMentionIds = [...new Set(mentionNames.map(item => item.id))];
    if (uniqueMentionIds.length > _constants.MAX_MENTION_USERS) {
      _reactNative.Alert.alert('Too many users mentioned', 'You can only mention up to 30 users per post.', [{
        text: 'OK'
      }]);
      return;
    }
    const comment = (0, _reactNativeControlledMentions.replaceTriggerValues)(inputMessage, ({
      name
    }) => `@${name}`);
    if (replyCommentId.length > 0) {
      try {
        await (0, _comment.createReplyComment)(comment, postId, replyCommentId, uniqueMentionIds, mentionsPosition, 'post');
      } catch (error) {
        showCommentErrorToast(error);
        return;
      }
    } else {
      try {
        await (0, _comment.createComment)(comment, postId, uniqueMentionIds, mentionsPosition, 'post');
      } catch (error) {
        showCommentErrorToast(error);
        return;
      }
    }
    setInputMessage('');
    _reactNative.Keyboard.dismiss();
    setMentionNames([]);
    setMentionsPosition([]);
    onCloseReply();
  };
  const renderFooterComponent = () => {
    return /*#__PURE__*/React.createElement(_reactNative.View, {
      style: styles.commentListFooter
    }, renderSuggestions({
      type: 'comment',
      bottom: inputBarHeight
    }), /*#__PURE__*/React.createElement(_reactNative.View, {
      onLayout: e => setInputBarHeight(e.nativeEvent.layout.height)
    }, replyUserName.length > 0 && /*#__PURE__*/React.createElement(_reactNative.View, {
      style: styles.replyLabelWrap
    }, /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: styles.replyLabel
    }, "Replying to", ' ', /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: styles.userNameLabel
    }, replyUserName)), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, null, /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
      onPress: onCloseReply
    }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
      style: styles.closeIcon,
      xml: (0, _xml.closeIcon)(themeStyles.colors.baseShade2),
      width: 20
    })))), !disabledInteraction && /*#__PURE__*/React.createElement(_reactNative.View, {
      style: styles.InputWrap
    }, /*#__PURE__*/React.createElement(_MyAvatar.default, {
      style: styles.myAvatar
    }), /*#__PURE__*/React.createElement(_reactNative.View, {
      style: styles.inputContainer
    }, renderInput({
      multiline: true,
      scrollEnabled: true,
      placeholder: 'Say something nice...',
      placeholderTextColor: themeStyles.colors.baseShade3,
      style: [styles.input, {
        lineHeight: 20
      }]
    })), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
      disabled: inputMessage.length > 0 ? false : true,
      onPress: handleSend,
      style: styles.postBtn
    }, /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: inputMessage.length > 0 ? styles.postBtnText : styles.postDisabledBtn
    }, "Post")))));
  };
  const renderLivestreamEndPopup = () => {
    _reactNative.Alert.alert('Live stream ended', 'Your live stream has been automatically terminated since you reached 4-hour limit.', [{
      text: 'OK',
      onPress: () => {
        setShowLivestreamEndPopup(false);
      }
    }]);
  };
  (0, _react.useEffect)(() => {
    showLivestreamEndPopup && renderLivestreamEndPopup();
  }, [showLivestreamEndPopup]);
  if (isExcluded) return null;
  if (isDeleted || postData !== null && postData !== void 0 && postData.isDeleted) {
    return /*#__PURE__*/React.createElement(_ErrorComponent.default, {
      themeStyle: themeStyles,
      onPress: onPressBack,
      title: "Something went wrong",
      description: "The content you're looking for is unavailable."
    });
  }
  return /*#__PURE__*/React.createElement(_reactNative.KeyboardAvoidingView, {
    style: styles.container,
    keyboardVerticalOffset: _reactNative.Platform.OS === 'ios' ? 0 : 0,
    behavior: _reactNative.Platform.OS === 'ios' ? 'padding' : 'height'
  }, /*#__PURE__*/React.createElement(_reactNativeSafeAreaContext.SafeAreaView, {
    edges: ['top'],
    testID: accessibilityId,
    style: styles.container
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.header
  }, /*#__PURE__*/React.createElement(_reactNative.Pressable, {
    onPress: onPressBack
  }, /*#__PURE__*/React.createElement(_BackButtonIconElement.default, {
    pageID: pageId,
    componentID: componentId,
    style: styles.headerIcon
  })), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.headerTitle
  }, "Post"), /*#__PURE__*/React.createElement(_PostMenu.PostMenu, {
    post: postData,
    pageId: pageId,
    componentId: componentId
  })), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: [styles.scrollContainer]
  }, loading ? /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.skeletonContainer
  }, /*#__PURE__*/React.createElement(_native2.default, _extends({
    speed: 1
  }, (0, _color.getSkeletonBackgrounColor)(themeStyles)), /*#__PURE__*/React.createElement(_native2.Circle, {
    cx: "16",
    cy: "16",
    r: "16"
  }), /*#__PURE__*/React.createElement(_native2.Rect, {
    x: "40",
    y: "4",
    width: "180",
    height: "8",
    rx: "3"
  }), /*#__PURE__*/React.createElement(_native2.Rect, {
    x: "40",
    y: "20",
    width: "64",
    height: "8",
    rx: "3"
  }), /*#__PURE__*/React.createElement(_native2.Rect, {
    x: "0",
    y: "56",
    width: "240",
    height: "8",
    rx: "3"
  }), /*#__PURE__*/React.createElement(_native2.Rect, {
    x: "0",
    y: "76",
    width: "180",
    height: "8",
    rx: "3"
  }), /*#__PURE__*/React.createElement(_native2.Rect, {
    x: "0",
    y: "96",
    width: "300",
    height: "8",
    rx: "3"
  }))) : /*#__PURE__*/React.createElement(_PostComment.default, {
    setReplyUserName: setReplyUserName,
    setReplyCommentId: setReplyCommentId,
    postId: postId,
    communityId: (postData === null || postData === void 0 ? void 0 : postData.targetType) === 'community' && (postData === null || postData === void 0 ? void 0 : postData.targetId),
    postType: "post",
    disabledInteraction: false,
    ListHeaderComponent: postData && /*#__PURE__*/React.createElement(_Content.default, {
      post: postData,
      showedAllOptions: true,
      category: category,
      AmityPostContentComponentStyle: _AmityPostContentComponentStyle.AmityPostContentComponentStyleEnum.detail,
      pageId: pageId
    })
  })), renderFooterComponent()));
};
var _default = exports.default = /*#__PURE__*/(0, _react.memo)(AmityPostDetailPage);
//# sourceMappingURL=index.js.map