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/productSelect/components/TabProduct/index.tsx
var TabProduct_exports = {};
__export(TabProduct_exports, {
  default: () => TabProduct_default
});
module.exports = __toCommonJS(TabProduct_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_ahooks = require("ahooks");
var import_utils = require("@pisell/utils");
var import_tabs = __toESM(require("./tabs"));
var import_productGroup = __toESM(require("../productGroup"));
var getOffsetTopRelativeToScrollContainer = (targetElement, scrollContainer) => {
  if (!targetElement || !scrollContainer) return 0;
  if (targetElement === scrollContainer) {
    return 0;
  }
  const bodyTransform = getComputedStyle(document.body).transform;
  let scaleY = 1;
  if (bodyTransform !== "none") {
    const matrix = new DOMMatrix(bodyTransform);
    scaleY = matrix.d;
  }
  const targetRect = targetElement.getBoundingClientRect();
  const containerRect = scrollContainer.getBoundingClientRect();
  return targetRect.top / scaleY - containerRect.top / scaleY + scrollContainer.scrollTop;
};
var TabProduct = (props) => {
  const {
    showTab = true,
    layout,
    list,
    onChange,
    amountSymbol = "$",
    scrollDom,
    offsetDom,
    value: currentProductId,
    loading,
    emptyDescription,
    ...rest
  } = props;
  const tabsRef = (0, import_react.useRef)();
  const [currentGroupId, setCurrentGroupId] = (0, import_react.useState)(1);
  const tabLocatingRef = (0, import_react.useRef)(false);
  const ioRef = (0, import_react.useRef)(null);
  (0, import_react.useEffect)(() => {
    if (list == null ? void 0 : list.length) {
      setCurrentGroupId(list[0].id);
      requestAnimationFrame(() => {
        handleObserver();
      });
    }
    return () => {
      handleUnobserver();
    };
  }, [list]);
  const debouncedScroll = (0, import_ahooks.useDebounceFn)(
    (id) => {
      var _a;
      (_a = tabsRef == null ? void 0 : tabsRef.current) == null ? void 0 : _a.scroll(id);
    },
    { wait: 100 }
    // 100ms防抖
  );
  const handleObserver = (0, import_ahooks.useMemoizedFn)(() => {
    const _marginTop = 270;
    const _marginBottom = window.innerHeight - 70 - 200 - 70;
    const _rootMargin = `${_marginTop * -1}px 0px ${_marginBottom * -1}px 0px`;
    ioRef.current = new IntersectionObserver(
      (entries) => {
        var _a;
        const enteringEntries = entries.filter((entry) => entry.isIntersecting);
        if (enteringEntries.length > 0) {
          const topMostEntry = enteringEntries.reduce((top, current) => {
            return current.boundingClientRect.top < top.boundingClientRect.top ? current : top;
          });
          const targetId = (_a = topMostEntry == null ? void 0 : topMostEntry.target) == null ? void 0 : _a.id;
          if (targetId) {
            const [name, id] = targetId.split("-");
            const newGroupId = Number(id);
            if (!tabLocatingRef.current && !isNaN(newGroupId)) {
              setCurrentGroupId(newGroupId);
              debouncedScroll.run(id);
            }
          }
        }
      },
      {
        root: null,
        rootMargin: _rootMargin
      }
    );
    if ((list == null ? void 0 : list.length) && ioRef.current) {
      for (const item of list) {
        const _item = document.querySelector(`#list-${item.id}`);
        if (_item) {
          ioRef.current.observe(_item);
        }
      }
    }
  });
  const handleUnobserver = (0, import_ahooks.useMemoizedFn)(() => {
    if ((list == null ? void 0 : list.length) && ioRef.current) {
      for (const item of list) {
        const _item = document.querySelector(`#list-${item.id}`);
        if (_item) {
          ioRef.current.unobserve(_item);
        }
      }
    }
    if (ioRef.current) {
      ioRef.current.disconnect();
      ioRef.current = null;
    }
  });
  const renderContent = () => {
    if (loading) {
      return /* @__PURE__ */ import_react.default.createElement(import_productGroup.ProductGroupSkeleton, { layout });
    }
    if (!(list == null ? void 0 : list.length)) {
      return /* @__PURE__ */ import_react.default.createElement(
        import_materials.PisellEmpty,
        {
          description: emptyDescription || import_utils.locales.getText("pisell2.product-select.empty")
        }
      );
    }
    return list.map((item, i) => {
      return /* @__PURE__ */ import_react.default.createElement("div", { id: `list-${item.id}`, key: `list-${item.id}` }, /* @__PURE__ */ import_react.default.createElement(
        import_productGroup.default,
        {
          onSelectProduct: onChange,
          currentProductId,
          key: item.id,
          data: item,
          layout,
          ...rest
        }
      ));
    });
  };
  const tabSkeleton = (0, import_react.useMemo)(() => {
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "booking-pisell-tabs" }, /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "booking-pisell-tabs-btn-left",
        style: { marginLeft: 20, width: 0 }
      }
    ), /* @__PURE__ */ import_react.default.createElement("div", { className: "booking-pisell-tabs-content" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Skeleton.Button, { active: true, size: "large", shape: "round" })));
  }, []);
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, showTab && list && list.length > 1 ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-product-select-tabs-wrapper" }, loading ? tabSkeleton : /* @__PURE__ */ import_react.default.createElement(
    import_tabs.default,
    {
      ref: tabsRef,
      options: list,
      rowKey: "id",
      tab: currentGroupId,
      onChange: (e) => {
        var _a;
        try {
          const productSelectWrapper = document.querySelector(
            ".pisell-product-select-wrapper"
          );
          const tabsWrapper = document.querySelector(
            ".pisell-product-select-tabs-wrapper"
          );
          let tabsHeight = 0;
          if (tabsWrapper) {
            tabsHeight = tabsWrapper.offsetHeight;
          }
          const targetListElement = document == null ? void 0 : document.querySelector("#list-" + e);
          const scrollContainer = scrollDom ? document == null ? void 0 : document.querySelector(scrollDom) : null;
          const offsetElement = offsetDom ? document == null ? void 0 : document.querySelector(offsetDom) : null;
          const extraOffset = offsetElement ? offsetElement.clientHeight : 0;
          handleUnobserver();
          tabLocatingRef.current = true;
          if (targetListElement && scrollContainer) {
            if (e === ((_a = list[0]) == null ? void 0 : _a.id)) {
              if (productSelectWrapper) {
                const wrapperOffsetTop = getOffsetTopRelativeToScrollContainer(productSelectWrapper, scrollContainer);
                scrollContainer.scrollTop = wrapperOffsetTop - extraOffset;
              }
            } else {
              const listOffsetTop = getOffsetTopRelativeToScrollContainer(targetListElement, scrollContainer);
              scrollContainer.scrollTop = listOffsetTop - tabsHeight - extraOffset;
            }
          }
          setCurrentGroupId(e);
          debouncedScroll.run(e);
          setTimeout(() => {
            tabLocatingRef.current = false;
            handleObserver();
          }, 500);
        } catch (error) {
          console.error("Tab onChange error:", error);
          tabLocatingRef.current = false;
          setCurrentGroupId(e);
        }
      }
    }
  )) : /* @__PURE__ */ import_react.default.createElement("p", null, /* @__PURE__ */ import_react.default.createElement("br", null)), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-product-select-product-list" }, renderContent()));
};
var TabProduct_default = TabProduct;
