"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// packages/editor/src/components/sync-connection-error-modal/index.tsx
var sync_connection_error_modal_exports = {};
__export(sync_connection_error_modal_exports, {
  SyncConnectionErrorModal: () => SyncConnectionErrorModal
});
module.exports = __toCommonJS(sync_connection_error_modal_exports);
var import_data = require("@wordpress/data");
var import_compose = require("@wordpress/compose");
var import_blocks = require("@wordpress/blocks");
var import_core_data = require("@wordpress/core-data");
var import_block_editor = require("@wordpress/block-editor");
var import_components = require("@wordpress/components");
var import_hooks = require("@wordpress/hooks");
var import_element = require("@wordpress/element");
var import_i18n = require("@wordpress/i18n");
var import_sync_error_messages = require("../../utils/sync-error-messages.cjs");
var import_store = require("../../store/index.cjs");
var import_lock_unlock = require("../../lock-unlock.cjs");
var import_use_retry_countdown = require("./use-retry-countdown.cjs");
var import_jsx_runtime = require("react/jsx-runtime");
var { BlockCanvasCover } = (0, import_lock_unlock.unlock)(import_block_editor.privateApis);
var { retrySyncConnection } = (0, import_lock_unlock.unlock)(import_core_data.privateApis);
var INITIAL_DISCONNECTED_DEBOUNCE_MS = 2e4;
function SyncConnectionErrorModal() {
  const [hasInitialized, setHasInitialized] = (0, import_element.useState)(false);
  const [showModal, setShowModal] = (0, import_element.useState)(false);
  const [isManualRetryAvailable, setIsManualRetryAvailable] = (0, import_element.useState)(false);
  const { connectionStatus, isCollaborationEnabled, postType } = (0, import_data.useSelect)(
    (selectFn) => {
      const currentPostType = selectFn(import_store.store).getCurrentPostType();
      return {
        connectionStatus: selectFn(import_core_data.store).getSyncConnectionStatus() || null,
        isCollaborationEnabled: selectFn(
          import_store.store
        ).isCollaborationEnabledForCurrentPost(),
        postType: currentPostType ? selectFn(import_core_data.store).getPostType(currentPostType) : null
      };
    },
    []
  );
  const { onManualRetry, secondsRemaining } = (0, import_use_retry_countdown.useRetryCountdown)(connectionStatus);
  const copyButtonRef = (0, import_compose.useCopyToClipboard)(() => {
    const blocks = (0, import_data.select)(import_block_editor.store).getBlocks();
    return (0, import_blocks.serialize)(blocks);
  });
  (0, import_element.useEffect)(() => {
    const timeout = setTimeout(() => {
      setHasInitialized(true);
    }, INITIAL_DISCONNECTED_DEBOUNCE_MS);
    return () => clearTimeout(timeout);
  }, []);
  (0, import_element.useEffect)(() => {
    if ("connecting" === connectionStatus?.status) {
      return;
    }
    setIsManualRetryAvailable(
      connectionStatus !== null && "canManuallyRetry" in connectionStatus && connectionStatus.canManuallyRetry === true
    );
  }, [connectionStatus]);
  const canRetry = connectionStatus && "disconnected" === connectionStatus.status && (connectionStatus.canManuallyRetry || connectionStatus.willAutoRetryInMs);
  (0, import_element.useEffect)(() => {
    if ("connected" === connectionStatus?.status) {
      setShowModal(false);
      return;
    }
    if (connectionStatus?.status && "connecting" !== connectionStatus.status && (!canRetry || connectionStatus.backgroundRetriesFailed)) {
      setShowModal(true);
    }
  }, [connectionStatus, canRetry]);
  if (!isCollaborationEnabled || !hasInitialized || !showModal) {
    return null;
  }
  const error = connectionStatus && "error" in connectionStatus ? connectionStatus?.error : void 0;
  if (!canRetry && (0, import_hooks.applyFilters)(
    "editor.isSyncConnectionErrorHandled",
    false,
    error?.code
  ) !== false) {
    return null;
  }
  const manualRetry = isManualRetryAvailable ? () => {
    onManualRetry();
    retrySyncConnection();
  } : void 0;
  const messages = (0, import_sync_error_messages.getSyncErrorMessages)(error);
  let retryCountdownText = "";
  let isRetrying = false;
  if (secondsRemaining && secondsRemaining > 0) {
    retryCountdownText = (0, import_i18n.sprintf)(
      /* translators: %d: number of seconds until retry */
      (0, import_i18n._n)(
        "Retrying connection in %d second\u2026",
        "Retrying connection in %d seconds\u2026",
        secondsRemaining
      ),
      secondsRemaining
    );
  } else if (0 === secondsRemaining) {
    isRetrying = true;
    retryCountdownText = (0, import_i18n.__)("Retrying\u2026");
  }
  let editPostHref = "edit.php";
  if (postType?.slug) {
    editPostHref = `edit.php?post_type=${postType.slug}`;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BlockCanvasCover.Fill, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    import_components.Modal,
    {
      overlayClassName: "editor-sync-connection-error-modal",
      isDismissible: false,
      onRequestClose: () => {
      },
      shouldCloseOnClickOutside: false,
      shouldCloseOnEsc: false,
      size: "medium",
      title: messages.title,
      children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_components.__experimentalVStack, { spacing: 6, children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { children: messages.description }),
        retryCountdownText && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "editor-sync-connection-error-modal__retry-countdown", children: retryCountdownText }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_components.__experimentalHStack, { justify: "right", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_components.Button,
            {
              __next40pxDefaultSize: true,
              href: editPostHref,
              isDestructive: true,
              variant: "tertiary",
              children: (0, import_i18n.sprintf)(
                /* translators: %s: Post type name (e.g., "Posts", "Pages"). */
                (0, import_i18n.__)("Back to %s"),
                postType?.labels?.name ?? (0, import_i18n.__)("Posts")
              )
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_components.Button,
            {
              __next40pxDefaultSize: true,
              ref: copyButtonRef,
              variant: manualRetry ? "secondary" : "primary",
              children: (0, import_i18n.__)("Copy Post Content")
            }
          ),
          manualRetry && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_components.Button,
            {
              __next40pxDefaultSize: true,
              accessibleWhenDisabled: true,
              "aria-disabled": isRetrying,
              disabled: isRetrying,
              isBusy: isRetrying,
              variant: "primary",
              onClick: manualRetry,
              children: (0, import_i18n.__)("Retry")
            }
          )
        ] })
      ] })
    }
  ) });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SyncConnectionErrorModal
});
//# sourceMappingURL=index.cjs.map
