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/eventBooking/components/bookingDetailModal/index.tsx
var bookingDetailModal_exports = {};
__export(bookingDetailModal_exports, {
  default: () => bookingDetailModal_default
});
module.exports = __toCommonJS(bookingDetailModal_exports);
var import_react = __toESM(require("react"));
var import_materials = require("@pisell/materials");
var import_eventCard = __toESM(require("../eventCard"));
var import_Sales = require("../../../Sales");
var import_utils = require("@pisell/utils");
var import_Schedule = __toESM(require("./components/Schedule"));
var import_Resource = __toESM(require("./components/Resource"));
var import_BookingOptions = __toESM(require("./components/BookingOptions"));
var import_OrderProductModal = __toESM(require("../Provider/OrderProductModal/index"));
var import_index = require("./index.less");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var BookingDetailModal = (props) => {
  var _a, _b, _c;
  const modalContentRef = (0, import_react.useRef)(null);
  const context = (0, import_useEngineContext.default)();
  const { utils } = context.appHelper || {};
  const tabsRef = (0, import_react.useRef)();
  const { open = false } = props;
  const {
    detail,
    onCloseEventDetail,
    onSelectEventDetail,
    selectEventDetailProductDetail,
    checkBeforeSelectEventDetail,
    getProductDetailRequest
  } = (0, import_Sales.useEventDetail)();
  const { addToCart, checkBeforeAddToCart, checkBeforeAddToCartResquest } = (0, import_Sales.useCart)();
  const { initData } = (0, import_Sales.useInit)();
  const [activeTab, setActiveTab] = (0, import_react.useState)("introduction");
  const [isScrolling, setIsScrolling] = (0, import_react.useState)(false);
  const [openCheckout, setOpenCheckout] = (0, import_react.useState)(false);
  const isUserClickRef = (0, import_react.useRef)(false);
  const scrollTimeoutRef = (0, import_react.useRef)(null);
  const buttonText = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    const config = ((_b2 = (_a2 = initData == null ? void 0 : initData.boardSetting) == null ? void 0 : _a2.config) == null ? void 0 : _b2.product_display_setting) || {};
    return ((_c2 = utils == null ? void 0 : utils.translation) == null ? void 0 : _c2.call(utils, config == null ? void 0 : config.booking_event_v2_product_detail_button)) || import_utils.locales.getText("pisell2.event.add.to.cart");
  }, [(_b = (_a = initData == null ? void 0 : initData.boardSetting) == null ? void 0 : _a.config) == null ? void 0 : _b.product_display_setting]);
  const anchorOptions = (0, import_react.useMemo)(
    () => [
      {
        id: "introduction",
        name: import_utils.locales.getText("pisell2.event.introduction")
      },
      {
        id: "schedule",
        name: import_utils.locales.getText("pisell2.event.schedule")
      },
      {
        id: "resource",
        name: import_utils.locales.getText("pisell2.event.resource")
      },
      // {
      //   id: 'campus',
      //   name: locales.getText('pisell2.event.campus'),
      // },
      {
        id: "booking_options",
        name: import_utils.locales.getText("pisell2.event.booking.options")
      }
    ],
    []
  );
  const images = (0, import_react.useMemo)(() => {
    var _a2;
    return ((_a2 = detail == null ? void 0 : detail.introduction) == null ? void 0 : _a2.images) || [];
  }, [(_c = detail == null ? void 0 : detail.introduction) == null ? void 0 : _c.images]);
  (0, import_react.useEffect)(() => {
    if (!modalContentRef.current) return;
    let isCurrentlyScrolling = false;
    let lastScrollTime = 0;
    let pendingAnchorId = null;
    const handleScroll = () => {
      if (isScrolling || isUserClickRef.current) return;
      lastScrollTime = Date.now();
      isCurrentlyScrolling = true;
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }
      const container2 = modalContentRef.current;
      if (!container2) return;
      const scrollTop = container2.scrollTop;
      const headerHeight = 56;
      const containerHeight = container2.clientHeight;
      const sectionPositions = anchorOptions.map((option) => {
        const element = document.getElementById(option.id) || document.querySelector(`[data-section="${option.id}"]`);
        if (!element) return null;
        const elementOffsetTop = element.offsetTop;
        const elementHeight = element.offsetHeight;
        const isElementVisible = elementOffsetTop >= scrollTop && elementOffsetTop <= scrollTop + containerHeight || elementOffsetTop + elementHeight >= scrollTop && elementOffsetTop + elementHeight <= scrollTop + containerHeight || elementOffsetTop <= scrollTop && elementOffsetTop + elementHeight >= scrollTop + containerHeight;
        return {
          id: option.id,
          offsetTop: elementOffsetTop,
          height: elementHeight,
          distanceFromViewportTop: Math.abs(
            elementOffsetTop - scrollTop - headerHeight
          ),
          isVisible: isElementVisible
        };
      }).filter(
        (section) => section !== null
      );
      const visibleSections = sectionPositions.filter(
        (section) => section.isVisible
      );
      if (visibleSections.length === 0) return;
      const bestSection = visibleSections.reduce(
        (prev, current) => prev.distanceFromViewportTop < current.distanceFromViewportTop ? prev : current
      );
      if (bestSection && activeTab !== bestSection.id) {
        pendingAnchorId = bestSection.id;
      }
      scrollTimeoutRef.current = setTimeout(() => {
        const timeSinceLastScroll = Date.now() - lastScrollTime;
        if (timeSinceLastScroll >= 300) {
          isCurrentlyScrolling = false;
          if (pendingAnchorId && activeTab !== pendingAnchorId && !isScrolling) {
            setActiveTab(pendingAnchorId);
          }
          pendingAnchorId = null;
        } else {
          scrollTimeoutRef.current = setTimeout(() => {
            isCurrentlyScrolling = false;
            if (pendingAnchorId && activeTab !== pendingAnchorId && !isScrolling) {
              setActiveTab(pendingAnchorId);
            }
            pendingAnchorId = null;
          }, 300 - timeSinceLastScroll);
        }
      }, 300);
    };
    const container = modalContentRef.current;
    container.addEventListener("scroll", handleScroll);
    return () => {
      container.removeEventListener("scroll", handleScroll);
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }
    };
  }, [anchorOptions, activeTab, isScrolling]);
  const handleTabChange = (key) => {
    setActiveTab(typeof key === "string" ? key : key.toString());
    if (isUserClickRef.current) {
      const section = document.querySelector(
        `[data-section="${typeof key === "string" ? key : key.toString()}"]`
      );
      if (section && modalContentRef.current) {
        const sectionTop = section.getBoundingClientRect().top;
        const contentTop = modalContentRef.current.getBoundingClientRect().top;
        const scrollTop = modalContentRef.current.scrollTop + (sectionTop - contentTop) - 50;
        modalContentRef.current.scrollTo({
          top: scrollTop,
          behavior: "smooth"
        });
      }
      isUserClickRef.current = false;
    }
  };
  const content = () => {
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "booking-detail-modal-content",
        style: { height: (0, import_utils.isMobile)() ? "100%" : "calc(80vh - 146px)" }
      },
      /* @__PURE__ */ import_react.default.createElement("div", { className: "anchor-wrapper" }, /* @__PURE__ */ import_react.default.createElement(
        import_materials.PisellAnchor,
        {
          ref: tabsRef,
          options: anchorOptions,
          containerRef: modalContentRef,
          tab: activeTab,
          onChange: (key) => {
            handleTabChange(key);
          },
          onTabClick: () => {
            isUserClickRef.current = true;
          }
        }
      )),
      /* @__PURE__ */ import_react.default.createElement("div", { className: "content-wrapper", ref: modalContentRef }, /* @__PURE__ */ import_react.default.createElement("div", { "data-section": "introduction", className: "content-section" }, (images == null ? void 0 : images.length) > 0 ? /* @__PURE__ */ import_react.default.createElement(
        import_materials.PisellImageCarousels,
        {
          dataSource: images,
          width: "100%",
          height: (0, import_utils.isMobile)() ? 300 : 400,
          showArrows: !(0, import_utils.isMobile)(),
          showDots: (images == null ? void 0 : images.length) > 1,
          autoplay: (images == null ? void 0 : images.length) > 1,
          loop: false
        }
      ) : null, /* @__PURE__ */ import_react.default.createElement(import_eventCard.default, { data: detail == null ? void 0 : detail.introduction })), /* @__PURE__ */ import_react.default.createElement("div", { "data-section": "schedule", className: "content-section" }, /* @__PURE__ */ import_react.default.createElement(import_Schedule.default, null)), /* @__PURE__ */ import_react.default.createElement("div", { "data-section": "resource", className: "content-section" }, /* @__PURE__ */ import_react.default.createElement(import_Resource.default, null)), /* @__PURE__ */ import_react.default.createElement("div", { "data-section": "booking_options", className: "content-section" }, /* @__PURE__ */ import_react.default.createElement(
        import_BookingOptions.default,
        {
          onChangeBookingOption: checkToOpenProductDetailModal
        }
      )))
    );
  };
  const checkToOpenProductDetailModal = (bookingOption) => {
    var _a2;
    console.log(">>>>>>>", bookingOption);
    if (((_a2 = bookingOption == null ? void 0 : bookingOption._originData) == null ? void 0 : _a2.is_eject) !== 1) {
      return;
    }
    utils == null ? void 0 : utils.action({
      type: "pisell1.productDetail",
      data: {
        detail: { ...(bookingOption == null ? void 0 : bookingOption._originData) || {}, open_deposit: 1 },
        isOS: false
      },
      callback: (data) => {
        if (data == null ? void 0 : data.isCancel) {
          return;
        }
        console.log("data>>>>>>", data);
        const product = {
          ...data,
          options: (data == null ? void 0 : data.option) || []
        };
        delete product.option;
        selectEventDetailProductDetail(product);
        handleOk();
      }
    });
  };
  const handleOk = async () => {
    console.log(">>>>>>>", detail);
    const result = checkBeforeSelectEventDetail();
    if (!result) {
      checkToOpenProductDetailModal(detail == null ? void 0 : detail.selectedProduct);
      return;
    }
    onSelectEventDetail();
    const checkRes = await checkBeforeAddToCart();
    if ((checkRes == null ? void 0 : checkRes.result) === false) {
      setOpenCheckout(true);
      return;
    }
    addToCart();
  };
  (0, import_react.useEffect)(() => {
    if (open) {
      setActiveTab("introduction");
      setIsScrolling(false);
      isUserClickRef.current = false;
    }
  }, [open]);
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      open,
      title: import_utils.locales.getText("pisell2.event.details"),
      platform: (0, import_utils.isMobile)() ? "h5" : "pc",
      bodyStyle: { padding: 0, overflow: "hidden" },
      destroyOnClose: true,
      className: "booking-detail-modal",
      onCancel: onCloseEventDetail,
      okText: buttonText,
      cancelVisible: false,
      onOk: handleOk,
      width: (0, import_utils.isMobile)() ? "100%" : 600,
      okButtonProps: {
        loading: (getProductDetailRequest == null ? void 0 : getProductDetailRequest.loading) || (checkBeforeAddToCartResquest == null ? void 0 : checkBeforeAddToCartResquest.loading)
      }
    },
    content()
  ), /* @__PURE__ */ import_react.default.createElement(
    import_OrderProductModal.default,
    {
      open: openCheckout,
      onCancel: () => setOpenCheckout(false)
    }
  ));
};
var bookingDetailModal_default = BookingDetailModal;
