const require_runtime = require("../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../../../hooks/useEngineContext.js");
const require_locals = require("./locals.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let _ant_design_icons = require("@ant-design/icons");
let react_dom = require("react-dom");
react_dom = require_runtime.__toESM(react_dom);
require("./index.less");
//#region src/plus/pisellReservation/components/blockTimeModal/index.tsx
const { RangePicker } = antd.DatePicker;
const CLOSE_ANIMATION_MS = 180;
let activeInstance = null;
function initBlockTimeLocales(locale = "en") {
	_pisell_utils.locales.init(require_locals.default, locale || "en");
}
initBlockTimeLocales();
function getText(key) {
	return _pisell_utils.locales.getText(key);
}
/** Build the submit payload with the same shape expected by blocked-time APIs. */
function buildSubmitPayload(draft, blockedSalesChannels) {
	var _draft$timeRange, _draft$timeRange2;
	if (!((_draft$timeRange = draft.timeRange) === null || _draft$timeRange === void 0 ? void 0 : _draft$timeRange[0]) || !((_draft$timeRange2 = draft.timeRange) === null || _draft$timeRange2 === void 0 ? void 0 : _draft$timeRange2[1])) {
		antd.message.warning(getText(`pisell-reservation.block-time.warn-select-time`));
		return null;
	}
	const [start, end] = draft.timeRange;
	if (!end.isAfter(start)) {
		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) {
		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;
	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);
}
const BlockTimeModalRenderer = ({ options, onResolve, onReject }) => {
	var _context$engine, _draft$timeRange3;
	const context = require_useEngineContext.default();
	initBlockTimeLocales((context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.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, react.useRef)(false);
	const timerRef = (0, react.useRef)(null);
	const [visible, setVisible] = (0, react.useState)(false);
	const [submitLoading, setSubmitLoading] = (0, react.useState)(false);
	const [submitError, setSubmitError] = (0, react.useState)("");
	const [draft, setDraft] = (0, 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, 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, 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, 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);
		};
	}, []);
	/** Validate current draft, then optionally let the caller submit inside the modal lifecycle. */
	const handleConfirm = function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* () {
			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 = yield options.onSubmit(submitContext);
				if (submitResult === false) return;
				finishClose("resolve", require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, resultBase), {}, { submitResult }));
			} catch (error) {
				const fallbackMessage = options.submitErrorMessage || getText(`pisell-reservation.block-time.submit-failed`);
				setSubmitError((error === null || error === void 0 ? void 0 : error.message) || fallbackMessage);
			} finally {
				setSubmitLoading(false);
			}
		});
		return function handleConfirm() {
			return _ref.apply(this, arguments);
		};
	}();
	return /* @__PURE__ */ 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__ */ react.default.createElement("div", {
		className: "pisell-block-time-modal__panel",
		onMouseDown: (event) => event.stopPropagation()
	}, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-block-time-modal__header" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-block-time-modal__title" }, title), /* @__PURE__ */ 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__ */ react.default.createElement("span", { className: "pisell-block-time-modal__close-icon" }, /* @__PURE__ */ react.default.createElement(_ant_design_icons.CloseOutlined, null)))), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-block-time-modal__body" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-block-time-modal__field" }, /* @__PURE__ */ react.default.createElement("label", { className: "pisell-block-time-modal__label" }, getText(`pisell-reservation.block-time.field-title`)), /* @__PURE__ */ react.default.createElement("input", {
		value: draft.name,
		onChange: (event) => setDraft((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), {}, { name: event.target.value })),
		placeholder: getText(`pisell-reservation.block-time.placeholder-title`),
		className: "pisell-block-time-modal__control"
	})), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-block-time-modal__field" }, /* @__PURE__ */ react.default.createElement("label", { className: "pisell-block-time-modal__label" }, getText(`pisell-reservation.block-time.field-note`)), /* @__PURE__ */ react.default.createElement("input", {
		value: draft.note,
		onChange: (event) => setDraft((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), {}, { note: event.target.value })),
		placeholder: getText(`pisell-reservation.block-time.placeholder-note`),
		className: "pisell-block-time-modal__control"
	})), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-block-time-modal__field" }, /* @__PURE__ */ react.default.createElement("label", { className: "pisell-block-time-modal__label" }, getText(`pisell-reservation.block-time.field-resource`)), /* @__PURE__ */ react.default.createElement("select", {
		value: draft.resourceId,
		onChange: (event) => setDraft((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), {}, { resourceId: event.target.value })),
		className: "pisell-block-time-modal__control"
	}, /* @__PURE__ */ react.default.createElement("option", { value: "" }, getText(`pisell-reservation.block-time.no-resource`)), normalizedResources.map((resource) => /* @__PURE__ */ react.default.createElement("option", {
		key: String(resource.id),
		value: String(resource.id)
	}, resource.name)))), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-block-time-modal__field" }, /* @__PURE__ */ react.default.createElement("label", { className: "pisell-block-time-modal__label" }, getText(`pisell-reservation.block-time.field-time-range`)), /* @__PURE__ */ 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$timeRange3 = draft.timeRange) !== null && _draft$timeRange3 !== void 0 ? _draft$timeRange3 : void 0,
		onChange: (value) => setDraft((prev) => {
			var _ref2;
			return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), {}, { timeRange: (_ref2 = value) !== null && _ref2 !== void 0 ? _ref2 : null });
		})
	}))), submitError && /* @__PURE__ */ react.default.createElement("div", { className: "pisell-block-time-modal__error" }, submitError), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-block-time-modal__footer" }, /* @__PURE__ */ react.default.createElement("button", {
		type: "button",
		disabled: submitLoading,
		onClick: () => handleCancel("cancel"),
		className: "pisell-block-time-modal__ghost-button"
	}, cancelText), /* @__PURE__ */ 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))));
};
/** Open the blocked-time modal as a Promise-based singleton. */
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);
		};
		react_dom.default.render(/* @__PURE__ */ react.default.createElement(BlockTimeModalRenderer, {
			options,
			onResolve: handleResolve,
			onReject: handleReject
		}), container);
	});
}
function close(reason) {
	closeActiveInstance(reason || { type: "programmatic-close" });
}
const blockTimeModal = {
	open,
	close
};
//#endregion
exports.default = blockTimeModal;
