// packages/block-library/src/page-list/use-convert-to-navigation-links.js
import { createBlock } from "@wordpress/blocks";
import { useDispatch } from "@wordpress/data";
import { store as blockEditorStore } from "@wordpress/block-editor";
import { buildNavigationLinkEntityBinding } from "../navigation-link/shared";
function createNavigationLinks(pages = []) {
  const POST_TYPE_KIND = "post-type";
  const linkMap = {};
  const navigationLinks = [];
  pages.forEach(({ id, title, link: url, type, parent }) => {
    const innerBlocks = linkMap[id]?.innerBlocks ?? [];
    linkMap[id] = createBlock(
      "core/navigation-link",
      {
        id,
        label: title.rendered,
        url,
        type,
        kind: POST_TYPE_KIND,
        metadata: {
          bindings: buildNavigationLinkEntityBinding(POST_TYPE_KIND)
        }
      },
      innerBlocks
    );
    if (!parent) {
      navigationLinks.push(linkMap[id]);
    } else {
      if (!linkMap[parent]) {
        linkMap[parent] = { innerBlocks: [] };
      }
      const parentLinkInnerBlocks = linkMap[parent].innerBlocks;
      parentLinkInnerBlocks.push(linkMap[id]);
    }
  });
  return navigationLinks;
}
function findNavigationLinkById(navigationLinks, id) {
  for (const navigationLink of navigationLinks) {
    if (navigationLink.attributes.id === id) {
      return navigationLink;
    }
    if (navigationLink.innerBlocks && navigationLink.innerBlocks.length) {
      const foundNavigationLink = findNavigationLinkById(
        navigationLink.innerBlocks,
        id
      );
      if (foundNavigationLink) {
        return foundNavigationLink;
      }
    }
  }
  return null;
}
function convertToNavigationLinks(pages = [], parentPageID = null) {
  let navigationLinks = createNavigationLinks(pages);
  if (parentPageID) {
    const parentPage = findNavigationLinkById(
      navigationLinks,
      parentPageID
    );
    if (parentPage && parentPage.innerBlocks) {
      navigationLinks = parentPage.innerBlocks;
    }
  }
  const transformSubmenus = (listOfLinks) => {
    listOfLinks.forEach((block, index, listOfLinksArray) => {
      const { attributes, innerBlocks } = block;
      if (innerBlocks.length !== 0) {
        transformSubmenus(innerBlocks);
        const transformedBlock = createBlock(
          "core/navigation-submenu",
          attributes,
          innerBlocks
        );
        listOfLinksArray[index] = transformedBlock;
      }
    });
  };
  transformSubmenus(navigationLinks);
  return navigationLinks;
}
function useConvertToNavigationLinks({
  clientId,
  pages,
  parentClientId,
  parentPageID
}) {
  const { replaceBlock, selectBlock } = useDispatch(blockEditorStore);
  return () => {
    const navigationLinks = convertToNavigationLinks(pages, parentPageID);
    replaceBlock(clientId, navigationLinks);
    selectBlock(parentClientId);
  };
}
export {
  convertToNavigationLinks,
  useConvertToNavigationLinks
};
//# sourceMappingURL=use-convert-to-navigation-links.js.map
