/* wp:polyfill */
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = StartTemplateOptions;
var _components = require("@wordpress/components");
var _i18n = require("@wordpress/i18n");
var _element = require("@wordpress/element");
var _blockEditor = require("@wordpress/block-editor");
var _data = require("@wordpress/data");
var _blocks = require("@wordpress/blocks");
var _coreData = require("@wordpress/core-data");
var _store = require("../../store");
var _constants = require("../../store/constants");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

function useFallbackTemplateContent(slug, isCustom = false) {
  return (0, _data.useSelect)(select => {
    const {
      getEntityRecord,
      getDefaultTemplateId
    } = select(_coreData.store);
    const templateId = getDefaultTemplateId({
      slug,
      is_custom: isCustom,
      ignore_empty: true
    });
    return templateId ? getEntityRecord('postType', _constants.TEMPLATE_POST_TYPE, templateId)?.content?.raw : undefined;
  }, [slug, isCustom]);
}
function useStartPatterns(fallbackContent) {
  const {
    slug,
    patterns
  } = (0, _data.useSelect)(select => {
    const {
      getCurrentPostType,
      getCurrentPostId
    } = select(_store.store);
    const {
      getEntityRecord,
      getBlockPatterns
    } = select(_coreData.store);
    const postId = getCurrentPostId();
    const postType = getCurrentPostType();
    const record = getEntityRecord('postType', postType, postId);
    return {
      slug: record.slug,
      patterns: getBlockPatterns()
    };
  }, []);
  const currentThemeStylesheet = (0, _data.useSelect)(select => select(_coreData.store).getCurrentTheme().stylesheet);

  // Duplicated from packages/block-library/src/pattern/edit.js.
  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 === undefined) {
          innerBlock.attributes.theme = currentThemeStylesheet;
        }
        return innerBlock;
      });
    }
    if (block.name === 'core/template-part' && block.attributes.theme === undefined) {
      block.attributes.theme = currentThemeStylesheet;
    }
    return block;
  }
  return (0, _element.useMemo)(() => {
    // filter patterns that are supposed to be used in the current template being edited.
    return [{
      name: 'fallback',
      blocks: (0, _blocks.parse)(fallbackContent),
      title: (0, _i18n.__)('Fallback content')
    }, ...patterns.filter(pattern => {
      return Array.isArray(pattern.templateTypes) && pattern.templateTypes.some(templateType => slug.startsWith(templateType));
    }).map(pattern => {
      return {
        ...pattern,
        blocks: (0, _blocks.parse)(pattern.content).map(block => injectThemeAttributeInBlockTemplateContent(block))
      };
    })];
  }, [fallbackContent, slug, patterns]);
}
function PatternSelection({
  fallbackContent,
  onChoosePattern,
  postType
}) {
  const [,, onChange] = (0, _coreData.useEntityBlockEditor)('postType', postType);
  const blockPatterns = useStartPatterns(fallbackContent);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.__experimentalBlockPatternsList, {
    blockPatterns: blockPatterns,
    onClickPattern: (pattern, blocks) => {
      onChange(blocks, {
        selection: undefined
      });
      onChoosePattern();
    }
  });
}
function StartModal({
  slug,
  isCustom,
  onClose,
  postType
}) {
  const fallbackContent = useFallbackTemplateContent(slug, isCustom);
  if (!fallbackContent) {
    return null;
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Modal, {
    className: "editor-start-template-options__modal",
    title: (0, _i18n.__)('Choose a pattern'),
    closeLabel: (0, _i18n.__)('Cancel'),
    focusOnMount: "firstElement",
    onRequestClose: onClose,
    isFullScreen: true,
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "editor-start-template-options__modal-content",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(PatternSelection, {
        fallbackContent: fallbackContent,
        slug: slug,
        isCustom: isCustom,
        postType: postType,
        onChoosePattern: () => {
          onClose();
        }
      })
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Flex, {
      className: "editor-start-template-options__modal__actions",
      justify: "flex-end",
      expanded: false,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.FlexItem, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
          __next40pxDefaultSize: true,
          variant: "tertiary",
          onClick: onClose,
          children: (0, _i18n.__)('Skip')
        })
      })
    })]
  });
}
function StartTemplateOptions() {
  const [isClosed, setIsClosed] = (0, _element.useState)(false);
  const {
    shouldOpenModal,
    slug,
    isCustom,
    postType,
    postId
  } = (0, _data.useSelect)(select => {
    const {
      getCurrentPostType,
      getCurrentPostId
    } = select(_store.store);
    const _postType = getCurrentPostType();
    const _postId = getCurrentPostId();
    const {
      getEditedEntityRecord,
      hasEditsForEntityRecord
    } = select(_coreData.store);
    const templateRecord = getEditedEntityRecord('postType', _postType, _postId);
    const hasEdits = hasEditsForEntityRecord('postType', _postType, _postId);
    return {
      shouldOpenModal: !hasEdits && '' === templateRecord.content && _constants.TEMPLATE_POST_TYPE === _postType,
      slug: templateRecord.slug,
      isCustom: templateRecord.is_custom,
      postType: _postType,
      postId: _postId
    };
  }, []);
  (0, _element.useEffect)(() => {
    // Should reset the modal state when navigating to a new page/post.
    setIsClosed(false);
  }, [postType, postId]);
  if (!shouldOpenModal || isClosed) {
    return null;
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(StartModal, {
    slug: slug,
    isCustom: isCustom,
    postType: postType,
    onClose: () => setIsClosed(true)
  });
}
//# sourceMappingURL=index.js.map