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/plus/productSelect/index.tsx
var productSelect_exports = {};
__export(productSelect_exports, {
  PREFIX: () => PREFIX,
  default: () => productSelect_default
});
module.exports = __toCommonJS(productSelect_exports);
var import_react = __toESM(require("react"));
var import_classnames = __toESM(require("classnames"));
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_SearchLg = __toESM(require("@pisell/icon/es/SearchLg"));
var import_CategoryTabs = __toESM(require("./CategoryTabs"));
var import_ProductList = __toESM(require("./ProductList"));
var import_useToken = require("./hooks/useToken");
var import_utils2 = require("./utils");
var import_IntersectionObserver = __toESM(require("./components/IntersectionObserver"));
var import_ProductCard = __toESM(require("./ProductCard"));
var import_locales = __toESM(require("./locales"));
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_materials2 = require("@pisell/materials");
var import_index = require("./index.less");
var import_utils3 = require("@pisell/utils");
var MOCK_DATA = (() => {
  const mockData = [];
  mockData.push({
    __typename: "category",
    id: "_c1_1"
  });
  for (let productIndex = 0; productIndex < 4; productIndex++) {
    mockData.push({
      __typename: "product",
      id: "_pi" + productIndex
    });
  }
  return mockData;
})();
var PREFIX = "pisell-product-select";
var CONTAINER_CLASS = `${PREFIX}-wrapper`;
var index = ({
  dataSource = [],
  emptyDescription,
  showSearch = true,
  scrollDom,
  offsetDom,
  style = {},
  token: customToken,
  onChange,
  value,
  selectedItems,
  productListSetting = {},
  customScrollParent,
  loading = false,
  layout,
  hideCategoryWhenOne = false,
  tabSwitchMode = "anchor",
  scenario = "default",
  compact = false,
  ...rest
}) => {
  var _a, _b;
  const context = (0, import_useEngineContext.default)();
  import_utils.locales.init(
    import_locales.default,
    ((_b = (_a = context.appHelper.utils) == null ? void 0 : _a.storage) == null ? void 0 : _b.get("umi_locale")) || "en"
  );
  const searchRef = (0, import_react.useRef)(null);
  const [keyword, setKeyword] = (0, import_react.useState)("");
  const [activeKey, setActiveKey] = (0, import_react.useState)(["0"]);
  const [scrollParent, setScrollParent] = (0, import_react.useState)(null);
  const isIndicatorVisibleRef = (0, import_react.useRef)(false);
  const containerRef = (0, import_react.useRef)(null);
  const _customScrollParent = customScrollParent || scrollDom;
  const gridComponents = (0, import_react.useMemo)(() => {
    return (0, import_ProductList.createGridComponents)(layout, {
      tabSwitchMode,
      gap: compact ? 6 : 12
    });
  }, [layout, tabSwitchMode, compact]);
  const _filteredList = (0, import_react.useMemo)(() => {
    if (!keyword) return dataSource;
    return dataSource.filter((product) => {
      if (typeof (product == null ? void 0 : product.title) !== "string") return false;
      return product.title.toLowerCase().indexOf(keyword.toLowerCase()) !== -1;
    });
  }, [keyword, dataSource]);
  const _groupedList = (0, import_react.useMemo)(() => {
    let _list = _filteredList || [];
    return (0, import_utils2.groupProductsByCategory)(_list);
  }, [_filteredList]);
  const _displayList = (0, import_react.useMemo)(() => {
    if (tabSwitchMode === "anchor") {
      return _groupedList;
    }
    if (!activeKey) {
      return _groupedList;
    }
    return _groupedList.filter((item) => {
      if (item.__typename === "category") {
        return false;
      }
      if ((0, import_utils3.isArr)(activeKey)) {
        if (activeKey.includes("0")) {
          return true;
        }
        return activeKey.includes(String(item.__categoryId));
      }
      if (activeKey === "0") {
        return true;
      }
      return String(item.__categoryId) === activeKey;
    });
  }, [tabSwitchMode, _groupedList, activeKey]);
  const _categories = (0, import_react.useMemo)(() => {
    return _groupedList.filter((item) => item.__typename === "category").map((item) => {
      return {
        ...item,
        key: String(item.id),
        label: item.name
      };
    });
  }, [_groupedList]);
  const isHideCategory = (0, import_react.useMemo)(() => {
    if ((productListSetting == null ? void 0 : productListSetting.layout) === 0) {
      return true;
    }
    if (hideCategoryWhenOne) {
      return (_categories == null ? void 0 : _categories.length) === 1 || !(_categories == null ? void 0 : _categories.length);
    }
    return false;
  }, [_categories, hideCategoryWhenOne, productListSetting == null ? void 0 : productListSetting.layout]);
  (0, import_react.useEffect)(() => {
    if (!(_categories == null ? void 0 : _categories.length)) {
      setActiveKey([]);
      return;
    }
    if (!activeKey) {
      switchCategory("0");
    } else {
      const found = _categories.find((category) => category.key === activeKey);
      if (!found) switchCategory("0");
    }
  }, [_categories]);
  (0, import_react.useLayoutEffect)(() => {
    if (_customScrollParent) {
      const sp = (0, import_utils2.getElementByIdentifier)(_customScrollParent);
      setScrollParent(sp);
    }
  }, [_customScrollParent]);
  const token = (0, import_useToken.useToken)(customToken);
  const cssVars = (0, import_react.useMemo)(() => (0, import_useToken.genCSSVars)(token), [token]);
  const mergedStyle = (0, import_react.useMemo)(() => {
    const baseStyle = {
      ...cssVars,
      ...style
    };
    if (!scrollParent) return baseStyle;
    if (scrollParent !== containerRef.current) {
      return {
        ...baseStyle,
        overflow: "unset",
        height: "unset"
      };
    }
    return baseStyle;
  }, [cssVars, style, scrollParent]);
  const disabled = (0, import_react.useMemo)(() => {
    return !!(productListSetting == null ? void 0 : productListSetting.list_max_length) && Array.isArray(selectedItems) && (selectedItems == null ? void 0 : selectedItems.length) > 0;
  }, [productListSetting, selectedItems]);
  const _onChange = (0, import_react.useCallback)(
    (value2, type) => {
      if (disabled) return;
      onChange == null ? void 0 : onChange(value2, type);
    },
    [disabled, onChange]
  );
  const debounceIndicator = (0, import_react.useCallback)((delay) => {
    isIndicatorVisibleRef.current = true;
    const timeoutId = setTimeout(() => {
      isIndicatorVisibleRef.current = false;
    }, delay);
    return () => clearTimeout(timeoutId);
  }, []);
  const lastActiveKeyRef = (0, import_react.useRef)("");
  const handleItemIntersectionIn = (0, import_react.useCallback)((item) => {
    if (tabSwitchMode === "switch") {
      return;
    }
    const _key = String(item.__categoryId);
    if (!isIndicatorVisibleRef.current && _key && _key !== lastActiveKeyRef.current) {
      setActiveKey(_key);
      lastActiveKeyRef.current = _key;
    }
  }, [tabSwitchMode]);
  const _listContext = (0, import_react.useMemo)(() => {
    return {
      onItemIntersectionIn: handleItemIntersectionIn,
      onItemIntersectionOut: () => {
      }
    };
  }, [handleItemIntersectionIn]);
  const switchCategory = (key) => {
    setActiveKey((0, import_utils3.isArr)(key) ? key : [key]);
    lastActiveKeyRef.current = key;
    if (tabSwitchMode === "switch") {
      return;
    }
    debounceIndicator(300);
    const categoryIndex = _groupedList.findIndex(
      (item) => item.__typename === "category" && String(item.id) === key
    );
    const _scrollParent = scrollParent || containerRef.current;
    if (!_scrollParent || !containerRef.current) return;
    const target = document.getElementById(`ps_category_${key}`);
    if (!target) return;
    const productSelectWrapper = document.querySelector(
      `.${PREFIX}-wrapper`
    );
    const tabsWrapper = document.querySelector(`.${PREFIX}__tabs-wrapper`);
    const tabsHeight = (tabsWrapper == null ? void 0 : tabsWrapper.offsetHeight) || 0;
    const offsetElement = (0, import_utils2.getElementByIdentifier)(offsetDom);
    const extraOffset = offsetElement ? offsetElement.clientHeight : 0;
    if (categoryIndex === 0) {
      if (productSelectWrapper) {
        const wrapperOffsetTop = (0, import_utils2.getOffsetTopRelativeToScrollContainer)(
          productSelectWrapper,
          _scrollParent
        );
        _scrollParent.scrollTop = wrapperOffsetTop - extraOffset;
      }
      return;
    } else {
      const listOffsetTop = (0, import_utils2.getOffsetTopRelativeToScrollContainer)(
        target,
        _scrollParent
      );
      _scrollParent.scrollTop = listOffsetTop - tabsHeight - extraOffset;
    }
  };
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      ref: containerRef,
      className: (0, import_classnames.default)(PREFIX, CONTAINER_CLASS, {
        disabled,
        [`${PREFIX}-compact`]: compact
      }),
      style: mergedStyle
    },
    showSearch ? /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__search-wrapper` }, /* @__PURE__ */ import_react.default.createElement(
      import_materials.Input,
      {
        ref: searchRef,
        prefix: /* @__PURE__ */ import_react.default.createElement(import_SearchLg.default, null),
        style: { height: 44 },
        placeholder: import_utils.locales.getText("pisell2.product-select.search"),
        allowClear: true,
        value: keyword,
        onChange: (e) => {
          setKeyword(e.target.value);
        }
      }
    )) : null,
    !isHideCategory ? tabSwitchMode === "switch" ? /* @__PURE__ */ import_react.default.createElement(
      import_materials.PisellTabbarTemplate1,
      {
        style: { position: "sticky", top: 0, zIndex: 10, background: "var(--ps-container-bg, #fff)" },
        dataSource: _categories,
        value: activeKey,
        onChange: switchCategory,
        className: `${PREFIX}__tabs-wrapper`
      }
    ) : /* @__PURE__ */ import_react.default.createElement(
      import_CategoryTabs.default,
      {
        activeKey,
        items: _categories,
        onChange: switchCategory,
        loading,
        skeleton: /* @__PURE__ */ import_react.default.createElement(import_CategoryTabs.CategorySkeleton, null)
      }
    ) : null,
    !loading && !(_groupedList == null ? void 0 : _groupedList.length) ? /* @__PURE__ */ import_react.default.createElement(
      import_materials2.PisellEmpty,
      {
        description: emptyDescription || import_utils.locales.getText("pisell2.product-select.empty")
      }
    ) : /* @__PURE__ */ import_react.default.createElement(
      import_IntersectionObserver.default,
      {
        rootMargin: "-270px 0px -270px 0px",
        priorityMode: "top"
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_ProductList.default,
        {
          className: (0, import_classnames.default)(`${PREFIX}__product-list`, {
            [`${PREFIX}__product-list_hide_category`]: isHideCategory
          }),
          loading,
          data: loading ? MOCK_DATA : _displayList,
          _customScrollParent: scrollParent,
          context: _listContext,
          components: gridComponents,
          itemContent: (index2, item, context2) => {
            if (loading) {
              return /* @__PURE__ */ import_react.default.createElement(
                import_ProductCard.ProductCardSkeleton,
                {
                  index: index2,
                  item,
                  imageWidth: productListSetting == null ? void 0 : productListSetting.imgWidth,
                  imageHeight: productListSetting == null ? void 0 : productListSetting.imgHeight,
                  style: {
                    gap: (productListSetting == null ? void 0 : productListSetting.gap) ?? 20,
                    padding: (productListSetting == null ? void 0 : productListSetting.skuCardPaddingY) !== void 0 || (productListSetting == null ? void 0 : productListSetting.skuCardPaddingX) !== void 0 ? `${(productListSetting == null ? void 0 : productListSetting.skuCardPaddingY) ?? 8}px ${(productListSetting == null ? void 0 : productListSetting.skuCardPaddingX) ?? 8}px` : void 0,
                    minHeight: compact ? 88 : void 0
                  }
                }
              );
            }
            return /* @__PURE__ */ import_react.default.createElement(
              import_ProductCard.default,
              {
                index: index2,
                item,
                context: context2,
                scenario,
                onSelectCover: (e) => {
                  _onChange(e, "cover");
                },
                onSelectInfo: (e) => {
                  _onChange(e, "info");
                },
                isSelected: item.id === value,
                decorateConfig: {
                  ...productListSetting,
                  gap: (productListSetting == null ? void 0 : productListSetting.gap) ?? 20
                }
              }
            );
          }
        }
      )
    )
  );
};
var productSelect_default = index;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PREFIX
});
