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/components/bigSale/components/TimeBar/index.tsx
var TimeBar_exports = {};
__export(TimeBar_exports, {
  default: () => TimeBar_default
});
module.exports = __toCommonJS(TimeBar_exports);
var import_react = __toESM(require("react"));
var import_icons = require("@ant-design/icons");
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_ahooks = require("ahooks");
var import_classnames = __toESM(require("classnames"));
var import_dayjs = __toESM(require("dayjs"));
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_compensatedPisellContainer = __toESM(require("../../../../pro/compensatedPisellContainer"));
var import_salesSdk = require("../../../../plus/salesSdk");
var import_responsive = require("../../../../responsive");
var import_locales = __toESM(require("../../locales"));
var import_index = require("./index.less");
var DISPLAY_DATE_FORMAT = "YYYY-MM-DD";
function resolveDate(rawDate) {
  if (rawDate && (0, import_dayjs.default)(rawDate).isValid()) {
    return (0, import_dayjs.default)(rawDate);
  }
  return (0, import_dayjs.default)();
}
var BigSaleTimeBar = (0, import_react.forwardRef)((props, ref) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
  const {
    context,
    productLoadParams,
    locale = "en",
    orderId,
    variant = "desktop",
    mobileDrawerOpen,
    onMobileDrawerClose
  } = props;
  const engineContext = (0, import_useEngineContext.default)();
  const bookingContext = (0, import_salesSdk.useSalesSdkBookingContext)();
  const intervalRef = (0, import_react.useRef)(null);
  const [currentDate, setCurrentDate] = (0, import_react.useState)(() => resolveDate(bookingContext.getDate()));
  const [collapsed, setCollapsed] = (0, import_react.useState)(true);
  const [scaleCompensation, setScaleCompensation] = (0, import_react.useState)(1);
  const [intervalSetTime, setIntervalSetTime] = (0, import_react.useState)(true);
  const [isDateChange, setIsDateChange] = (0, import_react.useState)(false);
  const [isTimeChange, setIsTimeChange] = (0, import_react.useState)(false);
  const [internalMobileDrawerOpen, setInternalMobileDrawerOpen] = (0, import_react.useState)(false);
  const mergedMobileDrawerOpen = mobileDrawerOpen ?? internalMobileDrawerOpen;
  import_utils.locales.init(
    import_locales.default,
    ((_f = (_e = (_d = (_c = (_b = (_a = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.getApp) == null ? void 0 : _c.call(_b)) == null ? void 0 : _d.locales) == null ? void 0 : _e.getLocale) == null ? void 0 : _f.call(_e)) || locale
  );
  (0, import_react.useEffect)(() => {
    setCurrentDate(resolveDate(bookingContext.getDate()));
  }, [bookingContext, context.sales.bookingTicket]);
  (0, import_react.useEffect)(() => {
    if (!context.sales.bookingTicket) return;
    return (0, import_salesSdk.subscribeBookingDateChange)(context.sales.bookingTicket, (rawDate) => {
      setCurrentDate(resolveDate(rawDate));
    });
  }, [context.sales.bookingTicket]);
  (0, import_react.useEffect)(() => {
    if (!context.sales.isReady || !context.sales.bookingTicket) return;
    startNowInterval(false);
    return () => {
      stopInterval();
    };
  }, [context.sales.isReady, context.sales.bookingTicket]);
  (0, import_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;
      const values = matrix[1].split(",").map((value) => parseFloat(value.trim()));
      return values[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, import_react.useEffect)(() => {
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, []);
  const reloadProducts = (0, import_ahooks.useMemoizedFn)(() => {
    context.products.load(productLoadParams).catch((error) => {
      console.error(error);
    });
  });
  const applyDate = (0, import_ahooks.useMemoizedFn)((date, shouldReloadProducts = false) => {
    setCurrentDate(date);
    if (!context.sales.bookingTicket) return;
    bookingContext.setDate(date);
    if (shouldReloadProducts) {
      reloadProducts();
    }
  });
  const stopInterval = (0, import_ahooks.useMemoizedFn)(() => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
    setIntervalSetTime(false);
  });
  const startNowInterval = (0, import_ahooks.useMemoizedFn)((shouldReloadProducts = false) => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }
    setIsDateChange(false);
    setIsTimeChange(false);
    setIntervalSetTime(true);
    applyDate((0, import_dayjs.default)(), shouldReloadProducts);
    intervalRef.current = setInterval(() => {
      applyDate((0, import_dayjs.default)(), false);
    }, 1e3 * 60);
  });
  const closeMobileDrawer = (0, import_ahooks.useMemoizedFn)(() => {
    setInternalMobileDrawerOpen(false);
    onMobileDrawerClose == null ? void 0 : onMobileDrawerClose();
  });
  const openMobileDrawer = (0, import_ahooks.useMemoizedFn)(() => {
    setInternalMobileDrawerOpen(true);
  });
  (0, import_react.useImperativeHandle)(ref, () => ({
    openMobileDrawer,
    closeMobileDrawer
  }));
  const handlePreviousDay = (0, import_ahooks.useMemoizedFn)(() => {
    const newDate = currentDate.subtract(1, "day");
    stopInterval();
    setIsDateChange(true);
    applyDate(newDate, true);
  });
  const handleNextDay = (0, import_ahooks.useMemoizedFn)(() => {
    const newDate = currentDate.add(1, "day");
    stopInterval();
    setIsDateChange(true);
    applyDate(newDate, true);
  });
  const handleDateChange = (0, import_ahooks.useMemoizedFn)((date) => {
    if (!date) return;
    stopInterval();
    setIsDateChange(true);
    applyDate(date, true);
  });
  const handleTimeChange = (0, import_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, import_dayjs.default)().format("HH:mm")) {
      startNowInterval(true);
    } else {
      stopInterval();
    }
  });
  const handleCreateClick = (0, import_ahooks.useMemoizedFn)(() => {
    context.sales.createNew().then(() => {
      startNowInterval(false);
    }).catch((error) => {
      console.error(error);
    });
  });
  const hasExistingOrder = Boolean(
    orderId || ((_g = context.sales.tempOrder) == null ? void 0 : _g.order_id) || ((_i = (_h = context.sales.salesDetail) == null ? void 0 : _h.header) == null ? void 0 : _i.order_id)
  );
  const dateFormat = locale === "en" ? "dddd, DD MMM YYYY" : "YYYY年MM月DD日";
  const collapsedHeight = 40 / scaleCompensation;
  return (0, import_react.useMemo)(() => {
    const isToday = currentDate.isSame((0, import_dayjs.default)(), "day");
    const collapsedText = isToday ? import_utils.locales.getText("pisell2.big-sale.today") : currentDate.format(DISPLAY_DATE_FORMAT);
    if (variant === "phone") {
      return /* @__PURE__ */ import_react.default.createElement(
        import_compensatedPisellContainer.default,
        {
          renderType: "drawer",
          showHandlerBar: true,
          onHandlerBarClick: closeMobileDrawer,
          props: {
            open: mergedMobileDrawerOpen,
            onClose: closeMobileDrawer,
            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__ */ import_react.default.createElement(
          "div",
          {
            className: "pisell-big-sale-time-bar-phone",
            style: { backgroundColor: isDateChange ? "#F79009" : void 0 }
          },
          /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-big-sale-time-bar-phone__nav" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { icon: /* @__PURE__ */ import_react.default.createElement(import_icons.LeftOutlined, null), onClick: handlePreviousDay, size: "large" }), /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              className: (0, import_classnames.default)("pisell-big-sale-time-bar-phone__field", {
                "pisell-big-sale-time-bar__picker--selected": isDateChange
              })
            },
            /* @__PURE__ */ import_react.default.createElement(
              import_materials.DatePicker,
              {
                inputReadOnly: true,
                value: currentDate,
                format: locale === "en" ? "DD MMM YYYY" : "YYYY年MM月DD日",
                onChange: handleDateChange,
                size: "large",
                style: { width: "100%" }
              }
            )
          ), /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { icon: /* @__PURE__ */ import_react.default.createElement(import_icons.RightOutlined, null), onClick: handleNextDay, size: "large" })),
          /* @__PURE__ */ import_react.default.createElement(
            import_antd.Button,
            {
              block: true,
              onClick: () => startNowInterval(true),
              size: "large",
              style: intervalSetTime ? { background: "#000", color: "#fff" } : void 0
            },
            import_utils.locales.getText("pisell2.big-sale.today")
          ),
          /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              className: (0, import_classnames.default)("pisell-big-sale-time-bar-phone__field", {
                "pisell-big-sale-time-bar__picker--selected": isTimeChange
              })
            },
            /* @__PURE__ */ import_react.default.createElement(
              import_materials.SelectTime,
              {
                value: currentDate.format("HH:mm"),
                onChange: handleTimeChange,
                popoverProps: {
                  style: { zoom: 0.8 }
                },
                timePickerProps: {},
                timeProps: {},
                slice: 5
              }
            )
          ),
          !hasExistingOrder && /* @__PURE__ */ import_react.default.createElement(
            import_antd.Button,
            {
              block: true,
              onClick: () => startNowInterval(true),
              size: "large",
              style: intervalSetTime ? { background: "#000", color: "#fff" } : void 0
            },
            import_utils.locales.getText("pisell2.big-sale.now")
          ),
          hasExistingOrder && /* @__PURE__ */ import_react.default.createElement(
            import_antd.Button,
            {
              block: true,
              onClick: () => {
                handleCreateClick();
                closeMobileDrawer();
              },
              size: "large",
              type: "primary"
            },
            import_utils.locales.getText("pisell2.big-sale.create-new")
          )
        )
      );
    }
    if (collapsed) {
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: (0, import_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__ */ import_react.default.createElement(
          "div",
          {
            className: "pisell-big-sale-time-bar__collapsed-content",
            style: { height: collapsedHeight }
          },
          /* @__PURE__ */ import_react.default.createElement(
            "span",
            {
              className: "pisell-big-sale-time-bar__collapsed-date",
              style: { lineHeight: `${collapsedHeight}px` }
            },
            collapsedText
          ),
          /* @__PURE__ */ import_react.default.createElement(
            import_antd.Button,
            {
              type: "link",
              size: "small",
              className: "pisell-big-sale-time-bar__collapsed-expand",
              onClick: () => setCollapsed(false),
              style: { lineHeight: `${collapsedHeight}px` }
            },
            /* @__PURE__ */ import_react.default.createElement("span", null, import_utils.locales.getText("pisell2.big-sale.expand")),
            /* @__PURE__ */ import_react.default.createElement(import_materials.Iconfont, { type: "pisell2-chevron-right-double" })
          )
        )
      );
    }
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: (0, import_classnames.default)(
          "pisell-big-sale-time-bar",
          `pisell-big-sale-time-bar--${variant}`
        ),
        style: { backgroundColor: isDateChange ? "#F79009" : void 0 }
      },
      /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-big-sale-time-bar__scroll" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-big-sale-time-bar__scroll-content" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { icon: /* @__PURE__ */ import_react.default.createElement(import_icons.LeftOutlined, null), onClick: handlePreviousDay, size: "large" }), /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          onClick: () => startNowInterval(true),
          size: "large",
          style: intervalSetTime ? { background: "#000", color: "#fff" } : void 0
        },
        import_utils.locales.getText("pisell2.big-sale.today")
      ), /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: (0, import_classnames.default)("pisell-big-sale-time-bar__date-picker", {
            "pisell-big-sale-time-bar__picker--selected": isDateChange
          })
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_materials.DatePicker,
          {
            inputReadOnly: true,
            value: currentDate,
            format: dateFormat,
            onChange: handleDateChange,
            size: "large",
            style: { width: "100%" }
          }
        )
      ), /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { icon: /* @__PURE__ */ import_react.default.createElement(import_icons.RightOutlined, null), onClick: handleNextDay, size: "large" }), /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: (0, import_classnames.default)("pisell-big-sale-time-bar__time-picker", {
            "pisell-big-sale-time-bar__picker--selected": isTimeChange
          })
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_materials.SelectTime,
          {
            value: currentDate.format("HH:mm"),
            onChange: handleTimeChange,
            popoverProps: {
              style: { zoom: 0.8 }
            },
            timePickerProps: {},
            timeProps: {},
            slice: 5
          }
        )
      ), !hasExistingOrder && /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          onClick: () => startNowInterval(true),
          size: "large",
          style: intervalSetTime ? { background: "#000", color: "#fff" } : void 0
        },
        import_utils.locales.getText("pisell2.big-sale.now")
      ), hasExistingOrder && /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { onClick: handleCreateClick, size: "large", type: "primary" }, import_utils.locales.getText("pisell2.big-sale.create-new")))),
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          type: "link",
          className: "pisell-big-sale-time-bar__collapse",
          onClick: () => setCollapsed(true)
        },
        /* @__PURE__ */ import_react.default.createElement("span", null, import_utils.locales.getText("pisell2.big-sale.collapse")),
        /* @__PURE__ */ import_react.default.createElement(import_materials.Iconfont, { type: "pisell2-chevron-left-double" })
      )
    );
  }, [
    collapsed,
    collapsedHeight,
    currentDate,
    dateFormat,
    handleCreateClick,
    handleDateChange,
    handleNextDay,
    handlePreviousDay,
    handleTimeChange,
    hasExistingOrder,
    intervalSetTime,
    isDateChange,
    isTimeChange,
    locale,
    closeMobileDrawer,
    mergedMobileDrawerOpen,
    startNowInterval,
    variant
  ]);
});
BigSaleTimeBar.displayName = "BigSaleTimeBar";
var TimeBar_default = (0, import_responsive.withResponsive)(BigSaleTimeBar);
