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);

// src/plus/pisellReservation/components/blockTimeModal/index.tsx
var blockTimeModal_exports = {};
__export(blockTimeModal_exports, {
  closeBlockTimeModal: () => close,
  default: () => blockTimeModal_default,
  openBlockTimeModal: () => open
});
module.exports = __toCommonJS(blockTimeModal_exports);
var import_react = __toESM(require("react"));
var import_react_dom = __toESM(require("react-dom"));
var import_icons = require("@ant-design/icons");
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_locals = __toESM(require("./locals"));
var import_index = require("./index.less");
var { RangePicker } = import_antd.DatePicker;
var CLOSE_ANIMATION_MS = 180;
var activeInstance = null;
function initBlockTimeLocales(locale = "en") {
  import_utils.locales.init(import_locals.default, locale || "en");
}
initBlockTimeLocales();
function getText(key) {
  return import_utils.locales.getText(key);
}
function buildSubmitPayload(draft, blockedSalesChannels) {
  var _a, _b;
  if (!((_a = draft.timeRange) == null ? void 0 : _a[0]) || !((_b = draft.timeRange) == null ? void 0 : _b[1])) {
    import_antd.message.warning(getText(`pisell-reservation.block-time.warn-select-time`));
    return null;
  }
  const [start, end] = draft.timeRange;
  if (!end.isAfter(start)) {
    import_antd.message.warning(getText(`pisell-reservation.block-time.warn-end-after-start`));
    return null;
  }
  const resourceId = Number(draft.resourceId);
  if (!Number.isFinite(resourceId) || resourceId <= 0) {
    import_antd.message.warning(getText(`pisell-reservation.block-time.warn-select-resource`));
    return null;
  }
  return {
    name: draft.name.trim() || getText(`pisell-reservation.block-time.default-title`),
    note: draft.note.trim(),
    resource_ids: [resourceId],
    blocked_sales_channels: blockedSalesChannels,
    start_time: start.format("YYYY-MM-DD HH:mm"),
    end_time: end.format("YYYY-MM-DD HH:mm")
  };
}
function destroyActiveInstance() {
  if (!activeInstance) {
    return;
  }
  const { container } = activeInstance;
  activeInstance = null;
  import_react_dom.default.unmountComponentAtNode(container);
  if (document.body.contains(container)) {
    document.body.removeChild(container);
  }
}
function closeActiveInstance(reason) {
  if (!activeInstance) {
    return;
  }
  const { reject } = activeInstance;
  destroyActiveInstance();
  reject(reason);
}
var BlockTimeModalRenderer = ({
  options,
  onResolve,
  onReject
}) => {
  var _a, _b;
  const context = (0, import_useEngineContext.default)();
  initBlockTimeLocales(((_b = (_a = context == null ? void 0 : context.engine) == null ? void 0 : _a.props) == null ? void 0 : _b.locale) || "en");
  const {
    resources,
    initialName,
    initialNote = "",
    initialResourceId,
    initialTimeRange = null,
    blockedSalesChannels = ["online_store"],
    minuteStep = 60,
    title = getText(`pisell-reservation.block-time.title`),
    confirmText = getText(`pisell-reservation.block-time.confirm`),
    cancelText = getText(`pisell-reservation.block-time.cancel`),
    closeOnBackdrop = true,
    zIndex = 1072,
    theme = "dark"
  } = options;
  const closedRef = (0, import_react.useRef)(false);
  const timerRef = (0, import_react.useRef)(null);
  const [visible, setVisible] = (0, import_react.useState)(false);
  const [submitLoading, setSubmitLoading] = (0, import_react.useState)(false);
  const [submitError, setSubmitError] = (0, import_react.useState)("");
  const [draft, setDraft] = (0, import_react.useState)({
    name: initialName || getText(`pisell-reservation.block-time.default-title`),
    note: initialNote,
    resourceId: initialResourceId === void 0 || initialResourceId === null ? "" : String(initialResourceId),
    timeRange: initialTimeRange
  });
  const normalizedMinuteStep = (0, import_react.useMemo)(() => {
    const next = Math.round(Number(minuteStep));
    if (!Number.isFinite(next) || next < 1) {
      return 60;
    }
    return next >= 60 ? 60 : Math.max(1, next);
  }, [minuteStep]);
  const normalizedResources = (0, import_react.useMemo)(
    () => Array.isArray(resources) ? resources : [],
    [resources]
  );
  const isLight = theme === "light";
  const finishClose = (type, payload) => {
    if (closedRef.current) {
      return;
    }
    closedRef.current = true;
    setVisible(false);
    timerRef.current = window.setTimeout(() => {
      if (type === "resolve") {
        onResolve(payload);
      } else {
        onReject(payload);
      }
    }, CLOSE_ANIMATION_MS);
  };
  const handleCancel = (reasonType) => {
    if (submitLoading) {
      return;
    }
    finishClose("reject", { type: reasonType });
  };
  (0, import_react.useEffect)(() => {
    const rafId = window.requestAnimationFrame(() => {
      setVisible(true);
    });
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKeyDown = (event) => {
      if (event.key === "Escape") {
        handleCancel("escape");
      }
    };
    window.addEventListener("keydown", onKeyDown);
    return () => {
      window.cancelAnimationFrame(rafId);
      window.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = previousOverflow;
      if (timerRef.current) {
        window.clearTimeout(timerRef.current);
      }
    };
  }, []);
  const handleConfirm = async () => {
    if (submitLoading) {
      return;
    }
    setSubmitError("");
    const submitPayload = buildSubmitPayload(draft, blockedSalesChannels);
    if (!submitPayload) {
      return;
    }
    const resultBase = {
      draft,
      submitPayload
    };
    if (!options.onSubmit) {
      finishClose("resolve", resultBase);
      return;
    }
    setSubmitLoading(true);
    try {
      const submitContext = {
        draft,
        submitPayload,
        options
      };
      const submitResult = await options.onSubmit(submitContext);
      if (submitResult === false) {
        return;
      }
      finishClose("resolve", {
        ...resultBase,
        submitResult
      });
    } catch (error) {
      const fallbackMessage = options.submitErrorMessage || getText(`pisell-reservation.block-time.submit-failed`);
      setSubmitError((error == null ? void 0 : error.message) || fallbackMessage);
    } finally {
      setSubmitLoading(false);
    }
  };
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: [
        "pisell-block-time-modal",
        visible ? "is-visible" : "",
        isLight ? "is-light" : "is-dark"
      ].filter(Boolean).join(" "),
      style: { zIndex },
      onMouseDown: (event) => {
        if (event.target === event.currentTarget && closeOnBackdrop) {
          handleCancel("backdrop");
        }
      }
    },
    /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "pisell-block-time-modal__panel",
        onMouseDown: (event) => event.stopPropagation()
      },
      /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-block-time-modal__header" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-block-time-modal__title" }, title), /* @__PURE__ */ import_react.default.createElement(
        "button",
        {
          type: "button",
          "aria-label": getText(`pisell-reservation.block-time.close-aria`),
          onClick: () => handleCancel("cancel"),
          className: "pisell-block-time-modal__close"
        },
        /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-block-time-modal__close-icon" }, /* @__PURE__ */ import_react.default.createElement(import_icons.CloseOutlined, null))
      )),
      /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-block-time-modal__body" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-block-time-modal__field" }, /* @__PURE__ */ import_react.default.createElement("label", { className: "pisell-block-time-modal__label" }, getText(`pisell-reservation.block-time.field-title`)), /* @__PURE__ */ import_react.default.createElement(
        "input",
        {
          value: draft.name,
          onChange: (event) => setDraft((prev) => ({
            ...prev,
            name: event.target.value
          })),
          placeholder: getText(`pisell-reservation.block-time.placeholder-title`),
          className: "pisell-block-time-modal__control"
        }
      )), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-block-time-modal__field" }, /* @__PURE__ */ import_react.default.createElement("label", { className: "pisell-block-time-modal__label" }, getText(`pisell-reservation.block-time.field-note`)), /* @__PURE__ */ import_react.default.createElement(
        "input",
        {
          value: draft.note,
          onChange: (event) => setDraft((prev) => ({
            ...prev,
            note: event.target.value
          })),
          placeholder: getText(`pisell-reservation.block-time.placeholder-note`),
          className: "pisell-block-time-modal__control"
        }
      )), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-block-time-modal__field" }, /* @__PURE__ */ import_react.default.createElement("label", { className: "pisell-block-time-modal__label" }, getText(`pisell-reservation.block-time.field-resource`)), /* @__PURE__ */ import_react.default.createElement(
        "select",
        {
          value: draft.resourceId,
          onChange: (event) => setDraft((prev) => ({
            ...prev,
            resourceId: event.target.value
          })),
          className: "pisell-block-time-modal__control"
        },
        /* @__PURE__ */ import_react.default.createElement("option", { value: "" }, getText(`pisell-reservation.block-time.no-resource`)),
        normalizedResources.map((resource) => /* @__PURE__ */ import_react.default.createElement("option", { key: String(resource.id), value: String(resource.id) }, resource.name))
      )), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-block-time-modal__field" }, /* @__PURE__ */ import_react.default.createElement("label", { className: "pisell-block-time-modal__label" }, getText(`pisell-reservation.block-time.field-time-range`)), /* @__PURE__ */ import_react.default.createElement(
        RangePicker,
        {
          ...{
            className: "pisell-block-time-modal__range",
            style: { width: "100%" },
            showTime: {
              format: "HH:mm",
              minuteStep: normalizedMinuteStep
            },
            format: "YYYY-MM-DD HH:mm",
            value: draft.timeRange ?? void 0,
            onChange: (value) => setDraft((prev) => ({
              ...prev,
              timeRange: value ?? null
            }))
          }
        }
      ))),
      submitError && /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-block-time-modal__error" }, submitError),
      /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-block-time-modal__footer" }, /* @__PURE__ */ import_react.default.createElement(
        "button",
        {
          type: "button",
          disabled: submitLoading,
          onClick: () => handleCancel("cancel"),
          className: "pisell-block-time-modal__ghost-button"
        },
        cancelText
      ), /* @__PURE__ */ import_react.default.createElement(
        "button",
        {
          type: "button",
          disabled: submitLoading,
          onClick: () => void handleConfirm(),
          className: "pisell-block-time-modal__primary-button"
        },
        submitLoading ? getText(`pisell-reservation.block-time.submitting`) : confirmText
      ))
    )
  );
};
function open(options) {
  if (typeof window === "undefined" || typeof document === "undefined") {
    return Promise.reject({
      type: "programmatic-close",
      message: getText(`pisell-reservation.block-time.browser-only`)
    });
  }
  if (activeInstance) {
    closeActiveInstance({
      type: "replaced",
      message: getText(`pisell-reservation.block-time.replaced`)
    });
  }
  const container = document.createElement("div");
  document.body.appendChild(container);
  return new Promise((resolve, reject) => {
    activeInstance = {
      container,
      reject
    };
    const handleResolve = (result) => {
      destroyActiveInstance();
      resolve(result);
    };
    const handleReject = (reason) => {
      destroyActiveInstance();
      reject(reason);
    };
    import_react_dom.default.render(
      /* @__PURE__ */ import_react.default.createElement(
        BlockTimeModalRenderer,
        {
          options,
          onResolve: handleResolve,
          onReject: handleReject
        }
      ),
      container
    );
  });
}
function close(reason) {
  closeActiveInstance(
    reason || {
      type: "programmatic-close"
    }
  );
}
var blockTimeModal = {
  open,
  close
};
var blockTimeModal_default = blockTimeModal;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  closeBlockTimeModal,
  openBlockTimeModal
});
