// packages/block-library/src/navigation/edit/unsaved-inner-blocks.js
import { useInnerBlocksProps } from "@wordpress/block-editor";
import { Disabled } from "@wordpress/components";
import { store as coreStore } from "@wordpress/core-data";
import { useSelect } from "@wordpress/data";
import { useContext, useEffect, useRef } from "@wordpress/element";
import { areBlocksDirty } from "./are-blocks-dirty";
import { DEFAULT_BLOCK, SELECT_NAVIGATION_MENUS_ARGS } from "../constants";
import { jsx } from "react/jsx-runtime";
var EMPTY_OBJECT = {};
function UnsavedInnerBlocks({
  blocks,
  createNavigationMenu,
  hasSelection
}) {
  const originalBlocksRef = useRef();
  useEffect(() => {
    if (!originalBlocksRef?.current) {
      originalBlocksRef.current = blocks;
    }
  }, [blocks]);
  const innerBlocksAreDirty = areBlocksDirty(
    originalBlocksRef?.current,
    blocks
  );
  const isDisabled = useContext(Disabled.Context);
  const innerBlocksProps = useInnerBlocksProps(
    {
      className: "wp-block-navigation__container"
    },
    {
      renderAppender: hasSelection ? void 0 : false,
      defaultBlock: DEFAULT_BLOCK,
      directInsert: true
    }
  );
  const { isSaving, hasResolvedAllNavigationMenus } = useSelect(
    (select) => {
      if (isDisabled) {
        return EMPTY_OBJECT;
      }
      const { hasFinishedResolution, isSavingEntityRecord } = select(coreStore);
      return {
        isSaving: isSavingEntityRecord("postType", "wp_navigation"),
        hasResolvedAllNavigationMenus: hasFinishedResolution(
          "getEntityRecords",
          SELECT_NAVIGATION_MENUS_ARGS
        )
      };
    },
    [isDisabled]
  );
  useEffect(() => {
    if (isDisabled || isSaving || !hasResolvedAllNavigationMenus || !hasSelection || !innerBlocksAreDirty) {
      return;
    }
    createNavigationMenu(null, blocks);
  }, [
    blocks,
    createNavigationMenu,
    isDisabled,
    isSaving,
    hasResolvedAllNavigationMenus,
    innerBlocksAreDirty,
    hasSelection
  ]);
  const Wrapper = isSaving ? Disabled : "div";
  return /* @__PURE__ */ jsx(Wrapper, { ...innerBlocksProps });
}
export {
  UnsavedInnerBlocks as default
};
//# sourceMappingURL=unsaved-inner-blocks.js.map
