"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _i18n = require("@wordpress/i18n");
var _components = require("@wordpress/components");
var _data = require("@wordpress/data");
var _coreData = require("@wordpress/core-data");
var _blockEditor = require("@wordpress/block-editor");
var _element = require("@wordpress/element");
var _icons = require("@wordpress/icons");
var _notices = require("@wordpress/notices");
var _store = require("../../store");
var _createNewTemplateModal = _interopRequireDefault(require("./create-new-template-modal"));
var _hooks = require("./hooks");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const POPOVER_PROPS = {
  className: 'editor-post-template__dropdown',
  placement: 'bottom-start'
};
function PostTemplateToggle({
  isOpen,
  onClick
}) {
  const templateTitle = (0, _data.useSelect)(select => {
    const templateSlug = select(_store.store).getEditedPostAttribute('template');
    const {
      supportsTemplateMode,
      availableTemplates
    } = select(_store.store).getEditorSettings();
    if (!supportsTemplateMode && availableTemplates[templateSlug]) {
      return availableTemplates[templateSlug];
    }
    const template = select(_coreData.store).canUser('create', {
      kind: 'postType',
      name: 'wp_template'
    }) && select(_store.store).getCurrentTemplateId();
    return template?.title || template?.slug || availableTemplates?.[templateSlug];
  }, []);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
    __next40pxDefaultSize: true,
    variant: "tertiary",
    "aria-expanded": isOpen,
    "aria-label": (0, _i18n.__)('Template options'),
    onClick: onClick,
    children: templateTitle !== null && templateTitle !== void 0 ? templateTitle : (0, _i18n.__)('Default template')
  });
}

/**
 * Renders the dropdown content for selecting a post template.
 *
 * @param {Object}   props         The component props.
 * @param {Function} props.onClose The function to close the dropdown.
 *
 * @return {JSX.Element} The rendered dropdown content.
 */
function PostTemplateDropdownContent({
  onClose
}) {
  var _options$find, _selectedOption$value;
  const allowSwitchingTemplate = (0, _hooks.useAllowSwitchingTemplates)();
  const {
    availableTemplates,
    fetchedTemplates,
    selectedTemplateSlug,
    canCreate,
    canEdit,
    currentTemplateId,
    onNavigateToEntityRecord,
    getEditorSettings
  } = (0, _data.useSelect)(select => {
    const {
      canUser,
      getEntityRecords
    } = select(_coreData.store);
    const editorSettings = select(_store.store).getEditorSettings();
    const canCreateTemplates = canUser('create', {
      kind: 'postType',
      name: 'wp_template'
    });
    const _currentTemplateId = select(_store.store).getCurrentTemplateId();
    return {
      availableTemplates: editorSettings.availableTemplates,
      fetchedTemplates: canCreateTemplates ? getEntityRecords('postType', 'wp_template', {
        post_type: select(_store.store).getCurrentPostType(),
        per_page: -1
      }) : undefined,
      selectedTemplateSlug: select(_store.store).getEditedPostAttribute('template'),
      canCreate: allowSwitchingTemplate && canCreateTemplates && editorSettings.supportsTemplateMode,
      canEdit: allowSwitchingTemplate && canCreateTemplates && editorSettings.supportsTemplateMode && !!_currentTemplateId,
      currentTemplateId: _currentTemplateId,
      onNavigateToEntityRecord: editorSettings.onNavigateToEntityRecord,
      getEditorSettings: select(_store.store).getEditorSettings
    };
  }, [allowSwitchingTemplate]);
  const options = (0, _element.useMemo)(() => Object.entries({
    ...availableTemplates,
    ...Object.fromEntries((fetchedTemplates !== null && fetchedTemplates !== void 0 ? fetchedTemplates : []).map(({
      slug,
      title
    }) => [slug, title.rendered]))
  }).map(([slug, title]) => ({
    value: slug,
    label: title
  })), [availableTemplates, fetchedTemplates]);
  const selectedOption = (_options$find = options.find(option => option.value === selectedTemplateSlug)) !== null && _options$find !== void 0 ? _options$find : options.find(option => !option.value); // The default option has '' value.

  const {
    editPost
  } = (0, _data.useDispatch)(_store.store);
  const {
    createSuccessNotice
  } = (0, _data.useDispatch)(_notices.store);
  const [isCreateModalOpen, setIsCreateModalOpen] = (0, _element.useState)(false);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: "editor-post-template__classic-theme-dropdown",
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.__experimentalInspectorPopoverHeader, {
      title: (0, _i18n.__)('Template'),
      help: (0, _i18n.__)('Templates define the way content is displayed when viewing your site.'),
      actions: canCreate ? [{
        icon: _icons.addTemplate,
        label: (0, _i18n.__)('Add template'),
        onClick: () => setIsCreateModalOpen(true)
      }] : [],
      onClose: onClose
    }), !allowSwitchingTemplate ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Notice, {
      status: "warning",
      isDismissible: false,
      children: (0, _i18n.__)('The posts page template cannot be changed.')
    }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.SelectControl, {
      __next40pxDefaultSize: true,
      __nextHasNoMarginBottom: true,
      hideLabelFromVision: true,
      label: (0, _i18n.__)('Template'),
      value: (_selectedOption$value = selectedOption?.value) !== null && _selectedOption$value !== void 0 ? _selectedOption$value : '',
      options: options,
      onChange: slug => editPost({
        template: slug || ''
      })
    }), canEdit && onNavigateToEntityRecord && /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button
      // TODO: Switch to `true` (40px size) if possible
      , {
        __next40pxDefaultSize: false,
        variant: "link",
        onClick: () => {
          onNavigateToEntityRecord({
            postId: currentTemplateId,
            postType: 'wp_template'
          });
          onClose();
          createSuccessNotice((0, _i18n.__)('Editing template. Changes made here affect all posts and pages that use the template.'), {
            type: 'snackbar',
            actions: [{
              label: (0, _i18n.__)('Go back'),
              onClick: () => getEditorSettings().onNavigateToPreviousEntityRecord()
            }]
          });
        },
        children: (0, _i18n.__)('Edit template')
      })
    }), isCreateModalOpen && /*#__PURE__*/(0, _jsxRuntime.jsx)(_createNewTemplateModal.default, {
      onClose: () => setIsCreateModalOpen(false)
    })]
  });
}
function ClassicThemeControl() {
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Dropdown, {
    popoverProps: POPOVER_PROPS,
    focusOnMount: true,
    renderToggle: ({
      isOpen,
      onToggle
    }) => /*#__PURE__*/(0, _jsxRuntime.jsx)(PostTemplateToggle, {
      isOpen: isOpen,
      onClick: onToggle
    }),
    renderContent: ({
      onClose
    }) => /*#__PURE__*/(0, _jsxRuntime.jsx)(PostTemplateDropdownContent, {
      onClose: onClose
    })
  });
}

/**
 * Provides a dropdown menu for selecting and managing post templates.
 *
 * The dropdown menu includes a button for toggling the menu, a list of available templates, and options for creating and editing templates.
 *
 * @return {JSX.Element} The rendered ClassicThemeControl component.
 */
var _default = exports.default = ClassicThemeControl;
//# sourceMappingURL=classic-theme.js.map