// packages/editor/src/components/post-template/hooks.js
import { useSelect } from "@wordpress/data";
import { useMemo } from "@wordpress/element";
import { store as coreStore } from "@wordpress/core-data";
import { store as editorStore } from "../../store/index.js";
function useEditedPostContext() {
  return useSelect((select) => {
    const { getCurrentPostId, getCurrentPostType } = select(editorStore);
    return {
      postId: getCurrentPostId(),
      postType: getCurrentPostType()
    };
  }, []);
}
function useAllowSwitchingTemplates() {
  const { postType, postId } = useEditedPostContext();
  return useSelect(
    (select) => {
      const { canUser, getEntityRecord, getEntityRecords } = select(coreStore);
      const siteSettings = canUser("read", {
        kind: "root",
        name: "site"
      }) ? getEntityRecord("root", "site") : void 0;
      const isPostsPage = +postId === siteSettings?.page_for_posts;
      const isFrontPage = postType === "page" && +postId === siteSettings?.page_on_front;
      const templates = isFrontPage ? getEntityRecords("postType", "wp_template", {
        per_page: -1
      }) : [];
      const hasFrontPage = isFrontPage && !!templates?.some(({ slug }) => slug === "front-page");
      return !isPostsPage && !hasFrontPage;
    },
    [postId, postType]
  );
}
function useTemplates(postType) {
  return useSelect(
    (select) => select(coreStore).getEntityRecords("postType", "wp_template", {
      per_page: -1,
      post_type: postType
      // We look at the combined templates for now (old endpoint)
      // because posts only accept slugs for templates, not IDs.
    }),
    [postType]
  );
}
function useAvailableTemplates(postType) {
  const currentTemplateSlug = useCurrentTemplateSlug();
  const allowSwitchingTemplate = useAllowSwitchingTemplates();
  const templates = useTemplates(postType);
  return useMemo(
    () => allowSwitchingTemplate && templates?.filter(
      (template) => template.is_custom && template.slug !== currentTemplateSlug && !!template.content.raw
      // Skip empty templates.
    ),
    [templates, currentTemplateSlug, allowSwitchingTemplate]
  );
}
function useCurrentTemplateSlug() {
  const { postType, postId } = useEditedPostContext();
  const templates = useTemplates(postType);
  const entityTemplate = useSelect(
    (select) => {
      const post = select(coreStore).getEditedEntityRecord(
        "postType",
        postType,
        postId
      );
      return post?.template;
    },
    [postType, postId]
  );
  if (!entityTemplate) {
    return;
  }
  return templates?.find((template) => template.slug === entityTemplate)?.slug;
}
export {
  useAllowSwitchingTemplates,
  useAvailableTemplates,
  useCurrentTemplateSlug,
  useEditedPostContext
};
//# sourceMappingURL=hooks.js.map
