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); }
import { Pressable, View, Alert, Keyboard, Text, TouchableOpacity, KeyboardAvoidingView, Platform } from 'react-native';
import { memo, useCallback, useEffect, useState, useLayoutEffect } from 'react';
import { ComponentID, PageID } from '../../../enums';
import { useAmityPage } from '../../../hooks';
import { useStyles } from './styles';
import BackButtonIconElement from '../../../elements/BackButtonIconElement/BackButtonIconElement';
import { CommonActions, useNavigation } from '@react-navigation/native';
import { PostRepository, SubscriptionLevels, getPostTopic, subscribeTopic } from '@amityco/ts-sdk-react-native';
import AmityPostContentComponent from '../components/Content/Content';
import { AmityPostContentComponentStyleEnum } from '../../../enums/AmityPostContentComponentStyle';
import AmityPostCommentComponent from '../../comment/components/PostComment';
import { closeIcon } from '../../../../core/assets/icons/xml';
import { SvgXml } from 'react-native-svg';
import NetInfo from '@react-native-community/netinfo';
import { useToast } from '../../../../core/stores/slices/toastSlice';
import MyAvatar from '../../../components/MyAvatar/MyAvatar';
import { MAX_MENTION_USERS } from '../../../../core/constants';
import { SafeAreaView } from 'react-native-safe-area-context';
import ErrorComponent from '../../../components/ErrorComponent/ErrorComponent';
import { getSkeletonBackgrounColor } from '../../../../core/utils/color';
import ContentLoader, { Circle, Rect } from 'react-content-loader/native';
import { PostMenu } from '../../../components/PostMenu';
import useMention from '../../../hooks/useMention';
import { replaceTriggerValues } from 'react-native-controlled-mentions';
import { createComment, createReplyComment } from '../../../../core/legacy/comment';
const AmityPostDetailPage = ({
  postId,
  isFromComponent,
  showEndPopup,
  category,
  isDeleted
}) => {
  var _postData$targetCommu;
  const pageId = PageID.post_detail_page;
  const componentId = ComponentID.WildCardComponent;
  const disabledInteraction = false;
  const navigation = useNavigation();
  const {
    isExcluded,
    themeStyles,
    accessibilityId
  } = useAmityPage({
    pageId
  });
  const styles = useStyles(themeStyles);
  const {
    showToast,
    showCommentErrorToast
  } = useToast();
  const [postData, setPostData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [replyUserName, setReplyUserName] = useState('');
  const [replyCommentId, setReplyCommentId] = useState('');
  const [inputMessage, setInputMessage] = useState('');
  const [mentionNames, setMentionNames] = useState([]);
  const [mentionsPosition, setMentionsPosition] = useState([]);
  const [inputBarHeight, setInputBarHeight] = useState(0);
  const [showLivestreamEndPopup, setShowLivestreamEndPopup] = 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
  } = useMention({
    value: inputMessage,
    onChange: setInputMessage,
    communityId: privateCommunityId,
    setMentionUsers: user => {
      setMentionNames(prev => {
        if (prev.length >= MAX_MENTION_USERS) {
          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]);
    }
  });
  useEffect(() => {
    const unsubscribe = NetInfo.addEventListener(state => {
      if (!state.isConnected) {
        showToast({
          type: 'failed',
          message: 'No internet connection.',
          duration: 3000,
          bottomPosition: 96
        });
      }
    });
    return () => unsubscribe();
  }, [showToast]);
  useLayoutEffect(() => {
    if (!postId) return () => {};
    setLoading(true);
    let unsub;
    let hasSubscribed = false;
    const postUnsub = PostRepository.getPost(postId, async ({
      error,
      loading: postLoading,
      data
    }) => {
      if (!error && !postLoading) {
        if (!hasSubscribed) {
          unsub = subscribeTopic(getPostTopic(data, SubscriptionLevels.COMMENT));
          hasSubscribed = true;
        }
        setPostData(data);
      }
      setLoading(postLoading);
    });
    return () => {
      postUnsub();
      unsub && unsub();
    };
  }, [postId]);
  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 = useCallback(() => {
    const routes = navigation.getState().routes;
    if (isFromComponent && routes.length === 1) {
      navigation.navigate('AmitySocialHomePage');
      navigation.dispatch(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 > MAX_MENTION_USERS) {
      Alert.alert('Too many users mentioned', 'You can only mention up to 30 users per post.', [{
        text: 'OK'
      }]);
      return;
    }
    const comment = replaceTriggerValues(inputMessage, ({
      name
    }) => `@${name}`);
    if (replyCommentId.length > 0) {
      try {
        await createReplyComment(comment, postId, replyCommentId, uniqueMentionIds, mentionsPosition, 'post');
      } catch (error) {
        showCommentErrorToast(error);
        return;
      }
    } else {
      try {
        await createComment(comment, postId, uniqueMentionIds, mentionsPosition, 'post');
      } catch (error) {
        showCommentErrorToast(error);
        return;
      }
    }
    setInputMessage('');
    Keyboard.dismiss();
    setMentionNames([]);
    setMentionsPosition([]);
    onCloseReply();
  };
  const renderFooterComponent = () => {
    return /*#__PURE__*/React.createElement(View, {
      style: styles.commentListFooter
    }, renderSuggestions({
      type: 'comment',
      bottom: inputBarHeight
    }), /*#__PURE__*/React.createElement(View, {
      onLayout: e => setInputBarHeight(e.nativeEvent.layout.height)
    }, replyUserName.length > 0 && /*#__PURE__*/React.createElement(View, {
      style: styles.replyLabelWrap
    }, /*#__PURE__*/React.createElement(Text, {
      style: styles.replyLabel
    }, "Replying to", ' ', /*#__PURE__*/React.createElement(Text, {
      style: styles.userNameLabel
    }, replyUserName)), /*#__PURE__*/React.createElement(TouchableOpacity, null, /*#__PURE__*/React.createElement(TouchableOpacity, {
      onPress: onCloseReply
    }, /*#__PURE__*/React.createElement(SvgXml, {
      style: styles.closeIcon,
      xml: closeIcon(themeStyles.colors.baseShade2),
      width: 20
    })))), !disabledInteraction && /*#__PURE__*/React.createElement(View, {
      style: styles.InputWrap
    }, /*#__PURE__*/React.createElement(MyAvatar, {
      style: styles.myAvatar
    }), /*#__PURE__*/React.createElement(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(TouchableOpacity, {
      disabled: inputMessage.length > 0 ? false : true,
      onPress: handleSend,
      style: styles.postBtn
    }, /*#__PURE__*/React.createElement(Text, {
      style: inputMessage.length > 0 ? styles.postBtnText : styles.postDisabledBtn
    }, "Post")))));
  };
  const renderLivestreamEndPopup = () => {
    Alert.alert('Live stream ended', 'Your live stream has been automatically terminated since you reached 4-hour limit.', [{
      text: 'OK',
      onPress: () => {
        setShowLivestreamEndPopup(false);
      }
    }]);
  };
  useEffect(() => {
    showLivestreamEndPopup && renderLivestreamEndPopup();
  }, [showLivestreamEndPopup]);
  if (isExcluded) return null;
  if (isDeleted || postData !== null && postData !== void 0 && postData.isDeleted) {
    return /*#__PURE__*/React.createElement(ErrorComponent, {
      themeStyle: themeStyles,
      onPress: onPressBack,
      title: "Something went wrong",
      description: "The content you're looking for is unavailable."
    });
  }
  return /*#__PURE__*/React.createElement(KeyboardAvoidingView, {
    style: styles.container,
    keyboardVerticalOffset: Platform.OS === 'ios' ? 0 : 0,
    behavior: Platform.OS === 'ios' ? 'padding' : 'height'
  }, /*#__PURE__*/React.createElement(SafeAreaView, {
    edges: ['top'],
    testID: accessibilityId,
    style: styles.container
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.header
  }, /*#__PURE__*/React.createElement(Pressable, {
    onPress: onPressBack
  }, /*#__PURE__*/React.createElement(BackButtonIconElement, {
    pageID: pageId,
    componentID: componentId,
    style: styles.headerIcon
  })), /*#__PURE__*/React.createElement(Text, {
    style: styles.headerTitle
  }, "Post"), /*#__PURE__*/React.createElement(PostMenu, {
    post: postData,
    pageId: pageId,
    componentId: componentId
  })), /*#__PURE__*/React.createElement(View, {
    style: [styles.scrollContainer]
  }, loading ? /*#__PURE__*/React.createElement(View, {
    style: styles.skeletonContainer
  }, /*#__PURE__*/React.createElement(ContentLoader, _extends({
    speed: 1
  }, getSkeletonBackgrounColor(themeStyles)), /*#__PURE__*/React.createElement(Circle, {
    cx: "16",
    cy: "16",
    r: "16"
  }), /*#__PURE__*/React.createElement(Rect, {
    x: "40",
    y: "4",
    width: "180",
    height: "8",
    rx: "3"
  }), /*#__PURE__*/React.createElement(Rect, {
    x: "40",
    y: "20",
    width: "64",
    height: "8",
    rx: "3"
  }), /*#__PURE__*/React.createElement(Rect, {
    x: "0",
    y: "56",
    width: "240",
    height: "8",
    rx: "3"
  }), /*#__PURE__*/React.createElement(Rect, {
    x: "0",
    y: "76",
    width: "180",
    height: "8",
    rx: "3"
  }), /*#__PURE__*/React.createElement(Rect, {
    x: "0",
    y: "96",
    width: "300",
    height: "8",
    rx: "3"
  }))) : /*#__PURE__*/React.createElement(AmityPostCommentComponent, {
    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(AmityPostContentComponent, {
      post: postData,
      showedAllOptions: true,
      category: category,
      AmityPostContentComponentStyle: AmityPostContentComponentStyleEnum.detail,
      pageId: pageId
    })
  })), renderFooterComponent()));
};
export default /*#__PURE__*/memo(AmityPostDetailPage);
//# sourceMappingURL=index.js.map