// packages/block-library/src/template-part/edit/utils/transformers.js
import {
  parse,
  cloneBlock,
  createBlock,
  getGroupingBlockName,
  getPossibleBlockTransformations,
  switchToBlockType
} from "@wordpress/blocks";
function transformWidgetToBlock(widget) {
  if (widget.id_base !== "block") {
    let attributes;
    if (widget._embedded.about[0].is_multi) {
      attributes = {
        idBase: widget.id_base,
        instance: widget.instance
      };
    } else {
      attributes = {
        id: widget.id
      };
    }
    return switchLegacyWidgetType(
      createBlock("core/legacy-widget", attributes)
    );
  }
  const parsedBlocks = parse(widget.instance.raw.content, {
    __unstableSkipAutop: true
  });
  if (!parsedBlocks.length) {
    return void 0;
  }
  const block = parsedBlocks[0];
  if (block.name === "core/widget-group") {
    return createBlock(
      getGroupingBlockName(),
      void 0,
      transformInnerBlocks(block.innerBlocks)
    );
  }
  if (block.innerBlocks.length > 0) {
    return cloneBlock(
      block,
      void 0,
      transformInnerBlocks(block.innerBlocks)
    );
  }
  return block;
}
function switchLegacyWidgetType(block) {
  const transforms = getPossibleBlockTransformations([block]).filter(
    (item) => {
      if (!item.transforms) {
        return true;
      }
      const hasWildCardFrom = item.transforms?.from?.find(
        (from) => from.blocks && from.blocks.includes("*")
      );
      const hasWildCardTo = item.transforms?.to?.find(
        (to) => to.blocks && to.blocks.includes("*")
      );
      return !hasWildCardFrom && !hasWildCardTo;
    }
  );
  if (!transforms.length) {
    return void 0;
  }
  return switchToBlockType(block, transforms[0].name);
}
function transformInnerBlocks(innerBlocks = []) {
  return innerBlocks.flatMap((block) => {
    if (block.name === "core/legacy-widget") {
      return switchLegacyWidgetType(block);
    }
    return createBlock(
      block.name,
      block.attributes,
      transformInnerBlocks(block.innerBlocks)
    );
  }).filter((block) => !!block);
}
export {
  transformWidgetToBlock
};
//# sourceMappingURL=transformers.js.map
