import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import { useCart } from "../../../Sales/Cart/index.js";
import { useInit } from "../../../Sales/Init/index.js";
import { useEventDetail } from "../../../Sales/Event/Detail.js";
import OrderProductModal from "../Provider/OrderProductModal/index.js";
import EventCard from "../eventCard/index.js";
import Schedule from "./components/Schedule.js";
import Resource from "./components/Resource.js";
import BookingOptions from "./components/BookingOptions.js";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { isMobile, locales } from "@pisell/utils";
import { PisellAnchor, PisellImageCarousels, PisellModal } from "@pisell/materials";
import "./index.less";
//#region src/components/eventBooking/components/bookingDetailModal/index.tsx
const BookingDetailModal = (props) => {
	var _initData$boardSettin2, _detail$introduction2;
	const modalContentRef = useRef(null);
	const { utils } = useEngineContext().appHelper || {};
	const tabsRef = useRef();
	const { open = false } = props;
	const { detail, onCloseEventDetail, onSelectEventDetail, selectEventDetailProductDetail, checkBeforeSelectEventDetail, getProductDetailRequest } = useEventDetail();
	const { addToCart, checkBeforeAddToCart, checkBeforeAddToCartResquest } = useCart();
	const { initData } = useInit();
	const [activeTab, setActiveTab] = useState("introduction");
	const [isScrolling, setIsScrolling] = useState(false);
	const [openCheckout, setOpenCheckout] = useState(false);
	const isUserClickRef = useRef(false);
	const scrollTimeoutRef = useRef(null);
	/**
	* @title: 按钮确认文案
	* @description:
	* @param {*} useMemo
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-06-26 15:34
	*/
	const buttonText = useMemo(() => {
		var _initData$boardSettin, _utils$translation;
		const config = (initData === null || initData === void 0 || (_initData$boardSettin = initData.boardSetting) === null || _initData$boardSettin === void 0 || (_initData$boardSettin = _initData$boardSettin.config) === null || _initData$boardSettin === void 0 ? void 0 : _initData$boardSettin.product_display_setting) || {};
		return (utils === null || utils === void 0 || (_utils$translation = utils.translation) === null || _utils$translation === void 0 ? void 0 : _utils$translation.call(utils, config === null || config === void 0 ? void 0 : config.booking_event_v2_product_detail_button)) || locales.getText("pisell2.event.add.to.cart");
	}, [initData === null || initData === void 0 || (_initData$boardSettin2 = initData.boardSetting) === null || _initData$boardSettin2 === void 0 || (_initData$boardSettin2 = _initData$boardSettin2.config) === null || _initData$boardSettin2 === void 0 ? void 0 : _initData$boardSettin2.product_display_setting]);
	/**
	* @title: 详情锚点
	* @description:
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-01-15 22:20
	*/
	const anchorOptions = useMemo(() => [
		{
			id: "introduction",
			name: locales.getText("pisell2.event.introduction")
		},
		{
			id: "schedule",
			name: locales.getText("pisell2.event.schedule")
		},
		{
			id: "resource",
			name: locales.getText("pisell2.event.resource")
		},
		{
			id: "booking_options",
			name: locales.getText("pisell2.event.booking.options")
		}
	], []);
	const images = useMemo(() => {
		var _detail$introduction;
		return (detail === null || detail === void 0 || (_detail$introduction = detail.introduction) === null || _detail$introduction === void 0 ? void 0 : _detail$introduction.images) || [];
	}, [detail === null || detail === void 0 || (_detail$introduction2 = detail.introduction) === null || _detail$introduction2 === void 0 ? void 0 : _detail$introduction2.images]);
	useEffect(() => {
		if (!modalContentRef.current) return;
		let lastScrollTime = 0;
		let pendingAnchorId = null;
		const handleScroll = () => {
			if (isScrolling || isUserClickRef.current) return;
			lastScrollTime = Date.now();
			if (scrollTimeoutRef.current) clearTimeout(scrollTimeoutRef.current);
			const container = modalContentRef.current;
			if (!container) return;
			const scrollTop = container.scrollTop;
			const headerHeight = 56;
			const containerHeight = container.clientHeight;
			const visibleSections = 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).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) {
					if (pendingAnchorId && activeTab !== pendingAnchorId && !isScrolling) setActiveTab(pendingAnchorId);
					pendingAnchorId = null;
				} else scrollTimeoutRef.current = setTimeout(() => {
					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
	]);
	/**
	* 处理tab切换
	* @param key 切换的标签ID
	*/
	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__ */ React.createElement("div", {
			className: "booking-detail-modal-content",
			style: { height: isMobile() ? "100%" : "calc(80vh - 146px)" }
		}, /* @__PURE__ */ React.createElement("div", { className: "anchor-wrapper" }, /* @__PURE__ */ React.createElement(PisellAnchor, {
			ref: tabsRef,
			options: anchorOptions,
			containerRef: modalContentRef,
			tab: activeTab,
			onChange: (key) => {
				handleTabChange(key);
			},
			onTabClick: () => {
				isUserClickRef.current = true;
			}
		})), /* @__PURE__ */ React.createElement("div", {
			className: "content-wrapper",
			ref: modalContentRef
		}, /* @__PURE__ */ React.createElement("div", {
			"data-section": "introduction",
			className: "content-section"
		}, (images === null || images === void 0 ? void 0 : images.length) > 0 ? /* @__PURE__ */ React.createElement(PisellImageCarousels, {
			dataSource: images,
			width: "100%",
			height: isMobile() ? 300 : 400,
			showArrows: !isMobile(),
			showDots: (images === null || images === void 0 ? void 0 : images.length) > 1,
			autoplay: (images === null || images === void 0 ? void 0 : images.length) > 1,
			loop: false
		}) : null, /* @__PURE__ */ React.createElement(EventCard, { data: detail === null || detail === void 0 ? void 0 : detail.introduction })), /* @__PURE__ */ React.createElement("div", {
			"data-section": "schedule",
			className: "content-section"
		}, /* @__PURE__ */ React.createElement(Schedule, null)), /* @__PURE__ */ React.createElement("div", {
			"data-section": "resource",
			className: "content-section"
		}, /* @__PURE__ */ React.createElement(Resource, null)), /* @__PURE__ */ React.createElement("div", {
			"data-section": "booking_options",
			className: "content-section"
		}, /* @__PURE__ */ React.createElement(BookingOptions, { onChangeBookingOption: checkToOpenProductDetailModal }))));
	};
	/**
	* @title: 判断是否需要拉起商品详情弹窗
	* @description: 如果是普通商品，则不需要拉起商品详情弹窗
	* @param {any} bookingOption 选中的option
	* @return {void}
	*/
	const checkToOpenProductDetailModal = (bookingOption) => {
		var _bookingOption$_origi;
		console.log(">>>>>>>", bookingOption);
		if ((bookingOption === null || bookingOption === void 0 || (_bookingOption$_origi = bookingOption._originData) === null || _bookingOption$_origi === void 0 ? void 0 : _bookingOption$_origi.is_eject) !== 1) return;
		utils === null || utils === void 0 || utils.action({
			type: "pisell1.productDetail",
			data: {
				detail: _objectSpread2(_objectSpread2({}, (bookingOption === null || bookingOption === void 0 ? void 0 : bookingOption._originData) || {}), {}, { open_deposit: 1 }),
				isOS: false
			},
			callback: (data) => {
				if (data === null || data === void 0 ? void 0 : data.isCancel) return;
				console.log("data>>>>>>", data);
				const product = _objectSpread2(_objectSpread2({}, data), {}, { options: (data === null || data === void 0 ? void 0 : data.option) || [] });
				delete product.option;
				selectEventDetailProductDetail(product);
				handleOk();
			}
		});
	};
	/**
	* @title: 点击加入购物车
	* @description:
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-01-15 23:08
	*/
	const handleOk = function() {
		var _ref = _asyncToGenerator(function* () {
			console.log(">>>>>>>", detail);
			if (!checkBeforeSelectEventDetail()) {
				checkToOpenProductDetailModal(detail === null || detail === void 0 ? void 0 : detail.selectedProduct);
				return;
			}
			onSelectEventDetail();
			const checkRes = yield checkBeforeAddToCart();
			if ((checkRes === null || checkRes === void 0 ? void 0 : checkRes.result) === false) {
				setOpenCheckout(true);
				return;
			}
			addToCart();
		});
		return function handleOk() {
			return _ref.apply(this, arguments);
		};
	}();
	useEffect(() => {
		if (open) {
			setActiveTab("introduction");
			setIsScrolling(false);
			isUserClickRef.current = false;
		}
	}, [open]);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(PisellModal, {
		open,
		title: locales.getText("pisell2.event.details"),
		platform: isMobile() ? "h5" : "pc",
		bodyStyle: {
			padding: 0,
			overflow: "hidden"
		},
		destroyOnClose: true,
		className: "booking-detail-modal",
		onCancel: onCloseEventDetail,
		okText: buttonText,
		cancelVisible: false,
		onOk: handleOk,
		width: isMobile() ? "100%" : 600,
		okButtonProps: { loading: (getProductDetailRequest === null || getProductDetailRequest === void 0 ? void 0 : getProductDetailRequest.loading) || (checkBeforeAddToCartResquest === null || checkBeforeAddToCartResquest === void 0 ? void 0 : checkBeforeAddToCartResquest.loading) }
	}, content()), /* @__PURE__ */ React.createElement(OrderProductModal, {
		open: openCheckout,
		onCancel: () => setOpenCheckout(false)
	}));
};
//#endregion
export { BookingDetailModal as default };
