"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var screen_revisions_exports = {};
__export(screen_revisions_exports, {
  default: () => screen_revisions_default
});
module.exports = __toCommonJS(screen_revisions_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_i18n = require("@wordpress/i18n");
var import_components = require("@wordpress/components");
var import_data = require("@wordpress/data");
var import_element = require("@wordpress/element");
var import_block_editor = require("@wordpress/block-editor");
var import_header = __toESM(require("../header"));
var import_lock_unlock = require("../../../lock-unlock");
var import_revisions = __toESM(require("../../revisions"));
var import_store = require("../../../store");
var import_use_global_styles_revisions = __toESM(require("./use-global-styles-revisions"));
var import_revisions_buttons = __toESM(require("./revisions-buttons"));
var import_style_book = __toESM(require("../../style-book"));
var import_pagination = __toESM(require("../../pagination"));
const { GlobalStylesContext, areGlobalStyleConfigsEqual } = (0, import_lock_unlock.unlock)(
  import_block_editor.privateApis
);
const PAGE_SIZE = 10;
function ScreenRevisions() {
  const { user: currentEditorGlobalStyles, setUserConfig } = (0, import_element.useContext)(GlobalStylesContext);
  const { blocks, editorCanvasContainerView } = (0, import_data.useSelect)(
    (select) => ({
      editorCanvasContainerView: (0, import_lock_unlock.unlock)(
        select(import_store.store)
      ).getEditorCanvasContainerView(),
      blocks: select(import_block_editor.store).getBlocks()
    }),
    []
  );
  const [currentPage, setCurrentPage] = (0, import_element.useState)(1);
  const [currentRevisions, setCurrentRevisions] = (0, import_element.useState)([]);
  const { revisions, isLoading, hasUnsavedChanges, revisionsCount } = (0, import_use_global_styles_revisions.default)({
    query: {
      per_page: PAGE_SIZE,
      page: currentPage
    }
  });
  const numPages = Math.ceil(revisionsCount / PAGE_SIZE);
  const [currentlySelectedRevision, setCurrentlySelectedRevision] = (0, import_element.useState)(currentEditorGlobalStyles);
  const [
    isLoadingRevisionWithUnsavedChanges,
    setIsLoadingRevisionWithUnsavedChanges
  ] = (0, import_element.useState)(false);
  const { setEditorCanvasContainerView } = (0, import_lock_unlock.unlock)(
    (0, import_data.useDispatch)(import_store.store)
  );
  const selectedRevisionMatchesEditorStyles = areGlobalStyleConfigsEqual(
    currentlySelectedRevision,
    currentEditorGlobalStyles
  );
  const onCloseRevisions = () => {
    const canvasContainerView = editorCanvasContainerView === "global-styles-revisions:style-book" ? "style-book" : void 0;
    setEditorCanvasContainerView(canvasContainerView);
  };
  const restoreRevision = (revision) => {
    setUserConfig(() => revision);
    setIsLoadingRevisionWithUnsavedChanges(false);
    onCloseRevisions();
  };
  (0, import_element.useEffect)(() => {
    if (!isLoading && revisions.length) {
      setCurrentRevisions(revisions);
    }
  }, [revisions, isLoading]);
  const firstRevision = revisions[0];
  const currentlySelectedRevisionId = currentlySelectedRevision?.id;
  const shouldSelectFirstItem = !!firstRevision?.id && !selectedRevisionMatchesEditorStyles && !currentlySelectedRevisionId;
  (0, import_element.useEffect)(() => {
    if (shouldSelectFirstItem) {
      setCurrentlySelectedRevision(firstRevision);
    }
  }, [shouldSelectFirstItem, firstRevision]);
  const isLoadButtonEnabled = !!currentlySelectedRevisionId && currentlySelectedRevisionId !== "unsaved" && !selectedRevisionMatchesEditorStyles;
  const hasRevisions = !!currentRevisions.length;
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_header.default,
      {
        title: revisionsCount && // translators: %s: number of revisions.
        (0, import_i18n.sprintf)((0, import_i18n.__)("Revisions (%s)"), revisionsCount),
        description: (0, import_i18n.__)(
          `Click on previously saved styles to preview them. To restore a selected version to the editor, hit "Apply." When you're ready, use the Save button to save your changes.`
        ),
        onBack: onCloseRevisions
      }
    ),
    !hasRevisions && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.Spinner, { className: "edit-site-global-styles-screen-revisions__loading" }),
    hasRevisions && (editorCanvasContainerView === "global-styles-revisions:style-book" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_style_book.default,
      {
        userConfig: currentlySelectedRevision,
        isSelected: () => {
        },
        onClose: () => {
          setEditorCanvasContainerView(
            "global-styles-revisions"
          );
        }
      }
    ) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_revisions.default,
      {
        blocks,
        userConfig: currentlySelectedRevision,
        closeButtonLabel: (0, import_i18n.__)("Close revisions")
      }
    )),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_revisions_buttons.default,
      {
        onChange: setCurrentlySelectedRevision,
        selectedRevisionId: currentlySelectedRevisionId,
        userRevisions: currentRevisions,
        canApplyRevision: isLoadButtonEnabled,
        onApplyRevision: () => hasUnsavedChanges ? setIsLoadingRevisionWithUnsavedChanges(true) : restoreRevision(currentlySelectedRevision)
      }
    ),
    numPages > 1 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "edit-site-global-styles-screen-revisions__footer", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_pagination.default,
      {
        className: "edit-site-global-styles-screen-revisions__pagination",
        currentPage,
        numPages,
        changePage: setCurrentPage,
        totalItems: revisionsCount,
        disabled: isLoading,
        label: (0, import_i18n.__)("Global Styles pagination")
      }
    ) }),
    isLoadingRevisionWithUnsavedChanges && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_components.__experimentalConfirmDialog,
      {
        isOpen: isLoadingRevisionWithUnsavedChanges,
        confirmButtonText: (0, import_i18n.__)("Apply"),
        onConfirm: () => restoreRevision(currentlySelectedRevision),
        onCancel: () => setIsLoadingRevisionWithUnsavedChanges(false),
        size: "medium",
        children: (0, import_i18n.__)(
          "Are you sure you want to apply this revision? Any unsaved changes will be lost."
        )
      }
    )
  ] });
}
var screen_revisions_default = ScreenRevisions;
//# sourceMappingURL=index.js.map
