// packages/block-library/src/term-name/use-term-name.js
import { store as coreStore } from "@wordpress/core-data";
import { useSelect } from "@wordpress/data";
function useTermName(termId, taxonomy) {
  const contextBasedTerm = useSelect(
    (select) => {
      if (!termId || !taxonomy) {
        return null;
      }
      return select(coreStore).getEntityRecord(
        "taxonomy",
        taxonomy,
        termId
      );
    },
    [termId, taxonomy]
  );
  const templateBasedTerm = useTemplateBasedTermData();
  const hasContext = Boolean(termId && taxonomy);
  return {
    hasContext,
    term: hasContext ? contextBasedTerm : templateBasedTerm
  };
}
function useTemplateBasedTermData() {
  const templateSlug = useSelect((select) => {
    const { getCurrentPostId, getCurrentPostType, getCurrentTemplateId } = select("core/editor");
    const currentPostType = getCurrentPostType();
    const templateId = getCurrentTemplateId() || (currentPostType === "wp_template" ? getCurrentPostId() : null);
    return templateId ? select(coreStore).getEditedEntityRecord(
      "postType",
      "wp_template",
      templateId
    )?.slug : null;
  }, []);
  const taxonomyMatches = templateSlug?.match(
    /^(category|tag|taxonomy-([^-]+))$|^(((category|tag)|taxonomy-([^-]+))-(.+))$/
  );
  let taxonomy;
  let termSlug;
  if (taxonomyMatches) {
    if (taxonomyMatches[3]) {
      taxonomy = taxonomyMatches[6] ? taxonomyMatches[6] : taxonomyMatches[4];
      termSlug = taxonomyMatches[7];
    }
    taxonomy = taxonomy === "tag" ? "post_tag" : taxonomy;
  }
  return useSelect(
    (select) => {
      if (!taxonomy || !termSlug) {
        return null;
      }
      const { getEntityRecords } = select(coreStore);
      const termRecords = getEntityRecords("taxonomy", taxonomy, {
        slug: termSlug,
        per_page: 1
      });
      if (termRecords && termRecords[0]) {
        return termRecords[0];
      }
      return null;
    },
    [taxonomy, termSlug]
  );
}
export {
  useTermName
};
//# sourceMappingURL=use-term-name.js.map
