// packages/block-library/src/comment-template/hooks.js
import { useState, useEffect, useMemo } from "@wordpress/element";
import { useSelect } from "@wordpress/data";
import { store as blockEditorStore } from "@wordpress/block-editor";
import { addQueryArgs } from "@wordpress/url";
import apiFetch from "@wordpress/api-fetch";
var MAX_COMMENTS_PER_PAGE = 100;
var useCommentQueryArgs = ({ postId }) => {
  const queryArgs = {
    status: "approve",
    order: "asc",
    context: "embed",
    parent: 0,
    _embed: "children"
  };
  const {
    pageComments,
    commentsPerPage,
    defaultCommentsPage: defaultPage
  } = useSelect((select) => {
    const { getSettings } = select(blockEditorStore);
    const { __experimentalDiscussionSettings } = getSettings();
    return __experimentalDiscussionSettings;
  });
  const perPage = pageComments ? Math.min(commentsPerPage, MAX_COMMENTS_PER_PAGE) : MAX_COMMENTS_PER_PAGE;
  const page = useDefaultPageIndex({
    defaultPage,
    postId,
    perPage,
    queryArgs
  });
  return useMemo(() => {
    return page ? {
      ...queryArgs,
      post: postId,
      per_page: perPage,
      page
    } : null;
  }, [postId, perPage, page]);
};
var useDefaultPageIndex = ({ defaultPage, postId, perPage, queryArgs }) => {
  const [defaultPages, setDefaultPages] = useState({});
  const key = `${postId}_${perPage}`;
  const page = defaultPages[key] || 0;
  useEffect(() => {
    if (page || defaultPage !== "newest") {
      return;
    }
    apiFetch({
      path: addQueryArgs("/wp/v2/comments", {
        ...queryArgs,
        post: postId,
        per_page: perPage,
        _fields: "id"
      }),
      method: "HEAD",
      parse: false
    }).then((res) => {
      const pages = parseInt(res.headers.get("X-WP-TotalPages"));
      setDefaultPages({
        ...defaultPages,
        [key]: pages <= 1 ? 1 : pages
        // If there are 0 pages, it means that there are no comments, but there is no 0th page.
      });
    }).catch(() => {
      setDefaultPages({
        ...defaultPages,
        [key]: 1
      });
    });
  }, [defaultPage, postId, perPage, setDefaultPages]);
  return defaultPage === "newest" ? page : 1;
};
var useCommentTree = (topLevelComments) => {
  const commentTree = useMemo(
    () => topLevelComments?.map(({ id, _embedded }) => {
      const [children] = _embedded?.children || [[]];
      return {
        commentId: id,
        children: children.map((child) => ({
          commentId: child.id
        }))
      };
    }),
    [topLevelComments]
  );
  return commentTree;
};
export {
  useCommentQueryArgs,
  useCommentTree
};
//# sourceMappingURL=hooks.js.map
