// packages/block-library/src/pattern/edit.js
import { cloneBlock } from "@wordpress/blocks";
import { useSelect, useDispatch, useRegistry } from "@wordpress/data";
import { useState, useEffect } from "@wordpress/element";
import {
  Warning,
  store as blockEditorStore,
  useBlockProps
} from "@wordpress/block-editor";
import { store as coreStore } from "@wordpress/core-data";
import { __, sprintf } from "@wordpress/i18n";
import { useParsePatternDependencies } from "./recursion-detector";
import { jsx } from "react/jsx-runtime";
var PatternEdit = ({ attributes, clientId }) => {
  const registry = useRegistry();
  const selectedPattern = useSelect(
    (select) => select(blockEditorStore).__experimentalGetParsedPattern(
      attributes.slug
    ),
    [attributes.slug]
  );
  const currentThemeStylesheet = useSelect(
    (select) => select(coreStore).getCurrentTheme()?.stylesheet,
    []
  );
  const {
    replaceBlocks,
    setBlockEditingMode,
    __unstableMarkNextChangeAsNotPersistent
  } = useDispatch(blockEditorStore);
  const { getBlockRootClientId, getBlockEditingMode } = useSelect(blockEditorStore);
  const [hasRecursionError, setHasRecursionError] = useState(false);
  const parsePatternDependencies = useParsePatternDependencies();
  function injectThemeAttributeInBlockTemplateContent(block) {
    if (block.innerBlocks.find(
      (innerBlock) => innerBlock.name === "core/template-part"
    )) {
      block.innerBlocks = block.innerBlocks.map((innerBlock) => {
        if (innerBlock.name === "core/template-part" && innerBlock.attributes.theme === void 0) {
          innerBlock.attributes.theme = currentThemeStylesheet;
        }
        return innerBlock;
      });
    }
    if (block.name === "core/template-part" && block.attributes.theme === void 0) {
      block.attributes.theme = currentThemeStylesheet;
    }
    return block;
  }
  useEffect(() => {
    if (!hasRecursionError && selectedPattern?.blocks) {
      try {
        parsePatternDependencies(selectedPattern);
      } catch (error) {
        setHasRecursionError(true);
        return;
      }
      window.queueMicrotask(() => {
        const rootClientId = getBlockRootClientId(clientId);
        const clonedBlocks = selectedPattern.blocks.map(
          (block) => cloneBlock(
            injectThemeAttributeInBlockTemplateContent(block)
          )
        );
        if (clonedBlocks.length === 1 && selectedPattern.categories?.length > 0) {
          clonedBlocks[0].attributes = {
            ...clonedBlocks[0].attributes,
            metadata: {
              ...clonedBlocks[0].attributes.metadata,
              categories: selectedPattern.categories,
              patternName: selectedPattern.name,
              name: clonedBlocks[0].attributes.metadata.name || selectedPattern.title
            }
          };
        }
        const rootEditingMode = getBlockEditingMode(rootClientId);
        registry.batch(() => {
          __unstableMarkNextChangeAsNotPersistent();
          setBlockEditingMode(rootClientId, "default");
          __unstableMarkNextChangeAsNotPersistent();
          replaceBlocks(clientId, clonedBlocks);
          __unstableMarkNextChangeAsNotPersistent();
          setBlockEditingMode(rootClientId, rootEditingMode);
        });
      });
    }
  }, [
    clientId,
    hasRecursionError,
    selectedPattern,
    __unstableMarkNextChangeAsNotPersistent,
    replaceBlocks,
    getBlockEditingMode,
    setBlockEditingMode,
    getBlockRootClientId
  ]);
  const props = useBlockProps();
  if (hasRecursionError) {
    return /* @__PURE__ */ jsx("div", { ...props, children: /* @__PURE__ */ jsx(Warning, { children: sprintf(
      // translators: A warning in which %s is the name of a pattern.
      __('Pattern "%s" cannot be rendered inside itself.'),
      selectedPattern?.name
    ) }) });
  }
  return /* @__PURE__ */ jsx("div", { ...props });
};
var edit_default = PatternEdit;
export {
  edit_default as default
};
//# sourceMappingURL=edit.js.map
