'use strict';

var tslib_es6 = require('./tslib.es6-2c2ed574.js');
var React = require('react');
var index$7 = require('./index-98ac1127.js');
var index$3 = require('./index-d54fe628.js');
var index = require('./index-3643ff1b.js');
var innertext = require('innertext');
var index$1 = require('./index-5b062789.js');
var index$2 = require('./index-b0ce6f8f.js');
var constants = require('./constants-762249c4.js');
var useTogetherAuthRequiredAction = require('./useTogetherAuthRequiredAction.js');
var togetherComponentGlobalContext = require('./utils-302bc65c.js');
var treePopoverMenu = require('./treePopoverMenu-89dcd8ba.js');
var styled = require('@emotion/styled');
var utils = require('./utils-b92a8b1c.js');
var miscTheme = require('./miscTheme.js');
var dataTransform = require('./dataTransform-a2855b2e.js');
var togetherApiPaths = require('./togetherApiPaths.js');
var index$9 = require('./index-80bd2eb2.js');
var togetherMoleculesCardAuthor = require('./index-63b0c985.js');
var togetherMoleculesProfileDetail = require('./index-be663749.js');
var togetherMoleculesPostImagePreview = require('./index-729f166a.js');
var index$a = require('./index-4fb2e074.js');
var index$8 = require('./index-4230e69a.js');
require('./index-6ce6e395.js');
var core$1 = require('@hhgtech/icons/core');
var other = require('@hhgtech/icons/other');
var core = require('@mantine/core');
var index$6 = require('./index-968f57c8.js');
var index$4 = require('./index-a31ed3e1.js');
var index$5 = require('./index-9747120c.js');
var normalizeLink = require('./normalizeLink-20e290e8.js');
var constantsDomainLocales = require('./constantsDomainLocales.js');

function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefault(React);
var innertext__default = /*#__PURE__*/_interopDefault(innertext);
var styled__default = /*#__PURE__*/_interopDefault(styled);

var img$7 = "data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='none'%3e%3cpath fill='%233E3F58' d='M5 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2M19 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2M12 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2'/%3e%3c/svg%3e";
var MBMoreSolid = img$7;

var img$6 = "data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='3' height='13' fill='none'%3e%3ccircle cx='1.583' cy='6.417' r='1.25' fill='%23595959' transform='rotate(90 1.583 6.417)'/%3e%3ccircle cx='1.583' cy='1.417' r='1.25' fill='%23595959' transform='rotate(90 1.583 1.417)'/%3e%3ccircle cx='1.583' cy='11.417' r='1.25' fill='%23595959' transform='rotate(90 1.583 11.417)'/%3e%3c/svg%3e";
var IconKebab = img$6;

var img$5 = "data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none'%3e%3cpath stroke='%23595959' stroke-linecap='round' stroke-linejoin='round' d='M7.17 3.236H2.995a1.193 1.193 0 0 0-1.193 1.192v8.35a1.193 1.193 0 0 0 1.193 1.192h8.35a1.193 1.193 0 0 0 1.192-1.192V8.603'/%3e%3cpath stroke='%23595959' stroke-linecap='round' stroke-linejoin='round' d='M11.643 2.341a1.265 1.265 0 0 1 1.789 1.79L7.766 9.795l-2.385.596.596-2.385z'/%3e%3c/svg%3e";
var IconTabEdit = img$5;

var img$4 = "data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none'%3e%3cpath stroke='%23737373' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.75' d='M2 4h12'/%3e%3cpath stroke='%23737373' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M5.333 4V2.667a1.333 1.333 0 0 1 1.334-1.334h2.666a1.334 1.334 0 0 1 1.334 1.334V4m2 0v9.333a1.334 1.334 0 0 1-1.334 1.334H4.667a1.334 1.334 0 0 1-1.334-1.334V4zM6.667 7.333v4M9.333 7.333v4'/%3e%3c/svg%3e";
var IconTrashBin = img$4;

// import IconBellOff from '../../../assets/svg/icon-bell-off.svg'
// import IconBellOn from '../../../assets/svg/icon-bell-on.svg'
const CardPostPopoverMore = ({ authorEmail, onDeletePost, shareUrl, post, className = '', popoverClassName = '', 
// onBookmark,
// onRemoveBookmark,
onEditPost, }) => {
    const { data: { locale, userInfo, 
    // togetherUserId,
    env: { isMarryBaby }, },
    // action: { pushNotifications },
     } = React.useContext(togetherComponentGlobalContext.TogetherComponentGlobalContext);
    const { t } = index.useTranslations();
    // const [localHasNoti, setLocalHasNoti] = useState(false)
    const [loading, setLoading] = React.useState(false);
    const [isOpenLeavePopup, setIsOpenLeavePopup] = React.useState(false);
    const [isOpenSharePopup, setIsOpenSharePopup] = React.useState(false);
    const { authActionWrapper } = useTogetherAuthRequiredAction.useTogetherAuthRequiredAction();
    const isAuthor = authorEmail && (userInfo === null || userInfo === void 0 ? void 0 : userInfo.email) && authorEmail === String(userInfo === null || userInfo === void 0 ? void 0 : userInfo.email);
    return (React__default["default"].createElement("div", { className: className, onClick: (e) => {
            e.preventDefault();
            e.stopPropagation();
        } },
        isOpenSharePopup && (React__default["default"].createElement(index$1.SharePopup, { url: shareUrl, text: post === null || post === void 0 ? void 0 : post.title, onClose: () => setIsOpenSharePopup(false) })),
        isOpenLeavePopup && (React__default["default"].createElement(index$1.PopupDanger, { thumbnail: index$2.CommonGAssets.getAssetPath('trash-bin.svg'), isThumbnailIcon: true, title: t('popup.deletePost.title'), description: t('popup.deletePost.description'), acceptText: t('popup.deletePost.accept'), cancelText: t('popup.deletePost.cancel'), onAccept: () => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
                if (!(post === null || post === void 0 ? void 0 : post.id) || loading)
                    return;
                setLoading(true);
                try {
                    const res = yield index$1.deletePost({
                        id: post.id,
                        locale,
                    });
                    if ((res === null || res === void 0 ? void 0 : res.status) === 1)
                        onDeletePost === null || onDeletePost === void 0 ? void 0 : onDeletePost();
                }
                catch (_a) { }
                setLoading(false);
            }), onClose: () => setIsOpenLeavePopup(false) })),
        React__default["default"].createElement(treePopoverMenu.TreePopoverMenu, { className: popoverClassName, toggleButtonContent: React__default["default"].createElement("img", { src: isMarryBaby ? MBMoreSolid : IconKebab, loading: "lazy" }), position: "bottom", align: "end", buttonProps: {
                isLoading: loading,
            }, data: isAuthor
                ? {
                    isShowheader: false,
                    type: 'list',
                    list: [
                        // {
                        //   icon: IconShareOnMedia,
                        //   label: t('morePopover.share'),
                        //   onClick: () => setIsOpenSharePopup(true),
                        // },
                        {
                            icon: IconTabEdit,
                            label: t('actionPopover.edit'),
                            onClick: onEditPost,
                        },
                        {
                            icon: IconTrashBin,
                            label: t('actionPopover.delete'),
                            onClick: () => {
                                authActionWrapper(() => setIsOpenLeavePopup(true));
                            },
                        },
                    ],
                }
                : {
                    isShowheader: false,
                    type: 'list',
                    list: [
                        // {
                        //   icon: IconShareOnMedia,
                        //   label: t('morePopover.share'),
                        //   onClick: () => setIsOpenSharePopup(true),
                        // },
                        // {
                        //   icon: !!post?.bookmarked ? IconBookmarkFill : IconBookmark,
                        //   label: !!post?.bookmarked
                        //     ? t('morePopover.unsavePost')
                        //     : t('morePopover.savePost'),
                        //   onClick: () => {
                        //     authActionWrapper(async () => {
                        //       if (!userInfo?.id || !post?.id) return
                        //       if (post?.bookmarked) {
                        //         const res = await callApiWithAuth(
                        //           getApiPath(PATHS.BOOKMARK.DELETE, {
                        //             _locale: locale,
                        //           }),
                        //           'DELETE',
                        //           {
                        //             data: {
                        //               post_id: String(post.id),
                        //             },
                        //           },
                        //         )
                        //         if (res?.status === 1) {
                        //           pushNotifications({
                        //             title: '',
                        //             message: 'Removed saved post',
                        //             type: 'success',
                        //             displayIcon: IconBookmark,
                        //           })
                        //           onRemoveBookmark && onRemoveBookmark()
                        //         } else {
                        //           pushNotifications({
                        //             title: '',
                        //             message: 'Remove failed',
                        //             type: 'danger',
                        //             displayIcon: IconBookmark,
                        //           })
                        //         }
                        //       } else {
                        //         const res = await callApiWithAuth(
                        //           getApiPath(PATHS.BOOKMARK.CREATE, {
                        //             _locale: locale,
                        //           }),
                        //           'POST',
                        //           {
                        //             data: {
                        //               user_id: togetherUserId || userInfo.id,
                        //               post_id: post.id,
                        //             },
                        //           },
                        //         )
                        //         if (res?.status === 1) {
                        //           pushNotifications({
                        //             title: '',
                        //             message: 'Post saved',
                        //             type: 'success',
                        //             displayIcon: IconBookmarkFill,
                        //           })
                        //           onBookmark && onBookmark()
                        //         } else {
                        //           pushNotifications({
                        //             title: '',
                        //             message: 'Post saved failed',
                        //             type: 'danger',
                        //             displayIcon: IconBookmark,
                        //           })
                        //         }
                        //       }
                        //     })
                        //   },
                        // },
                        // {
                        //   icon: togetherBasePath + '/svg/icon-bell-on.svg',
                        //   label: !localHasNoti
                        //     ? t( 'morePopover.turnOnNotifications' })
                        //     : t( 'morePopover.turnOffNotifications' }),
                        //   onClick: () => {
                        //   authActionWrapper(async () => {
                        //     if (!post?.id || loading) return
                        //     setLoading(true)
                        //     try {
                        //       const res = await followUnfollowPost({
                        //         id: post?.id,
                        //         locale,
                        //       })
                        //       if (res?.status === 1) {
                        //         pushNotifications({
                        //           message: !localHasNoti
                        //             ? 'Notification on'
                        //             : 'Notification off',
                        //           type: !localHasNoti ? 'success' : 'danger',
                        //           displayIcon: !localHasNoti ? IconBellOn : IconBellOff,
                        //         })
                        //         setLocalHasNoti((v) => !v)
                        //       }
                        //     } catch {}
                        //     setLoading(false)
                        //   })
                        // },
                        // },
                        {
                            icon: index$1.IconAlertCircle,
                            label: t('morePopover.report'),
                            subTree: {
                                title: t('morePopover.report.title'),
                                description: t('morePopover.report.description'),
                                isShowheader: true,
                                type: 'list',
                                list: Object.keys(constants.REPORT_REASON_MAP)
                                    .map((k) => ({
                                    label: constants.REPORT_REASON_MAP[k].label,
                                    reason: constants.REPORT_REASON_MAP[k].reportReasonText,
                                    reasonValue: k,
                                }))
                                    .map((item) => ({
                                    label: t(item.label),
                                    subTree: {
                                        title: t('morePopover.reportSubmit.title'),
                                        description: t('morePopover.reportSubmit.description'),
                                        isShowheader: true,
                                        type: 'jsx',
                                        jsxRenderer: (setShow) => (React__default["default"].createElement(index$1.SubmitReportForm, { reason: item.reasonValue, reasonText: t(item.reason), postId: post === null || post === void 0 ? void 0 : post.id, onClose: () => setShow && setShow(false) })),
                                    },
                                })),
                            },
                        },
                    ],
                } })));
};

const StyledCardPost$1 = styled__default["default"].div `
  position: relative;
  margin-bottom: 24px;
  background: white;
  border-radius: ${miscTheme.theme.borderRadius};

  a {
    text-decoration: none;
  }

  ${utils.MediaQueries.mbDown} {
    margin-bottom: 8px;
  }
  &.flat-top {
    border-top-left-radius: 0;
    border-top-right-radius: 0;
  }

  .post-pin {
    padding: 0.5rem 1rem;
    border-radius: ${miscTheme.theme.borderRadius} 6px 0 0;
  }
  .post-author {
    display: flex;
    align-items: center;
    justify-content: space-between;
    &.comment {
      padding-right: 2.6rem;
    }
    .author-avatar-wrapper {
      width: 40px;
      height: 40px;
      font-size: 20px;
      ${utils.MediaQueries.mbDown} {
        width: 32px;
        height: 32px;
        font-size: 16px;
      }
    }
  }
  .post-content-link-wrapper {
    color: inherit;
    cursor: pointer;
    .post-content-title {
      padding: 1rem 1rem 0;
      word-break: break-word;
    }
  }
  .social-preview-wrapper.has-image {
    margin-bottom: 5px;
  }
  .social-preview-wrapper,
  .image-preview-wrapper,
  .link-preview-wrapper {
    width: 100%;
    &[data-is-reply='true'] {
      padding-right: 1rem;
      padding-left: 1rem;
    }
  }
  .post-topics {
    padding: 0 1rem;
  }

  .post-reaction {
    background: none;
    border-radius: 0 0 6px 6px;
    &.hide-top-border {
      ::before {
        display: none;
      }
    }
  }
  .most-engaging-wrapper {
    padding: 1rem;
    cursor: pointer;
    .author-avatar-wrapper {
      width: 2rem;
      height: 2rem;
      font-size: 1rem;
    }
    .see-more-comments {
      width: 100%;
      padding: 12px 0 0;
      text-align: unset;
    }
  }
  &[data-most-engaging='true'] {
    border: none;
    ${utils.MediaQueries.mbDown} {
      margin: 1rem;
      border: 1px solid #e4e8ec;
    }
  }
  .top-divider {
    border-color: #e4e8ec;
  }
  .popover {
    .popover-menu__btn {
      display: flex;
      width: 1.5rem;
      height: 1rem;
      align-items: center;
      justify-content: center;
      padding: 0;
      background: transparent;

      &:hover {
        background-color: transparent;
      }
    }
    .popover-menu__content {
      &.--position-bottom {
        &.--align-end {
          &::before {
            right: 12.5px;
          }
        }
      }
    }
  }

  &[data-is-marrybaby='true'] {
    border: 1px solid #f3f3f3;
    border-radius: 1rem;
    /* shadow */

    box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.08);
    .image-preview-wrapper,
    .link-preview-wrapper {
      padding-right: 1rem;
      padding-left: 1rem;
    }
    .popover {
      .popover-menu__btn {
        width: 24px;
        height: 24px;
        ${utils.MediaQueries.mbDown} {
          width: 18px;
          height: 18px;
        }
      }
      .popover-menu__content {
        &.--position-bottom {
          &.--align-end {
            &::before {
              right: 1rem;
            }
            width: 350px;
            ${utils.MediaQueries.mbDown} {
              max-width: calc(320px - 2rem);
            }
          }
        }
      }
    }
    .most-engaging-wrapper {
      position: relative;
      padding: 0;
      &::before {
        position: absolute;
        z-index: 5;
        top: 0;
        left: 50%;
        width: calc(100% - 2rem);
        height: 1px;
        background: #f3f3f3;
        content: ' ';
        transform: translateX(-50%);
      }
    }
    ${utils.MediaQueries.mbDown} {
      margin-bottom: 12px;
    }
  }
`;

var img$3 = "data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%23595959'%3e%3cpath stroke='%23595959' stroke-linecap='round' stroke-linejoin='round' d='M12 13.333 8 10.37l-4 2.963V3.852c0-.314.12-.616.335-.838.214-.222.505-.347.808-.347h5.714c.303 0 .594.125.808.347s.335.524.335.838z'/%3e%3c/svg%3e";
var IconBookmarkFill = img$3;

var img$2 = "data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none'%3e%3cpath stroke='%23595959' stroke-linecap='round' stroke-linejoin='round' d='M12 13.333 8 10.37l-4 2.963V3.852c0-.314.12-.616.335-.838.214-.222.505-.347.808-.347h5.714c.303 0 .594.125.808.347s.335.524.335.838z'/%3e%3c/svg%3e";
var IconBookmark = img$2;

var img$1 = "data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' height='17' fill='none'%3e%3cg stroke='%23737373' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' clip-path='url(%23a)'%3e%3cpath d='M2 4.008h12m-8.667 0V2.675a1.333 1.333 0 0 1 1.334-1.333h2.666a1.333 1.333 0 0 1 1.334 1.333v1.333m2 0v9.334a1.333 1.333 0 0 1-1.334 1.333H4.667a1.333 1.333 0 0 1-1.334-1.333V4.008zm-6 3.334v4m2.666-4v4'/%3e%3c/g%3e%3cdefs%3e%3cclipPath id='a'%3e%3cpath fill='white' d='M0 .008h16v16H0z'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e";
var IconDelete = img$1;

const CardReplyPopover = ({ onDeleteComment, commentId, className = '', popoverClassName = '', }) => {
    const { data: { env: { isMarryBaby }, locale, }, action: { pushNotifications }, } = React.useContext(togetherComponentGlobalContext.TogetherComponentGlobalContext);
    const { t } = index.useTranslations();
    const [isOpenLeavePopup, setIsOpenLeavePopup] = React.useState(false);
    const { authActionWrapper } = useTogetherAuthRequiredAction.useTogetherAuthRequiredAction();
    return (React__default["default"].createElement("div", { className: className, onClick: (e) => {
            e.preventDefault();
            e.stopPropagation();
        } },
        isOpenLeavePopup && (React__default["default"].createElement(index$1.PopupDanger, { thumbnail: IconDelete, isThumbnailIcon: true, title: t('popup.deleteComment.title'), description: t('popup.deleteComment.description'), acceptText: t('popup.deletePost.accept'), cancelText: t('popup.deletePost.cancel'), onAccept: () => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
                var _a;
                if (!commentId)
                    return;
                const res = yield index$1.deleteComment({ id: commentId, locale });
                if ((res === null || res === void 0 ? void 0 : res.status) === 1) {
                    onDeleteComment && onDeleteComment();
                    pushNotifications({
                        title: '',
                        message: t('notification.success'),
                        type: 'success',
                    });
                }
                else {
                    pushNotifications({
                        title: '',
                        message: ((_a = res === null || res === void 0 ? void 0 : res.messages) === null || _a === void 0 ? void 0 : _a[0]) || t('notification.failure'),
                        type: 'danger',
                    });
                }
            }), onClose: () => setIsOpenLeavePopup(false) })),
        React__default["default"].createElement(treePopoverMenu.TreePopoverMenu, { position: "bottom", align: "end", data: {
                isShowheader: false,
                type: 'list',
                list: [
                    // {
                    //   icon: _href('/svg/icon-share-on-media.svg'),
                    //   label: f({ id: 'morePopover.share' }),
                    //   subTree: {
                    //     title: f({ id: 'morePopover.shareOn' }),
                    //     isShowheader: true,
                    //     type: 'jsx',
                    //     jsxType: TreeJSXType.share,
                    //     data: {
                    //       shareUrl: shareUrl,
                    //       shareTitle: shareTitle,
                    //     },
                    //   },
                    // },
                    // {
                    //   icon: _href('/svg/icon-tab-edit-2.svg'),
                    //   label: f({ id: 'actionPopover.edit' }),
                    //   onClick: onEditPost,
                    // },
                    {
                        icon: IconTrashBin,
                        label: t('actionPopover.delete'),
                        onClick: () => {
                            authActionWrapper(() => {
                                setIsOpenLeavePopup(true);
                            });
                        },
                    },
                ],
            }, className: popoverClassName, toggleButtonContent: React__default["default"].createElement("img", { src: isMarryBaby ? MBMoreSolid : IconKebab, loading: "lazy" }), buttonProps: {
            // isLoading: loading,
            } })));
};

const StyledContainer$1 = styled__default["default"].div `
  .add-link {
    color: ${miscTheme.theme.colors.primaryBase};
  }
`;
const StyledAlertTag = styled__default["default"].div `
  margin: 16px 0;
  background: ${miscTheme.theme.colors.yellow50};
  padding: 5px 10px;
  border-radius: 2px;

  .icon {
    display: inline-block;
    vertical-align: middle;
    margin-right: 6px;
  }
`;
const StyledSourceItemWrapper = styled__default["default"].div `
  display: flex;
  align-items: center;
  gap: 8px;
`;
const StyledListItems$1 = styled__default["default"].div `
  padding: 8px 16px;
`;
const StyledInputWrapper = styled__default["default"].div `
  margin-bottom: 12px;
  width: 100%;
`;

const StyledContainer = styled__default["default"].div ``;
const StyledHeader = styled__default["default"].div `
  margin-bottom: 16px;
`;
const StyledListItems = styled__default["default"].div `
  display: flex;
  flex-wrap: wrap;
  row-gap: 16px;
  ${utils.MediaQueries.tdUp} {
    align-items: center;
    column-gap: 24px;
  }
`;
const StyledItem$1 = styled__default["default"].a `
  display: flex;
  align-items: center;
  gap: 16px;
  ${utils.MediaQueries.mbDown} {
    width: 100%;
    justify-content: space-between;
  }
`;
const StyledItemInfo = styled__default["default"].div `
  display: flex;
  align-items: center;
  gap: 16px;
`;
const StyledThumb = styled__default["default"].div `
  border-radius: ${miscTheme.theme.borderRadius};
  overflow: hidden;
  width: 48px;
  height: 48px;
  img {
    object-fit: cover;
    width: 100%;
    height: 100%;
  }
`;

const RecommentCategories = ({ categories }) => {
    const { t } = index.useTranslations();
    const { data: { locale, env: { isMarryBaby }, }, } = React.useContext(togetherComponentGlobalContext.TogetherComponentGlobalContext);
    const url = normalizeLink.getCurrentBaseUrl(locale, isMarryBaby);
    return (React__default["default"].createElement(StyledContainer, null,
        React__default["default"].createElement(StyledHeader, null,
            React__default["default"].createElement(index$3.Heading, { tag: "h6", as: "h5" }, t('cardReply.recommentCategories.heading'))),
        React__default["default"].createElement(StyledListItems, null, categories.map((i) => (React__default["default"].createElement(StyledItem$1, { href: url + i.permalink, key: String(i.termId), target: "_blank" },
            React__default["default"].createElement(StyledItemInfo, null,
                React__default["default"].createElement(StyledThumb, null,
                    React__default["default"].createElement("img", { src: i.featureImage ||
                            index$2.CommonGAssets.getAssetPath(isMarryBaby ? 'mb-logo.svg' : '/logo/logomark.png'), alt: i.displayName, loading: "lazy" })),
                React__default["default"].createElement(index$4.Text, { size: "s3", weight: "bold" }, i.displayName)),
            React__default["default"].createElement(other.ArrowRight, { size: 20, color: miscTheme.theme.colors.gray400 })))))));
};

const StyledItem = styled__default["default"].a `
  padding: 12px 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
  border-top: 1px solid ${miscTheme.theme.colors.neutral100};
  text-decoration: none;

  &:first-child {
    border-top: 0;
  }
`;

const SourceItem = ({ postTitle, articleReviewed, modifiedTime, href, }) => {
    const { t } = index.useTranslations();
    const getDetail = (() => {
        const { expert, editor, is_author } = articleReviewed;
        if (expert) {
            const result = {
                name: expert.display_name,
                role: 'expert',
                avatar: expert.avatar,
            };
            if (is_author) {
                return Object.assign({ title: t('articleAuthor.title.written-by') }, result);
            }
            else {
                if (expert.role === 'expert') {
                    // Is Expert
                    return Object.assign({ title: t('articleAuthor.title.expert') }, result);
                }
                else {
                    // Is medical
                    return Object.assign({ title: t('articleAuthor.title.medical') }, result);
                }
            }
        }
        else if (editor) {
            return {
                title: t('articleAuthor.title.fact-check'),
                name: editor.display_name,
                avatar: editor.avatar,
            };
        }
    })();
    return (React__default["default"].createElement(StyledItem, { href: href, title: postTitle, target: "_blank" },
        React__default["default"].createElement(index$4.Text, { size: "s3", as: "h5", weight: "bold" }, postTitle),
        React__default["default"].createElement("div", null,
            React__default["default"].createElement(togetherMoleculesCardAuthor.CardAuthor, { avatar: getDetail === null || getDetail === void 0 ? void 0 : getDetail.avatar, avatarProps: {
                    size: 32,
                }, name: getDetail === null || getDetail === void 0 ? void 0 : getDetail.name, role: getDetail === null || getDetail === void 0 ? void 0 : getDetail.role, hideBackground: true },
                React__default["default"].createElement(togetherMoleculesCardAuthor.CardAuthor.SubTextRow, null,
                    React__default["default"].createElement(togetherMoleculesCardAuthor.CardAuthor.SubText, null, getDetail === null || getDetail === void 0 ? void 0 :
                        getDetail.title,
                        ' ',
                        React__default["default"].createElement("span", { style: { color: miscTheme.theme.colors.gray800 } }, getDetail === null || getDetail === void 0 ? void 0 : getDetail.name)),
                    React__default["default"].createElement(togetherMoleculesCardAuthor.CardAuthor.SubDivider, null),
                    React__default["default"].createElement(togetherMoleculesCardAuthor.CardAuthor.SubText, null, modifiedTime))))));
};

var styles$1 = {"accordion":"CnNZq8D","header":"F4mmgSy","heading":"_8jLruY3","headingIcon":"FE8w-fe","panel":"Yd2a9Nj","chevron":"A7QrQ7A"};

const SourceList = (_a) => {
    var { listUrl: listUrlInit, hideSourceList, categorySlug, editMode, collapseSource, onListChange, isMarryBaby } = _a, rest = tslib_es6.__rest(_a, ["listUrl", "hideSourceList", "categorySlug", "editMode", "collapseSource", "onListChange", "isMarryBaby"]);
    const { t } = index.useTranslations();
    const [listUrl, setListUrl] = React.useState(listUrlInit || []);
    const [data, setData] = React.useState([]);
    const [categories, setCategories] = React.useState([]);
    const [loading, setLoading] = React.useState(false);
    React.useEffect(() => {
        !hideSourceList &&
            (() => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
                setLoading(true);
                const listPaths = listUrl.map((i) => {
                    const url = new URL(i);
                    const pathArr = String(url.pathname)
                        .split('/')
                        .filter((i) => i != '');
                    const origin = url.origin;
                    const isMarrySite = origin.search('marrybaby.vn') !== -1;
                    return {
                        isMarrySite,
                        path: pathArr[pathArr.length - 1],
                        href: i,
                    };
                });
                const listApi = [
                    ...listPaths.map((i) => togetherComponentGlobalContext.callApi(i.isMarrySite
                        ? togetherComponentGlobalContext.getMarryBabyApiPath(togetherApiPaths.DISCOVER_PATHS.GET_PREVIEW_ARTICLE, {
                            fullSlug: i.path,
                        }, true)
                        : togetherComponentGlobalContext.getDiscoverApiPath(togetherApiPaths.DISCOVER_PATHS.GET_PREVIEW_ARTICLE, {
                            fullSlug: i.path,
                        }, true), 'GET')),
                ];
                const res = yield Promise.all(listApi);
                setData(res
                    .map((i, index) => {
                    var _a, _b;
                    return ((_a = i === null || i === void 0 ? void 0 : i.data) === null || _a === void 0 ? void 0 : _a.post) && Object.assign(Object.assign({}, dataTransform.formatArticle((_b = i === null || i === void 0 ? void 0 : i.data) === null || _b === void 0 ? void 0 : _b.post)), { href: listPaths[index].href });
                })
                    .filter(Boolean));
                setLoading(false);
            }))();
    }, []);
    React.useEffect(() => {
        !hideSourceList &&
            (data === null || data === void 0 ? void 0 : data.length) === 0 &&
            categorySlug &&
            (() => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
                var _a;
                const res = yield togetherComponentGlobalContext.callApi(isMarryBaby
                    ? togetherComponentGlobalContext.getMarryBabyApiPath(togetherApiPaths.DISCOVER_PATHS.GET_CATEGORY_OR_ARTICLE_DETAIL, {
                        fullSlug: categorySlug,
                    }, true)
                    : togetherComponentGlobalContext.getDiscoverApiPath(togetherApiPaths.DISCOVER_PATHS.GET_CATEGORY_OR_ARTICLE_DETAIL, {
                        fullSlug: categorySlug,
                    }, true), 'GET');
                (res === null || res === void 0 ? void 0 : res.data) && setCategories([dataTransform.formatCategory((_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.category)]);
            }))();
    }, [data]);
    const handleRemoveItem = (idx) => {
        setListUrl((old) => {
            const tmp = [...old];
            tmp.splice(idx, 1);
            return tmp;
        });
        setData((old) => {
            const tmp = [...old];
            tmp.splice(idx, 1);
            return tmp;
        });
    };
    React.useEffect(() => {
        onListChange === null || onListChange === void 0 ? void 0 : onListChange(listUrl);
    }, [listUrl]);
    return (React__default["default"].createElement("div", Object.assign({}, rest),
        !editMode && (React__default["default"].createElement(StyledAlertTag, null,
            React__default["default"].createElement("img", { className: "icon", src: index$2.CommonGAssets.getAssetPath('warning.svg'), alt: "warning", style: { marginBottom: '3px', width: '18px' }, loading: "lazy" }),
            React__default["default"].createElement(index$4.Text, { size: "s3", as: "span", dangerouslySetInnerHTML: {
                    __html: t('cardReply.disclaimer'),
                } }))),
        !hideSourceList ? (loading ? (React__default["default"].createElement(index$5.Loading, null)) : data.length > 0 || editMode ? (React__default["default"].createElement(StyledContainer$1, null,
            React__default["default"].createElement(core.Accordion, { defaultValue: !collapseSource && 'accordion', styles: {
                    control: {
                        borderRadius: 'inherit',
                        '&[aria-expanded="false"]': {
                            borderBottom: 0,
                        },
                    },
                    chevron: {
                        width: '32px',
                        height: '32px',
                    },
                    content: {
                        padding: 0,
                        borderBottom: 0,
                        borderTop: `1px solid ${miscTheme.theme.colors.neutral100}`,
                    },
                    item: {
                        marginBottom: '16px',
                        borderTopLeftRadius: '8px',
                        borderTopRightRadius: '8px',
                        border: `1px solid ${miscTheme.theme.colors.neutral100}`,
                        borderBottomLeftRadius: '8px',
                        borderBottomRightRadius: '8px',
                        '&[data-active]': {
                            borderBottomLeftRadius: 0,
                            borderBottomRightRadius: 0,
                        },
                    },
                }, chevron: React__default["default"].createElement("div", { className: styles$1.chevron },
                    React__default["default"].createElement(other.ArrowDown, { color: miscTheme.theme.colors.gray600, size: 20 })) },
                React__default["default"].createElement(core.Accordion.Item, { value: "accordion" },
                    React__default["default"].createElement(core.Accordion.Control, null,
                        React__default["default"].createElement("div", { className: styles$1.header },
                            React__default["default"].createElement(index$3.Heading, { as: "h4", tag: "h6" }, t('cardReply.source')))),
                    React__default["default"].createElement(core.Accordion.Panel, null,
                        React__default["default"].createElement(StyledListItems$1, null,
                            (data || []).map((i, idx) => (React__default["default"].createElement(StyledSourceItemWrapper, { key: String(idx) },
                                typeof i === 'object' ? (React__default["default"].createElement(SourceItem, Object.assign({}, i))) : (React__default["default"].createElement(StyledInputWrapper, null,
                                    React__default["default"].createElement(index$6.Input, { style: { width: '100%' }, name: "source-list", value: i || '', size: "sm", onChange: (v) => {
                                            setListUrl((old) => {
                                                const tmp = [...old];
                                                tmp[idx] = v;
                                                return tmp;
                                            });
                                            setData((old) => {
                                                const tmp = [...old];
                                                tmp[idx] = v;
                                                return tmp;
                                            });
                                        } }))),
                                editMode && (React__default["default"].createElement(index$7.Button, { size: "md", color: "transparent", icon: React__default["default"].createElement(other.Trash, null), onClick: () => handleRemoveItem(idx) }))))),
                            editMode && (React__default["default"].createElement(index$7.Button, { className: "add-link", color: "transparent", size: "md", icon: React__default["default"].createElement(core$1.Plus, { color: miscTheme.theme.colors.primaryBase, size: 18 }), onClick: () => {
                                    setListUrl((old) => [...old, '']);
                                    setData((old) => [...old, '']);
                                } }, "Add source")))))))) : (React__default["default"].createElement(RecommentCategories, { categories: categories }))) : null));
};

const StyledCardPost = styled__default["default"].div `
  position: relative;
  margin-bottom: 0;
  background: white;
  border-radius: ${miscTheme.theme.borderRadius};

  .verify-tag {
    margin-top: 12px;
  }

  .post-author {
    &.with-popover {
      padding-right: 2.6rem;
    }
    .author-avatar-wrapper {
      width: 40px;
      height: 40px;
      font-size: 20px;
      ${utils.MediaQueries.mbDown} {
        width: 32px;
        height: 32px;
        font-size: 16px;
      }
    }
  }
  .image-preview-wrapper,
  .link-preview-wrapper {
    width: 100%;
    &[data-is-reply='true'] {
      padding-right: 1rem;
      padding-left: 1rem;
    }
  }
  .post-reaction {
    background: none;
    border-radius: 0 0 6px 6px;
  }
  &[data-is-reply='true'] {
    > .post-author .author-avatar-wrapper {
      width: 20px;
      height: 20px;
      font-size: 10px;
    }
  }
  &[data-is-reply='false'] {
    border: 1px solid #e4e8ec;
  }
  .expert-wrapper {
    width: 100%;
  }
  &[data-has-booking='true'] {
    display: grid;
    .post-author {
      background-color: ${miscTheme.theme.colors.primary50};
    }
    .btn-wrapper {
      padding: 0 16px;
      .btn-booking {
        width: 100%;
        margin: 12px 0;
      }
    }
  }

  .comment-reply-wrapper {
    padding: 0 1rem;
    .more-cmt {
      .chevron-right {
        height: 1rem;
        width: 1rem;
        vertical-align: middle;
      }
    }
  }
  .top-divider {
    border-color: #e4e8ec;
  }
  .popover {
    position: absolute;
    top: 1.5rem;
    right: 1rem;
    .popover-menu__btn {
      display: flex;
      width: 1rem;
      height: 1rem;
      align-items: center;
      justify-content: center;
      padding: 0;
      background: transparent;

      &:hover {
        background-color: transparent;
      }

      .popover-menu__content {
        &.--position-bottom {
          &.--align-end {
            &::before {
              right: 12.5px;
            }
          }
        }
      }
    }
  }

  &[data-is-marrybaby='true'] {
    &[data-is-reply='false'] {
      border: none;
    }
    .image-preview-wrapper,
    .link-preview-wrapper {
      padding-right: 1rem;
      padding-left: 1rem;
    }
    .popover {
      .popover-menu__btn {
        width: 24px;
        height: 24px;
      }
    }

    margin-left: 56px;
    ${utils.MediaQueries.mbDown} {
      margin-left: 40px;
    }
    > .post-author {
      margin-left: -56px;
      ${utils.MediaQueries.mbDown} {
        margin-left: -40px;
      }
      .author-info {
        align-items: center;
        display: flex;
        align-items: center;
        .author-info-top {
          width: 100%;
        }
        .author-info-text-wrapper {
          justify-content: space-between;
        }
      }
      .author-avatar-wrapper {
        width: 40px;
        height: 40px;
        font-size: 20px;
        ${utils.MediaQueries.mbDown} {
          width: 24px;
          height: 24px;
          font-size: 12px;
        }
      }
    }
    &[data-is-reply] {
      > .post-author {
        .author-avatar-wrapper {
          width: 40px;
          height: 40px;
          font-size: 20px;
          ${utils.MediaQueries.mbDown} {
            width: 24px;
            height: 24px;
            font-size: 12px;
          }
        }
      }
    }

    .comment-reply-wrapper {
      padding-right: 0;
      padding-left: 0;
    }
    .post-reaction {
      &::after {
        position: absolute;
        bottom: 0;
        left: 50%;
        width: calc(100% - 2rem);
        height: 1px;
        background: #f3f3f3;
        content: ' ';
        transform: translateX(-50%);
      }
    }
    .post-content-wrapper {
      padding-top: 0;
      padding-bottom: 0;
      ${utils.MediaQueries.mbDown} {
        padding-left: 0.5rem;
      }
    }

    ${utils.MediaQueries.mbDown} {
      margin-bottom: 12px;
    }
  }
`;
const StyledSourceList = styled__default["default"](SourceList) `
  margin-top: 12px;
  padding: 0.5rem 1rem 1rem;
`;

var styles = {"button":"-dzIuHr"};

const VerifiedTag = ({ userId, avatar, name, role, title, className, }) => {
    const { t } = index.useTranslations();
    const [openPopup, setOpenPopup] = React.useState(false);
    return (React__default["default"].createElement(React__default["default"].Fragment, null,
        React__default["default"].createElement(index$7.Button, { className: `${styles.button} ${className}`, color: "success", size: "xs", onClick: () => setOpenPopup(true), style: {
                padding: '5px 8px',
                marginBottom: '12px',
                borderRadius: '4px',
            } },
            React__default["default"].createElement("span", { className: "text" },
                React__default["default"].createElement(other.Endorse, { isSolid: true, size: 18, color: miscTheme.theme.colors.green800, className: "icon" }),
                t('cardReply.verifyBy', {
                    name: `${name || ''}`,
                }))),
        React__default["default"].createElement(togetherMoleculesCardAuthor.ProfileDetailModal, { open: openPopup, onClose: () => setOpenPopup(false), profileModalProps: { zIndex: 1000 } },
            React__default["default"].createElement(togetherMoleculesProfileDetail.ProfileDetail, { authorProps: {
                    userId,
                    avatar: avatar,
                    name,
                    role,
                    title,
                }, hideQuestionTab: true }))));
};

var img = "data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none'%3e%3cpath stroke='%232D87F3' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 12 4-4-4-4'/%3e%3c/svg%3e";
var ChevronRightActive = img;

const COMMENT_LIMIT = 4;
const CardReply = ({ className, style, comment: CommentProps, type = 'comment', level = 0, replyingId, onPostCommentSuccess, post, onDeleteComment, refetchComment, hasQuickBookingEnable, handleMakeAppointment, cardAuthorProps, maxChars = 600, disableShortenContent, }) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
    const { data: { locale, userInfo, env: { isMarryBaby }, }, } = React.useContext(togetherComponentGlobalContext.TogetherComponentGlobalContext);
    const { t } = index.useTranslations();
    const [comment, setComment] = React.useState(CommentProps || null);
    const { id, countLikes, content, replies = [], images = [], author, liked, link, mentionedUser, mentions, } = comment;
    const { text, replyingTo } = index$1.decodeCommentBody(content);
    const { authActionWrapper } = useTogetherAuthRequiredAction.useTogetherAuthRequiredAction({
        _joinCommunityIds: [(_a = post === null || post === void 0 ? void 0 : post.community) === null || _a === void 0 ? void 0 : _a.id],
        _joinTopicIds: (_b = post === null || post === void 0 ? void 0 : post.topics) === null || _b === void 0 ? void 0 : _b.map((t) => t.id),
    });
    const [maxRepliesShow, setMaxRepliesShow] = React.useState(COMMENT_LIMIT);
    const isCommented = (userInfo === null || userInfo === void 0 ? void 0 : userInfo.id)
        ? replies === null || replies === void 0 ? void 0 : replies.some((c) => c.author.id === userInfo.id)
        : false;
    const addNewReply = (comment) => {
        setComment((old) => {
            // somehow this set state run twice
            // => we need to check unique comment id before add to array
            if (!old.replies.find((c) => c.id === comment.id)) {
                old.replies.unshift(comment);
                const newComment = Object.assign(Object.assign({}, old), { replies: old.replies.slice(), countReplies: old.countReplies + 1 });
                refetchComment && refetchComment(newComment);
                return newComment;
            }
            return old;
        });
    };
    const [showInputComment, setShowInputComment] = React.useState(false);
    const sortedReplies = React.useMemo(() => {
        if (type !== 'comment' || !replies || replies.length == 0)
            return replies;
        return replies.sort((a, b) => {
            const timeA = new Date(a.createdAt).getTime();
            const timeB = new Date(b.createdAt).getTime();
            if (timeA > timeB)
                return -1;
            if (timeA < timeB)
                return 1;
            return 0;
        });
    }, [type, replies]);
    const mergeCountReplies = (replies === null || replies === void 0 ? void 0 : replies.length) || 0;
    const hasPopover = String(author === null || author === void 0 ? void 0 : author.email) &&
        (userInfo === null || userInfo === void 0 ? void 0 : userInfo.email) &&
        String(author === null || author === void 0 ? void 0 : author.email) === String(userInfo === null || userInfo === void 0 ? void 0 : userInfo.email);
    // const isAnonymousOfCurAuthor =
    //   post?.isAnonymous && post?.author?.username === author?.username
    // const name = isAnonymousOfCurAuthor
    //   ? t('cardPost.anonymous')
    //   : author?.name || author?.username || ''
    // const avatar = isAnonymousOfCurAuthor ? DEFAULT_AVATAR_IMG : author?.avatar
    // const username = isAnonymousOfCurAuthor
    //   ? t('cardPost.anonymous')
    //   : author?.username || author?.name || ''
    const name = (author === null || author === void 0 ? void 0 : author.name) || (author === null || author === void 0 ? void 0 : author.username) || '';
    const username = (author === null || author === void 0 ? void 0 : author.username) || (author === null || author === void 0 ? void 0 : author.name) || '';
    const avatar = author === null || author === void 0 ? void 0 : author.avatar;
    const authorRole = (post === null || post === void 0 ? void 0 : post.isAnonymous) ? undefined : author === null || author === void 0 ? void 0 : author.role;
    const listMentions = [
        ...((post === null || post === void 0 ? void 0 : post.isAnonymous)
            ? [
                {
                    id: ((_c = post === null || post === void 0 ? void 0 : post.author) === null || _c === void 0 ? void 0 : _c.id) || 0,
                    name: t('cardPost.anonymous'),
                },
            ]
            : []),
        ...(mentions || []),
    ];
    const [hospitalInfo, setHospitalInfo] = React.useState(null);
    const [doctorInfo, setDoctorInfo] = React.useState(null);
    React.useEffect(() => {
        if (author === null || author === void 0 ? void 0 : author.hospitalId) {
            const fetchHospitalDetail = (hospitalId) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
                var _a;
                const response = yield togetherComponentGlobalContext.callApi(togetherComponentGlobalContext.getCarePath(togetherApiPaths.CARE_PATHS.GET_HOSPITAL_INFO, {
                    hospital_branch_id: hospitalId,
                    website_url: constantsDomainLocales.domainLocales[locale],
                }), 'get');
                if ((_a = response === null || response === void 0 ? void 0 : response._data) === null || _a === void 0 ? void 0 : _a.branch) {
                    setHospitalInfo(response === null || response === void 0 ? void 0 : response._data.branch);
                }
            });
            fetchHospitalDetail(author.hospitalId);
        }
        if (author === null || author === void 0 ? void 0 : author.doctorId) {
            const fetchDoctorDetail = (doctorId) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
                var _b;
                const response = yield togetherComponentGlobalContext.callApi(togetherComponentGlobalContext.getCarePath(togetherApiPaths.CARE_PATHS.GET_DOCTOR_INFO, {
                    doctorId: doctorId,
                    website_url: constantsDomainLocales.domainLocales[locale],
                }), 'get');
                if ((_b = response === null || response === void 0 ? void 0 : response._data) === null || _b === void 0 ? void 0 : _b.doctor) {
                    setDoctorInfo(response === null || response === void 0 ? void 0 : response._data.doctor);
                }
            });
            fetchDoctorDetail(author.doctorId);
        }
    }, [author.hospitalId, author.doctorId]);
    const isDoctorAvailable = (doctorInfo === null || doctorInfo === void 0 ? void 0 : doctorInfo.valid_outpatient) || (doctorInfo === null || doctorInfo === void 0 ? void 0 : doctorInfo.valid_telemedicine);
    const isHospitalAvailable = ((hospitalInfo === null || hospitalInfo === void 0 ? void 0 : hospitalInfo.total_available_service) ||
        (hospitalInfo === null || hospitalInfo === void 0 ? void 0 : hospitalInfo.total_available_doctor)) > 0;
    const hasQuickBooking = hasQuickBookingEnable && (isDoctorAvailable || isHospitalAvailable);
    const isChatbotAuthor = ((_d = comment === null || comment === void 0 ? void 0 : comment.author) === null || _d === void 0 ? void 0 : _d.type) === 'chatbot';
    return (React__default["default"].createElement(useTogetherAuthRequiredAction.TogetherAuthConfigContextProvider, { defaultParams: {
            _joinCommunityIds: [(_e = post === null || post === void 0 ? void 0 : post.community) === null || _e === void 0 ? void 0 : _e.id],
            _joinTopicIds: (_f = post === null || post === void 0 ? void 0 : post.topics) === null || _f === void 0 ? void 0 : _f.map((t) => t.id),
        } },
        React__default["default"].createElement(StyledCardPost, { className: className, style: style, "data-is-reply": !!level, "data-is-marrybaby": isMarryBaby, "data-has-booking": hasQuickBooking },
            type === 'reply' && React__default["default"].createElement(index$8.Divider, { className: "top-divider", type: "solid" }),
            React__default["default"].createElement("div", { style: { padding: '16px 16px 0' } },
                React__default["default"].createElement(togetherMoleculesCardAuthor.CardAuthor, Object.assign({ avatar: avatar, name: name, username: username, timeText: post === null || post === void 0 ? void 0 : post.createdTime, community: post === null || post === void 0 ? void 0 : post.community, 
                    // miniIcon="./svg/icon-tag.svg"
                    // authorLabelType={getAuthorLabelFromRoles(author?.role || [])}
                    className: `post-author ${hasPopover ? 'with-popover' : ''}`, type: type, userId: author === null || author === void 0 ? void 0 : author.id, role: authorRole, expertId: author === null || author === void 0 ? void 0 : author.partnerId, title: author === null || author === void 0 ? void 0 : author.title, doctorId: author === null || author === void 0 ? void 0 : author.doctorId, hospitalId: author === null || author === void 0 ? void 0 : author.hospitalId, hasQuickBooking: hasQuickBooking, handleMakeAppointment: handleMakeAppointment, isAnonymous: (comment === null || comment === void 0 ? void 0 : comment.isAnonymous) ||
                        (Boolean(post === null || post === void 0 ? void 0 : post.isAnonymous) &&
                            ((_g = post === null || post === void 0 ? void 0 : post.author) === null || _g === void 0 ? void 0 : _g.username) === (author === null || author === void 0 ? void 0 : author.username)), hideBackground: isChatbotAuthor, userType: author === null || author === void 0 ? void 0 : author.type }, cardAuthorProps)),
                Boolean(comment === null || comment === void 0 ? void 0 : comment.isVerify) && !Boolean(comment === null || comment === void 0 ? void 0 : comment.isOppose) && (React__default["default"].createElement(VerifiedTag, { title: (_h = comment === null || comment === void 0 ? void 0 : comment.userVerify) === null || _h === void 0 ? void 0 : _h.title, name: (_j = comment === null || comment === void 0 ? void 0 : comment.userVerify) === null || _j === void 0 ? void 0 : _j.name, userId: (_k = comment === null || comment === void 0 ? void 0 : comment.userVerify) === null || _k === void 0 ? void 0 : _k.id, role: (_l = comment === null || comment === void 0 ? void 0 : comment.userVerify) === null || _l === void 0 ? void 0 : _l.role, avatar: (_m = comment === null || comment === void 0 ? void 0 : comment.userVerify) === null || _m === void 0 ? void 0 : _m.avatar, className: "verify-tag" }))),
            React__default["default"].createElement(togetherMoleculesProfileDetail.PostContent, { className: "post-content-wrapper", replyingTo: replyingTo, mentionedUser: mentionedUser, description: text, mentions: listMentions, maxChars: maxChars, disableShortenContent: disableShortenContent }),
            React__default["default"].createElement("span", null),
            React__default["default"].createElement("span", null),
            images && images.length > 0 ? (React__default["default"].createElement("div", { key: "image-preview", className: "image-preview-wrapper", "data-is-reply": true },
                React__default["default"].createElement(togetherMoleculesPostImagePreview.PostImagePreview, { images: images, authorName: author === null || author === void 0 ? void 0 : author.username }))) : null,
            (!images || images.length === 0) && link ? (React__default["default"].createElement("div", { key: "link-preview", className: "link-preview-wrapper", "data-is-reply": true },
                React__default["default"].createElement(index$9.CardLink, { url: link }))) : null,
            type !== 'most-engaging' ? (React__default["default"].createElement(React__default["default"].Fragment, null,
                isChatbotAuthor && (React__default["default"].createElement(StyledSourceList, { listUrl: comment === null || comment === void 0 ? void 0 : comment.source, categorySlug: comment === null || comment === void 0 ? void 0 : comment.categorySlug })),
                React__default["default"].createElement(treePopoverMenu.CardReactions, { type: treePopoverMenu.CardReactionType.reply, loveCount: countLikes, replyCount: mergeCountReplies, className: "post-reaction", liked: liked, isReplied: isCommented, hideCommentIcon: type === 'reply' || isChatbotAuthor, hasShare: false, onCommentClick: () => authActionWrapper(() => setShowInputComment((v) => !v)), onCommentCountClick: () => authActionWrapper(() => {
                        setShowInputComment(true);
                    }), onLikeClick: () => authActionWrapper(() => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
                        if (id) {
                            const res = yield index$1.likeUnlikeComment({
                                commentId: id,
                                setLike: !liked,
                                locale,
                            });
                            if (res.status === 1) {
                                setComment((old) => {
                                    return Object.assign(Object.assign({}, old), { liked: !liked, countLikes: old.countLikes + (!liked ? 1 : -1) });
                                });
                            }
                        }
                    })) }),
                showInputComment && (React__default["default"].createElement(index$1.InputCommentBar, { replyingId: replyingId || comment.id, replyToName: name, isReply: true, onClose: () => setShowInputComment(false), onPostSuccess: (comment) => {
                        if (type === 'reply') {
                            onPostCommentSuccess && onPostCommentSuccess(comment);
                        }
                        else {
                            addNewReply(comment);
                        }
                    }, post: post, replyingUser: author })),
                type === 'comment' && replies && replies.length > 0 ? (React__default["default"].createElement("div", { className: "comment-reply-wrapper" }, (_o = sortedReplies === null || sortedReplies === void 0 ? void 0 : sortedReplies.slice(0, maxRepliesShow)) === null || _o === void 0 ? void 0 :
                    _o.map((reply) => (React__default["default"].createElement(CardReply, { key: reply.id, comment: reply, type: "reply", className: "comment-reply-item", level: level + 1, replyingId: id, onPostCommentSuccess: addNewReply, post: post, onDeleteComment: () => {
                            setComment((old) => {
                                return Object.assign(Object.assign({}, old), { replies: old.replies.filter((r) => r.id !== reply.id), countReplies: old.countReplies - 1 });
                            });
                        }, handleMakeAppointment: handleMakeAppointment, hasQuickBookingEnable: hasQuickBookingEnable }))),
                    mergeCountReplies > maxRepliesShow && (React__default["default"].createElement(React__default["default"].Fragment, null,
                        React__default["default"].createElement(index$8.Divider, { className: "top-divider", type: "solid" }),
                        React__default["default"].createElement(index$7.Button, { className: "more-cmt", size: "lg", color: "ghost", onClick: () => setMaxRepliesShow((m) => m + COMMENT_LIMIT) },
                            t('comment.seeMoreReplies', {
                                count: mergeCountReplies - maxRepliesShow,
                            }),
                            React__default["default"].createElement("img", { className: "chevron-right", src: ChevronRightActive, loading: "lazy" })))))) : null)) : null,
            hasPopover && (React__default["default"].createElement(CardReplyPopover, { onDeleteComment: onDeleteComment, className: "popover", commentId: comment.id })))));
};

const getMostEngagingComment = (postId, locale) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
    var _a, _b, _c;
    const commentsRes = yield togetherComponentGlobalContext.callApiWithOptionalAuth(togetherComponentGlobalContext.getApiPath(togetherApiPaths.PATHS.COMMENT.LIST, {
        postId: postId,
        _locale: locale,
        sort: 'popularity',
        perPage: 1,
        withoutReply: 1,
    }), 'GET');
    return (_c = (_b = (_a = commentsRes === null || commentsRes === void 0 ? void 0 : commentsRes.data) === null || _a === void 0 ? void 0 : _a.comments) === null || _b === void 0 ? void 0 : _b.map(dataTransform.formatComment)) === null || _c === void 0 ? void 0 : _c[0];
});
const CardPost = ({ className, style, hideViewMoreComment, showMostEngaging, onCommentClick, onCommentCountClick, onMostEngagingCommentClick, onPostCommentSuccess: onPostCommentSuccessProp, disableCardLink, disableShortenContent, onDeletePost, onEditPost, post: postProp, mostEngagingComment: mostEngagingCommentProp, onDeleteComment: onDeleteCommentProp, showInputComment: propsShowInputComment, InlineCommentsComponent, hasQuickBookingEnable, handleMakeAppointment, onSaveUnsaveSuccess, cardAuthorProps, verticalReactions = false, }) => {
    const [post, setPost] = React.useState(postProp);
    const [isOpenSharePopup, setIsOpenSharePopup] = React.useState(false);
    const [mostEngagingComment, setMostEngagingComment] = React.useState(mostEngagingCommentProp);
    const { community, topics, author, slug, isPin, liked, photos, mentions, title, description, previewUrl, likesCount, commentsCount, id, commented, } = post;
    const { data: { locale, togetherUserId, userInfo, env: { isMarryBaby, togetherBasePath }, }, action: { pushNotifications }, } = React.useContext(togetherComponentGlobalContext.TogetherComponentGlobalContext);
    const isLoggedIn = Boolean(userInfo === null || userInfo === void 0 ? void 0 : userInfo.id);
    const { t } = index.useTranslations();
    const [showInputComment, setShowInputComment] = React.useState(propsShowInputComment);
    const postRelativeHref = `${togetherBasePath}/${(community === null || community === void 0 ? void 0 : community.slug) || '_'}/${slug || ''}`;
    const postHref = `${togetherComponentGlobalContext.getCurrentBaseUrl(locale)}${postRelativeHref}`;
    const { authActionWrapper } = useTogetherAuthRequiredAction.useTogetherAuthRequiredAction((community === null || community === void 0 ? void 0 : community.slug)
        ? {
            _joinCommunityIds: [community.id],
            _joinTopicIds: topics === null || topics === void 0 ? void 0 : topics.map((t) => t.id),
            // _location: postHref,
        }
        : undefined);
    const [isLikeLoading, setIsLikeLoading] = React.useState(false);
    React.useEffect(() => {
        setShowInputComment(propsShowInputComment);
    }, [propsShowInputComment]);
    const name = (author === null || author === void 0 ? void 0 : author.name) || (author === null || author === void 0 ? void 0 : author.username) || '';
    const username = (author === null || author === void 0 ? void 0 : author.username) || (author === null || author === void 0 ? void 0 : author.name) || '';
    const avatar = author === null || author === void 0 ? void 0 : author.avatar;
    const authorRole = (post === null || post === void 0 ? void 0 : post.isAnonymous) ? undefined : author === null || author === void 0 ? void 0 : author.role;
    const [hospitalInfo, setHospitalInfo] = React.useState(null);
    const [doctorInfo, setDoctorInfo] = React.useState(null);
    React.useEffect(() => {
        if (author === null || author === void 0 ? void 0 : author.hospitalId) {
            const fetchHospitalDetail = (hospitalId) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
                var _a;
                const response = yield togetherComponentGlobalContext.callApi(togetherComponentGlobalContext.getCarePath(togetherApiPaths.CARE_PATHS.GET_HOSPITAL_INFO, {
                    hospital_branch_id: hospitalId,
                    website_url: togetherComponentGlobalContext.domainLocales[locale],
                }), 'get');
                if ((_a = response === null || response === void 0 ? void 0 : response._data) === null || _a === void 0 ? void 0 : _a.branch) {
                    setHospitalInfo(response === null || response === void 0 ? void 0 : response._data.branch);
                }
            });
            fetchHospitalDetail(author.hospitalId);
        }
        if (author === null || author === void 0 ? void 0 : author.doctorId) {
            const fetchDoctorDetail = (doctorId) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
                var _b;
                const response = yield togetherComponentGlobalContext.callApi(togetherComponentGlobalContext.getCarePath(togetherApiPaths.CARE_PATHS.GET_DOCTOR_INFO, {
                    doctorId: doctorId,
                    website_url: togetherComponentGlobalContext.domainLocales[locale],
                }), 'get');
                if ((_b = response === null || response === void 0 ? void 0 : response._data) === null || _b === void 0 ? void 0 : _b.doctor) {
                    setDoctorInfo(response === null || response === void 0 ? void 0 : response._data.doctor);
                }
            });
            fetchDoctorDetail(author.doctorId);
        }
    }, [author.hospitalId, author.doctorId]);
    const isDoctorAvailable = (doctorInfo === null || doctorInfo === void 0 ? void 0 : doctorInfo.valid_outpatient) || (doctorInfo === null || doctorInfo === void 0 ? void 0 : doctorInfo.valid_telemedicine);
    const isHospitalAvailable = ((hospitalInfo === null || hospitalInfo === void 0 ? void 0 : hospitalInfo.total_available_service) ||
        (hospitalInfo === null || hospitalInfo === void 0 ? void 0 : hospitalInfo.total_available_doctor)) > 0;
    const hasQuickBooking = hasQuickBookingEnable && (isDoctorAvailable || isHospitalAvailable);
    React.useEffect(() => {
        (() => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
            if (id &&
                commentsCount &&
                showMostEngaging &&
                !(mostEngagingCommentProp === null || mostEngagingCommentProp === void 0 ? void 0 : mostEngagingCommentProp.id)) {
                const comment = yield getMostEngagingComment(id, locale);
                setMostEngagingComment(comment);
            }
        }))();
    }, [id, locale, commentsCount, showMostEngaging, mostEngagingCommentProp === null || mostEngagingCommentProp === void 0 ? void 0 : mostEngagingCommentProp.id]);
    React.useEffect(() => {
        setMostEngagingComment(mostEngagingCommentProp);
    }, [mostEngagingCommentProp === null || mostEngagingCommentProp === void 0 ? void 0 : mostEngagingCommentProp.id]);
    const onPostCommentSuccess = (comment) => {
        if (commentsCount === 0 && !(mostEngagingComment === null || mostEngagingComment === void 0 ? void 0 : mostEngagingComment.id)) {
            setMostEngagingComment(comment);
        }
        setPost((p) => (Object.assign(Object.assign({}, p), { commentsCount: p.commentsCount + 1, commented: true })));
        onPostCommentSuccessProp && onPostCommentSuccessProp(comment);
    };
    const onDeleteComment = (comment) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
        if (commentsCount > 1 &&
            (mostEngagingComment === null || mostEngagingComment === void 0 ? void 0 : mostEngagingComment.id) &&
            (mostEngagingComment === null || mostEngagingComment === void 0 ? void 0 : mostEngagingComment.id) === (comment === null || comment === void 0 ? void 0 : comment.id)) {
            const newMostEngaging = yield getMostEngagingComment(id, locale);
            setMostEngagingComment(newMostEngaging);
        }
        setPost((p) => (Object.assign(Object.assign({}, p), { commentsCount: p.commentsCount - 1 })));
        onDeleteCommentProp && onDeleteCommentProp(comment);
    });
    return (React__default["default"].createElement(useTogetherAuthRequiredAction.TogetherAuthConfigContextProvider, { defaultParams: (community === null || community === void 0 ? void 0 : community.slug)
            ? {
                _joinCommunityIds: [community.id],
                _joinTopicIds: topics === null || topics === void 0 ? void 0 : topics.map((t) => t.id),
                // _location: postHref,
            }
            : undefined },
        isOpenSharePopup && (React__default["default"].createElement(index$1.SharePopup, { url: postHref, avatar: constants.DEFAULT_IMG, text: title, onClose: () => setIsOpenSharePopup(false) })),
        React__default["default"].createElement(StyledCardPost$1, { className: className, style: style, "data-is-marrybaby": isMarryBaby },
            isPin ? React__default["default"].createElement(treePopoverMenu.LabelPin, { className: "post-pin" }) : null,
            React__default["default"].createElement("div", { style: { position: 'relative', padding: '1rem 1rem 0' } },
                React__default["default"].createElement(togetherMoleculesCardAuthor.CardAuthor, Object.assign({ avatar: avatar, name: name, username: username, url: disableCardLink ? undefined : postRelativeHref, community: community, 
                    // miniIcon="./svg/icon-tag.svg"
                    timeText: post === null || post === void 0 ? void 0 : post.createdTime, className: "post-author", role: authorRole, userId: author === null || author === void 0 ? void 0 : author.id, expertId: author === null || author === void 0 ? void 0 : author.partnerId, doctorId: author === null || author === void 0 ? void 0 : author.doctorId, hospitalId: author === null || author === void 0 ? void 0 : author.hospitalId, title: author === null || author === void 0 ? void 0 : author.title, hasQuickBooking: hasQuickBooking, handleMakeAppointment: handleMakeAppointment, "data-testid": "name", isAnonymous: !!(post === null || post === void 0 ? void 0 : post.isAnonymous), extendEle: React__default["default"].createElement(CardPostPopoverMore, { authorEmail: String(author === null || author === void 0 ? void 0 : author.email), onDeletePost: onDeletePost, shareUrl: postHref, post: post, className: "popover", onEditPost: onEditPost }) }, cardAuthorProps))),
            React__default["default"].createElement("a", { href: disableCardLink ? undefined : postRelativeHref, className: "post-content-link-wrapper" },
                title && (React__default["default"].createElement(index$3.Heading, { className: "post-content-title", as: "h2", tag: "h5", fontWeight: "bold", "data-testid": "Title of the Post" }, innertext__default["default"](title))),
                React__default["default"].createElement(togetherMoleculesProfileDetail.PostContent, { className: "post-content-wrapper", description: description, disableShortenContent: disableShortenContent, mentions: mentions, "data-testid": "Content of the Post" })),
            React__default["default"].createElement("span", null),
            React__default["default"].createElement("span", null),
            React__default["default"].createElement("div", { key: "tag-topic" }, topics && topics.length > 0 ? (React__default["default"].createElement(treePopoverMenu.TagTopic, { topics: topics, className: "post-topics" })) : null),
            React__default["default"].createElement("div", { key: "social-preview" }, (post === null || post === void 0 ? void 0 : post.introUrl) ? (React__default["default"].createElement("div", { className: `social-preview-wrapper ${!!(photos === null || photos === void 0 ? void 0 : photos.length) ? 'has-image' : ''}` },
                React__default["default"].createElement(index$a.SocialLinkPreview, { url: post.introUrl, image: post.bannerImage }))) : null),
            React__default["default"].createElement("div", { key: "image-preview" }, !!(photos === null || photos === void 0 ? void 0 : photos.length) ? (React__default["default"].createElement("div", { className: "image-preview-wrapper" },
                React__default["default"].createElement(togetherMoleculesPostImagePreview.PostImagePreview, { images: photos, authorName: author === null || author === void 0 ? void 0 : author.name, isSensitive: Boolean(post === null || post === void 0 ? void 0 : post.isSensitive) }))) : null),
            React__default["default"].createElement("div", { key: "link-preview" }, !(post === null || post === void 0 ? void 0 : post.introUrl) && !(photos === null || photos === void 0 ? void 0 : photos.length) && (previewUrl === null || previewUrl === void 0 ? void 0 : previewUrl.url) ? (React__default["default"].createElement("div", { className: "link-preview-wrapper" },
                React__default["default"].createElement(index$9.CardLink, { title: previewUrl.title, url: previewUrl.url, image: previewUrl.image }))) : null),
            React__default["default"].createElement(treePopoverMenu.CardReactions, { isMarryBaby: isMarryBaby, type: treePopoverMenu.CardReactionType.post, loveCount: likesCount, replyCount: commentsCount, className: `post-reaction ${(photos === null || photos === void 0 ? void 0 : photos.length) || (previewUrl === null || previewUrl === void 0 ? void 0 : previewUrl.url) ? 'hide-top-border' : ''}`, liked: isLikeLoading ? !liked : liked, isReplied: commented, isSaved: (post === null || post === void 0 ? void 0 : post.bookmarked) || false, onCommentClick: () => authActionWrapper(() => {
                    onCommentClick ? onCommentClick() : setShowInputComment((v) => !v);
                }), onCommentCountClick: () => {
                    authActionWrapper(() => {
                        isMarryBaby
                            ? setShowInputComment(true)
                            : onCommentCountClick
                                ? onCommentCountClick()
                                : !disableCardLink && (window.location.href = postRelativeHref);
                    });
                }, onShareClick: () => {
                    setIsOpenSharePopup(true);
                }, onLikeClick: () => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
                    authActionWrapper(() => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
                        if (!id || isLikeLoading)
                            return;
                        setIsLikeLoading(true);
                        try {
                            const res = yield index$1.likeUnlikePost({
                                id,
                                locale,
                            });
                            if ((res === null || res === void 0 ? void 0 : res.status) !== 1) {
                                pushNotifications(index$1.getDefaultFailNoti(t));
                            }
                            else {
                                setPost((p) => (Object.assign(Object.assign({}, p), { likesCount: (p.likesCount || 0) + (!p.liked ? 1 : -1), liked: !p.liked })));
                            }
                        }
                        catch (_a) {
                            pushNotifications(index$1.getDefaultFailNoti(t));
                        }
                        setIsLikeLoading(false);
                    }));
                }), onSaveClick: () => {
                    authActionWrapper(() => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
                        if (!(userInfo === null || userInfo === void 0 ? void 0 : userInfo.id) || !(post === null || post === void 0 ? void 0 : post.id))
                            return;
                        if (post === null || post === void 0 ? void 0 : post.bookmarked) {
                            const res = yield togetherComponentGlobalContext.callApiWithAuth(togetherComponentGlobalContext.getApiPath(togetherApiPaths.PATHS.BOOKMARK.DELETE, {
                                _locale: locale,
                            }), 'DELETE', {
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                data: {
                                    post_id: String(post.id),
                                },
                            });
                            if ((res === null || res === void 0 ? void 0 : res.status) === 1) {
                                pushNotifications({
                                    title: '',
                                    message: t('post.remove.success'),
                                    type: 'success',
                                    displayIcon: IconBookmark,
                                });
                                onSaveUnsaveSuccess === null || onSaveUnsaveSuccess === void 0 ? void 0 : onSaveUnsaveSuccess();
                            }
                            else {
                                pushNotifications({
                                    title: '',
                                    message: t('post.remove.failed'),
                                    type: 'danger',
                                    displayIcon: IconBookmark,
                                });
                            }
                        }
                        else {
                            const res = yield togetherComponentGlobalContext.callApiWithAuth(togetherComponentGlobalContext.getApiPath(togetherApiPaths.PATHS.BOOKMARK.CREATE, {
                                _locale: locale,
                            }), 'POST', {
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                data: {
                                    user_id: togetherUserId || userInfo.id,
                                    post_id: post.id,
                                },
                            });
                            if ((res === null || res === void 0 ? void 0 : res.status) === 1) {
                                pushNotifications({
                                    title: '',
                                    message: t('post.save.success'),
                                    type: 'success',
                                    displayIcon: IconBookmarkFill,
                                });
                                onSaveUnsaveSuccess === null || onSaveUnsaveSuccess === void 0 ? void 0 : onSaveUnsaveSuccess();
                            }
                            else {
                                pushNotifications({
                                    title: '',
                                    message: t('post.save.failed'),
                                    type: 'danger',
                                    displayIcon: IconBookmark,
                                });
                            }
                        }
                    }));
                }, onGoToUrl: (params) => {
                    const urlDetailPost = params ? `${postHref}${params}` : postHref;
                    if (!isLoggedIn) {
                        authActionWrapper(() => (window.location.href = urlDetailPost));
                    }
                    else {
                        window.location.href = urlDetailPost;
                    }
                }, showingMostEngaging: !!(showMostEngaging && (mostEngagingComment === null || mostEngagingComment === void 0 ? void 0 : mostEngagingComment.id)), isVertical: verticalReactions }),
            showInputComment && (React__default["default"].createElement(index$1.InputCommentBar, { isMainCmt: !propsShowInputComment, onClose: () => setShowInputComment(false), onPostSuccess: onPostCommentSuccess, post: post })),
            showMostEngaging && (mostEngagingComment === null || mostEngagingComment === void 0 ? void 0 : mostEngagingComment.id) ? (React__default["default"].createElement("div", { className: "most-engaging-wrapper", onClick: (e) => {
                    if (onMostEngagingCommentClick) {
                        e.stopPropagation();
                        onMostEngagingCommentClick();
                    }
                    else
                        window.location.href = postRelativeHref;
                } },
                React__default["default"].createElement(CardReply, { hasQuickBookingEnable: hasQuickBookingEnable, handleMakeAppointment: handleMakeAppointment, comment: mostEngagingComment, post: post, onDeleteComment: () => {
                        onDeleteComment && onDeleteComment(mostEngagingComment);
                    }, className: "most-engaging-comment", type: "most-engaging", key: mostEngagingComment.id, cardAuthorProps: cardAuthorProps }),
                commentsCount > 1 && !hideViewMoreComment && (React__default["default"].createElement(index$7.Button, { className: "see-more-comments", color: "ghost", size: "md" }, t('comment.seeMoreComments', {
                    count: commentsCount - 1,
                }))))) : null,
            InlineCommentsComponent)));
};

exports.CardPost = CardPost;
exports.CardPostPopoverMore = CardPostPopoverMore;
exports.CardReply = CardReply;
exports.CardReplyPopover = CardReplyPopover;
exports.SourceList = SourceList;
exports.VerifiedTag = VerifiedTag;
