const require_runtime = require("../../../../_virtual/_rolldown/runtime.js");
const require_useEngineContext = require("../../../../hooks/useEngineContext.js");
const require_index = require("../../../../pro/compensatedPisellContainer/index.js");
const require_withResponsive = require("../../../../responsive/withResponsive.js");
const require_bookingDate = require("../../../../plus/salesSdk/utils/bookingDate.js");
const require_SalesSdkBookingContext = require("../../../../plus/salesSdk/context/SalesSdkBookingContext.js");
const require_index$1 = require("../../locales/index.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
let classnames = require("classnames");
classnames = require_runtime.__toESM(classnames);
let ahooks = require("ahooks");
let _ant_design_icons = require("@ant-design/icons");
require("./index.less");
//#region src/components/bigSale/components/TimeBar/index.tsx
const DISPLAY_DATE_FORMAT = "YYYY-MM-DD";
function resolveDate(rawDate) {
	if (rawDate && (0, dayjs.default)(rawDate).isValid()) return (0, dayjs.default)(rawDate);
	return (0, dayjs.default)();
}
/**
* BigSaleTimeBar 只同步 SalesSdk BookingContext，不依赖 ticketBooking 的 mini-redux。
*/
const BigSaleTimeBar = ({ dataSource, productLoadParams, locale = "en", orderId, variant = "desktop", mobileDrawerOpen = false, onMobileDrawerClose }) => {
	var _context$appHelper, _context$appHelper$ge, _context$appHelper$ge2, _dataSource$sales$tem, _dataSource$sales$sal;
	const context = require_useEngineContext.default();
	const bookingContext = require_SalesSdkBookingContext.useSalesSdkBookingContext();
	const intervalRef = (0, react.useRef)(null);
	const [currentDate, setCurrentDate] = (0, react.useState)(() => resolveDate(bookingContext.getDate()));
	const [collapsed, setCollapsed] = (0, react.useState)(true);
	const [scaleCompensation, setScaleCompensation] = (0, react.useState)(1);
	const [intervalSetTime, setIntervalSetTime] = (0, react.useState)(true);
	const [isDateChange, setIsDateChange] = (0, react.useState)(false);
	const [isTimeChange, setIsTimeChange] = (0, react.useState)(false);
	_pisell_utils.locales.init(require_index$1.default, (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 || (_context$appHelper$ge = _context$appHelper.getApp) === null || _context$appHelper$ge === void 0 || (_context$appHelper$ge = _context$appHelper$ge.call(_context$appHelper)) === null || _context$appHelper$ge === void 0 || (_context$appHelper$ge = _context$appHelper$ge.locales) === null || _context$appHelper$ge === void 0 || (_context$appHelper$ge2 = _context$appHelper$ge.getLocale) === null || _context$appHelper$ge2 === void 0 ? void 0 : _context$appHelper$ge2.call(_context$appHelper$ge)) || locale);
	(0, react.useEffect)(() => {
		setCurrentDate(resolveDate(bookingContext.getDate()));
	}, [bookingContext, dataSource.sales.bookingTicket]);
	/** 订阅 OS BookingContext 日期变更，保持 TimeBar 与 store 同步。 */
	(0, react.useEffect)(() => {
		if (!dataSource.sales.bookingTicket) return;
		return require_bookingDate.subscribeBookingDateChange(dataSource.sales.bookingTicket, (rawDate) => {
			setCurrentDate(resolveDate(rawDate));
		});
	}, [dataSource.sales.bookingTicket]);
	/**
	* SDK ready 后启动「跟随当前时间」定时器（对齐 ticketBooking `_setIntervalTime(true)`，不 reload 商品）。
	*/
	(0, react.useEffect)(() => {
		if (!dataSource.sales.isReady || !dataSource.sales.bookingTicket) return;
		startNowInterval(false);
		return () => {
			stopInterval();
		};
	}, [dataSource.sales.isReady, dataSource.sales.bookingTicket]);
	(0, react.useEffect)(() => {
		const getBodyScale = () => {
			const transform = window.getComputedStyle(document.body).transform;
			if (!transform || transform === "none") return 1;
			const matrix = transform.match(/matrix\(([^)]+)\)/);
			if (!matrix) return 1;
			return matrix[1].split(",").map((value) => parseFloat(value.trim()))[0] || 1;
		};
		const updateScale = () => {
			setScaleCompensation(getBodyScale());
		};
		updateScale();
		const observer = new MutationObserver(updateScale);
		observer.observe(document.body, {
			attributes: true,
			attributeFilter: ["style", "class"]
		});
		window.addEventListener("resize", updateScale);
		return () => {
			observer.disconnect();
			window.removeEventListener("resize", updateScale);
		};
	}, []);
	(0, react.useEffect)(() => {
		return () => {
			if (intervalRef.current) clearInterval(intervalRef.current);
		};
	}, []);
	const reloadProducts = (0, ahooks.useMemoizedFn)(() => {
		dataSource.products.load(productLoadParams).catch((error) => {
			console.error(error);
		});
	});
	const applyDate = (0, ahooks.useMemoizedFn)((date, shouldReloadProducts = false) => {
		setCurrentDate(date);
		if (!dataSource.sales.bookingTicket) return;
		bookingContext.setDate(date);
		if (shouldReloadProducts) reloadProducts();
	});
	const stopInterval = (0, ahooks.useMemoizedFn)(() => {
		if (intervalRef.current) {
			clearInterval(intervalRef.current);
			intervalRef.current = null;
		}
		setIntervalSetTime(false);
	});
	/**
	* 开启「跟随当前时间」模式。
	* - 定时 tick 只同步 BookingContext（对齐 ticketBooking `_setDataChange`，不 reload 商品）
	* - 用户点 Today/Now 时传 shouldReloadProducts=true
	*
	* @example
	* startNowInterval(false); // mount 时
	* startNowInterval(true);  // 用户点「现在」
	*/
	const startNowInterval = (0, ahooks.useMemoizedFn)((shouldReloadProducts = false) => {
		if (intervalRef.current) clearInterval(intervalRef.current);
		setIsDateChange(false);
		setIsTimeChange(false);
		setIntervalSetTime(true);
		applyDate((0, dayjs.default)(), shouldReloadProducts);
		intervalRef.current = setInterval(() => {
			applyDate((0, dayjs.default)(), false);
		}, 1e3 * 60);
	});
	const handlePreviousDay = (0, ahooks.useMemoizedFn)(() => {
		const newDate = currentDate.subtract(1, "day");
		stopInterval();
		setIsDateChange(true);
		applyDate(newDate, true);
	});
	const handleNextDay = (0, ahooks.useMemoizedFn)(() => {
		const newDate = currentDate.add(1, "day");
		stopInterval();
		setIsDateChange(true);
		applyDate(newDate, true);
	});
	const handleDateChange = (0, ahooks.useMemoizedFn)((date) => {
		if (!date) return;
		stopInterval();
		setIsDateChange(true);
		applyDate(date, true);
	});
	const handleTimeChange = (0, ahooks.useMemoizedFn)((timeString) => {
		const [hours, minutes] = timeString.split(":").map(Number);
		const newDate = currentDate.hour(hours).minute(minutes).second(0);
		setIsTimeChange(true);
		applyDate(newDate, true);
		if (timeString === (0, dayjs.default)().format("HH:mm")) startNowInterval(true);
		else stopInterval();
	});
	const handleCreateClick = (0, ahooks.useMemoizedFn)(() => {
		dataSource.sales.createNew().then(() => {
			startNowInterval(false);
		}).catch((error) => {
			console.error(error);
		});
	});
	const hasExistingOrder = Boolean(orderId || ((_dataSource$sales$tem = dataSource.sales.tempOrder) === null || _dataSource$sales$tem === void 0 ? void 0 : _dataSource$sales$tem.order_id) || ((_dataSource$sales$sal = dataSource.sales.salesDetail) === null || _dataSource$sales$sal === void 0 || (_dataSource$sales$sal = _dataSource$sales$sal.header) === null || _dataSource$sales$sal === void 0 ? void 0 : _dataSource$sales$sal.order_id));
	const dateFormat = locale === "en" ? "dddd, DD MMM YYYY" : "YYYY年MM月DD日";
	const collapsedHeight = 40 / scaleCompensation;
	return (0, react.useMemo)(() => {
		const collapsedText = currentDate.isSame((0, dayjs.default)(), "day") ? _pisell_utils.locales.getText("pisell2.big-sale.today") : currentDate.format(DISPLAY_DATE_FORMAT);
		if (variant === "phone") return /* @__PURE__ */ react.default.createElement(require_index.default, {
			renderType: "drawer",
			showHandlerBar: true,
			onHandlerBarClick: onMobileDrawerClose,
			props: {
				open: mobileDrawerOpen,
				onClose: onMobileDrawerClose,
				placement: "bottom",
				header: false,
				footer: false,
				closable: false,
				destroyOnClose: false,
				className: "pisell-big-sale-time-bar-drawer-phone",
				contentWrapperStyle: {
					maxWidth: "none",
					height: "auto"
				},
				styles: { body: { padding: 0 } }
			}
		}, /* @__PURE__ */ react.default.createElement("div", {
			className: "pisell-big-sale-time-bar-phone",
			style: { backgroundColor: isDateChange ? "#F79009" : void 0 }
		}, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-big-sale-time-bar-phone__nav" }, /* @__PURE__ */ react.default.createElement(antd.Button, {
			icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.LeftOutlined, null),
			onClick: handlePreviousDay,
			size: "large"
		}), /* @__PURE__ */ react.default.createElement("div", { className: (0, classnames.default)("pisell-big-sale-time-bar-phone__field", { "pisell-big-sale-time-bar__picker--selected": isDateChange }) }, /* @__PURE__ */ react.default.createElement(_pisell_materials.DatePicker, {
			inputReadOnly: true,
			value: currentDate,
			format: locale === "en" ? "DD MMM YYYY" : "YYYY年MM月DD日",
			onChange: handleDateChange,
			size: "large",
			style: { width: "100%" }
		})), /* @__PURE__ */ react.default.createElement(antd.Button, {
			icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.RightOutlined, null),
			onClick: handleNextDay,
			size: "large"
		})), /* @__PURE__ */ react.default.createElement(antd.Button, {
			block: true,
			onClick: () => startNowInterval(true),
			size: "large",
			style: intervalSetTime ? {
				background: "#000",
				color: "#fff"
			} : void 0
		}, _pisell_utils.locales.getText("pisell2.big-sale.today")), /* @__PURE__ */ react.default.createElement("div", { className: (0, classnames.default)("pisell-big-sale-time-bar-phone__field", { "pisell-big-sale-time-bar__picker--selected": isTimeChange }) }, /* @__PURE__ */ react.default.createElement(_pisell_materials.SelectTime, {
			value: currentDate.format("HH:mm"),
			onChange: handleTimeChange,
			popoverProps: { style: { zoom: .8 } },
			timePickerProps: {},
			timeProps: {},
			slice: 5
		})), !hasExistingOrder && /* @__PURE__ */ react.default.createElement(antd.Button, {
			block: true,
			onClick: () => startNowInterval(true),
			size: "large",
			style: intervalSetTime ? {
				background: "#000",
				color: "#fff"
			} : void 0
		}, _pisell_utils.locales.getText("pisell2.big-sale.now")), hasExistingOrder && /* @__PURE__ */ react.default.createElement(antd.Button, {
			block: true,
			onClick: () => {
				handleCreateClick();
				onMobileDrawerClose === null || onMobileDrawerClose === void 0 || onMobileDrawerClose();
			},
			size: "large",
			type: "primary"
		}, _pisell_utils.locales.getText("pisell2.big-sale.create-new"))));
		if (collapsed) return /* @__PURE__ */ react.default.createElement("div", {
			className: (0, classnames.default)("pisell-big-sale-time-bar", "pisell-big-sale-time-bar--collapsed", `pisell-big-sale-time-bar--${variant}`),
			style: {
				height: collapsedHeight,
				minHeight: collapsedHeight,
				maxHeight: collapsedHeight
			}
		}, /* @__PURE__ */ react.default.createElement("div", {
			className: "pisell-big-sale-time-bar__collapsed-content",
			style: { height: collapsedHeight }
		}, /* @__PURE__ */ react.default.createElement("span", {
			className: "pisell-big-sale-time-bar__collapsed-date",
			style: { lineHeight: `${collapsedHeight}px` }
		}, collapsedText), /* @__PURE__ */ react.default.createElement(antd.Button, {
			type: "link",
			size: "small",
			className: "pisell-big-sale-time-bar__collapsed-expand",
			onClick: () => setCollapsed(false),
			style: { lineHeight: `${collapsedHeight}px` }
		}, /* @__PURE__ */ react.default.createElement("span", null, _pisell_utils.locales.getText("pisell2.big-sale.expand")), /* @__PURE__ */ react.default.createElement(_pisell_materials.Iconfont, { type: "pisell2-chevron-right-double" }))));
		return /* @__PURE__ */ react.default.createElement("div", {
			className: (0, classnames.default)("pisell-big-sale-time-bar", `pisell-big-sale-time-bar--${variant}`),
			style: { backgroundColor: isDateChange ? "#F79009" : void 0 }
		}, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-big-sale-time-bar__scroll" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-big-sale-time-bar__scroll-content" }, /* @__PURE__ */ react.default.createElement(antd.Button, {
			icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.LeftOutlined, null),
			onClick: handlePreviousDay,
			size: "large"
		}), /* @__PURE__ */ react.default.createElement(antd.Button, {
			onClick: () => startNowInterval(true),
			size: "large",
			style: intervalSetTime ? {
				background: "#000",
				color: "#fff"
			} : void 0
		}, _pisell_utils.locales.getText("pisell2.big-sale.today")), /* @__PURE__ */ react.default.createElement("div", { className: (0, classnames.default)("pisell-big-sale-time-bar__date-picker", { "pisell-big-sale-time-bar__picker--selected": isDateChange }) }, /* @__PURE__ */ react.default.createElement(_pisell_materials.DatePicker, {
			inputReadOnly: true,
			value: currentDate,
			format: dateFormat,
			onChange: handleDateChange,
			size: "large",
			style: { width: "100%" }
		})), /* @__PURE__ */ react.default.createElement(antd.Button, {
			icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.RightOutlined, null),
			onClick: handleNextDay,
			size: "large"
		}), /* @__PURE__ */ react.default.createElement("div", { className: (0, classnames.default)("pisell-big-sale-time-bar__time-picker", { "pisell-big-sale-time-bar__picker--selected": isTimeChange }) }, /* @__PURE__ */ react.default.createElement(_pisell_materials.SelectTime, {
			value: currentDate.format("HH:mm"),
			onChange: handleTimeChange,
			popoverProps: { style: { zoom: .8 } },
			timePickerProps: {},
			timeProps: {},
			slice: 5
		})), !hasExistingOrder && /* @__PURE__ */ react.default.createElement(antd.Button, {
			onClick: () => startNowInterval(true),
			size: "large",
			style: intervalSetTime ? {
				background: "#000",
				color: "#fff"
			} : void 0
		}, _pisell_utils.locales.getText("pisell2.big-sale.now")), hasExistingOrder && /* @__PURE__ */ react.default.createElement(antd.Button, {
			onClick: handleCreateClick,
			size: "large",
			type: "primary"
		}, _pisell_utils.locales.getText("pisell2.big-sale.create-new")))), /* @__PURE__ */ react.default.createElement(antd.Button, {
			type: "link",
			className: "pisell-big-sale-time-bar__collapse",
			onClick: () => setCollapsed(true)
		}, /* @__PURE__ */ react.default.createElement("span", null, _pisell_utils.locales.getText("pisell2.big-sale.collapse")), /* @__PURE__ */ react.default.createElement(_pisell_materials.Iconfont, { type: "pisell2-chevron-left-double" })));
	}, [
		collapsed,
		collapsedHeight,
		currentDate,
		dateFormat,
		handleCreateClick,
		handleDateChange,
		handleNextDay,
		handlePreviousDay,
		handleTimeChange,
		hasExistingOrder,
		intervalSetTime,
		isDateChange,
		isTimeChange,
		locale,
		mobileDrawerOpen,
		onMobileDrawerClose,
		startNowInterval,
		variant
	]);
};
BigSaleTimeBar.displayName = "BigSaleTimeBar";
var TimeBar_default = require_withResponsive.default(BigSaleTimeBar);
//#endregion
exports.default = TimeBar_default;
