import { _objectSpread2 } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _objectWithoutProperties } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import useEngineContext from "../../hooks/useEngineContext.js";
import IntersectionObserverProvider from "./components/IntersectionObserver.js";
import CategorySkeleton from "./CategoryTabs/CategorySkeleton.js";
import { createGridComponents } from "./ProductList/gridComponents.js";
import ProductList from "./ProductList/index.js";
import { genCSSVars, useToken } from "./hooks/useToken.js";
import { getElementByIdentifier, getOffsetTopRelativeToScrollContainer, groupProductsByCategory } from "./utils.js";
import locales_default from "./locales.js";
import ProductCardSkeleton from "./ProductCard/ProductCardSkeleton.js";
import ProductCard$1 from "./ProductCard/index.js";
import CategoryTabs from "./CategoryTabs/index.js";
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { isArr, locales } from "@pisell/utils";
import { Input, PisellEmpty, PisellTabbarTemplate1 } from "@pisell/materials";
import SearchLg from "@pisell/icon/es/SearchLg";
import classNames from "classnames";
import "./index.less";
//#region src/plus/productSelect/index.tsx
const _excluded = [
	"dataSource",
	"emptyDescription",
	"showSearch",
	"scrollDom",
	"offsetDom",
	"style",
	"token",
	"onChange",
	"value",
	"selectedItems",
	"productListSetting",
	"customScrollParent",
	"loading",
	"layout",
	"hideCategoryWhenOne",
	"tabSwitchMode",
	"scenario",
	"compact"
];
const 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;
})();
const PREFIX = "pisell-product-select";
const CONTAINER_CLASS = `${PREFIX}-wrapper`;
const index = (_ref) => {
	var _context$appHelper$ut;
	let { 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 } = _ref;
	_objectWithoutProperties(_ref, _excluded);
	const context = useEngineContext();
	locales.init(locales_default, ((_context$appHelper$ut = context.appHelper.utils) === null || _context$appHelper$ut === void 0 || (_context$appHelper$ut = _context$appHelper$ut.storage) === null || _context$appHelper$ut === void 0 ? void 0 : _context$appHelper$ut.get("umi_locale")) || "en");
	const searchRef = useRef(null);
	const [keyword, setKeyword] = useState("");
	const [activeKey, setActiveKey] = useState(["0"]);
	const [scrollParent, setScrollParent] = useState(null);
	const isIndicatorVisibleRef = useRef(false);
	const containerRef = useRef(null);
	const _customScrollParent = customScrollParent || scrollDom;
	const gridComponents = useMemo(() => {
		return createGridComponents(layout, {
			tabSwitchMode,
			gap: compact ? 6 : 12
		});
	}, [
		layout,
		tabSwitchMode,
		compact
	]);
	const _filteredList = useMemo(() => {
		if (!keyword) return dataSource;
		return dataSource.filter((product) => {
			if (typeof (product === null || product === void 0 ? void 0 : product.title) !== "string") return false;
			return product.title.toLowerCase().indexOf(keyword.toLowerCase()) !== -1;
		});
	}, [keyword, dataSource]);
	const _groupedList = useMemo(() => {
		return groupProductsByCategory(_filteredList || []);
	}, [_filteredList]);
	/**
	* @title: 根据模式获取显示的数据列表
	* @description: anchor模式显示全部分类数据，switch模式只显示当前选中分类的产品
	*/
	const _displayList = useMemo(() => {
		if (tabSwitchMode === "anchor") return _groupedList;
		if (!activeKey) return _groupedList;
		return _groupedList.filter((item) => {
			if (item.__typename === "category") return false;
			if (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 = useMemo(() => {
		return _groupedList.filter((item) => item.__typename === "category").map((item) => {
			return _objectSpread2(_objectSpread2({}, item), {}, {
				key: String(item.id),
				label: item.name
			});
		});
	}, [_groupedList]);
	/**
	* @title: 是否隐藏分类
	* @description:
	* @param {*} useMemo
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-10-09 15:13
	*/
	const isHideCategory = useMemo(() => {
		if ((productListSetting === null || productListSetting === void 0 ? void 0 : productListSetting.layout) === 0) return true;
		if (hideCategoryWhenOne) return (_categories === null || _categories === void 0 ? void 0 : _categories.length) === 1 || !(_categories === null || _categories === void 0 ? void 0 : _categories.length);
		return false;
	}, [
		_categories,
		hideCategoryWhenOne,
		productListSetting === null || productListSetting === void 0 ? void 0 : productListSetting.layout
	]);
	useEffect(() => {
		if (!(_categories === null || _categories === void 0 ? void 0 : _categories.length)) {
			setActiveKey([]);
			return;
		}
		if (!activeKey) switchCategory("0");
		else if (!_categories.find((category) => category.key === activeKey)) switchCategory("0");
	}, [_categories]);
	useLayoutEffect(() => {
		if (_customScrollParent) setScrollParent(getElementByIdentifier(_customScrollParent));
	}, [_customScrollParent]);
	const token = useToken(customToken);
	const cssVars = useMemo(() => genCSSVars(token), [token]);
	const mergedStyle = useMemo(() => {
		const baseStyle = _objectSpread2(_objectSpread2({}, cssVars), style);
		if (!scrollParent) return baseStyle;
		if (scrollParent !== containerRef.current) return _objectSpread2(_objectSpread2({}, baseStyle), {}, {
			overflow: "unset",
			height: "unset"
		});
		return baseStyle;
	}, [
		cssVars,
		style,
		scrollParent
	]);
	const disabled = useMemo(() => {
		return !!(productListSetting === null || productListSetting === void 0 ? void 0 : productListSetting.list_max_length) && Array.isArray(selectedItems) && (selectedItems === null || selectedItems === void 0 ? void 0 : selectedItems.length) > 0;
	}, [productListSetting, selectedItems]);
	const _onChange = useCallback((value, type) => {
		if (disabled) return;
		onChange === null || onChange === void 0 || onChange(value, type);
	}, [disabled, onChange]);
	const debounceIndicator = useCallback((delay) => {
		isIndicatorVisibleRef.current = true;
		const timeoutId = setTimeout(() => {
			isIndicatorVisibleRef.current = false;
		}, delay);
		return () => clearTimeout(timeoutId);
	}, []);
	const lastActiveKeyRef = useRef("");
	/**
	* @title: 项目进入视口时的回调
	* @description: 仅在anchor模式下生效，用于滚动时自动切换高亮的分类Tab
	*/
	const handleItemIntersectionIn = 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 = useMemo(() => {
		return {
			onItemIntersectionIn: handleItemIntersectionIn,
			onItemIntersectionOut: () => {}
		};
	}, [handleItemIntersectionIn]);
	/**
	* @title: 切换分类
	* @description: anchor模式下滚动到对应锚点，switch模式下只切换数据
	*/
	const switchCategory = (key) => {
		setActiveKey(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 || tabsWrapper === void 0 ? void 0 : tabsWrapper.offsetHeight) || 0;
		const offsetElement = getElementByIdentifier(offsetDom);
		const extraOffset = offsetElement ? offsetElement.clientHeight : 0;
		if (categoryIndex === 0) {
			if (productSelectWrapper) _scrollParent.scrollTop = getOffsetTopRelativeToScrollContainer(productSelectWrapper, _scrollParent) - extraOffset;
			return;
		} else _scrollParent.scrollTop = getOffsetTopRelativeToScrollContainer(target, _scrollParent) - tabsHeight - extraOffset;
	};
	return /* @__PURE__ */ React.createElement("div", {
		ref: containerRef,
		className: classNames(PREFIX, CONTAINER_CLASS, {
			disabled,
			[`${PREFIX}-compact`]: compact
		}),
		style: mergedStyle
	}, showSearch ? /* @__PURE__ */ React.createElement("div", { className: `${PREFIX}__search-wrapper` }, /* @__PURE__ */ React.createElement(Input, {
		ref: searchRef,
		prefix: /* @__PURE__ */ React.createElement(SearchLg, null),
		style: { height: 44 },
		placeholder: locales.getText("pisell2.product-select.search"),
		allowClear: true,
		value: keyword,
		onChange: (e) => {
			setKeyword(e.target.value);
		}
	})) : null, !isHideCategory ? tabSwitchMode === "switch" ? /* @__PURE__ */ React.createElement(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__ */ React.createElement(CategoryTabs, {
		activeKey,
		items: _categories,
		onChange: switchCategory,
		loading,
		skeleton: /* @__PURE__ */ React.createElement(CategorySkeleton, null)
	}) : null, !loading && !(_groupedList === null || _groupedList === void 0 ? void 0 : _groupedList.length) ? /* @__PURE__ */ React.createElement(PisellEmpty, { description: emptyDescription || locales.getText("pisell2.product-select.empty") }) : /* @__PURE__ */ React.createElement(IntersectionObserverProvider, {
		rootMargin: "-270px 0px -270px 0px",
		priorityMode: "top"
	}, /* @__PURE__ */ React.createElement(ProductList, {
		className: classNames(`${PREFIX}__product-list`, { [`${PREFIX}__product-list_hide_category`]: isHideCategory }),
		loading,
		data: loading ? MOCK_DATA : _displayList,
		_customScrollParent: scrollParent,
		context: _listContext,
		components: gridComponents,
		itemContent: (index, item, context) => {
			var _productListSetting$g2;
			if (loading) {
				var _productListSetting$g, _productListSetting$s, _productListSetting$s2;
				return /* @__PURE__ */ React.createElement(ProductCardSkeleton, {
					index,
					item,
					imageWidth: productListSetting === null || productListSetting === void 0 ? void 0 : productListSetting.imgWidth,
					imageHeight: productListSetting === null || productListSetting === void 0 ? void 0 : productListSetting.imgHeight,
					style: {
						gap: (_productListSetting$g = productListSetting === null || productListSetting === void 0 ? void 0 : productListSetting.gap) !== null && _productListSetting$g !== void 0 ? _productListSetting$g : 20,
						padding: (productListSetting === null || productListSetting === void 0 ? void 0 : productListSetting.skuCardPaddingY) !== void 0 || (productListSetting === null || productListSetting === void 0 ? void 0 : productListSetting.skuCardPaddingX) !== void 0 ? `${(_productListSetting$s = productListSetting === null || productListSetting === void 0 ? void 0 : productListSetting.skuCardPaddingY) !== null && _productListSetting$s !== void 0 ? _productListSetting$s : 8}px ${(_productListSetting$s2 = productListSetting === null || productListSetting === void 0 ? void 0 : productListSetting.skuCardPaddingX) !== null && _productListSetting$s2 !== void 0 ? _productListSetting$s2 : 8}px` : void 0,
						minHeight: compact ? 88 : void 0
					}
				});
			}
			return /* @__PURE__ */ React.createElement(ProductCard$1, {
				index,
				item,
				context,
				scenario,
				onSelectCover: (e) => {
					_onChange(e, "cover");
				},
				onSelectInfo: (e) => {
					_onChange(e, "info");
				},
				isSelected: item.id === value,
				decorateConfig: _objectSpread2(_objectSpread2({}, productListSetting), {}, { gap: (_productListSetting$g2 = productListSetting === null || productListSetting === void 0 ? void 0 : productListSetting.gap) !== null && _productListSetting$g2 !== void 0 ? _productListSetting$g2 : 20 })
			});
		}
	})));
};
//#endregion
export { PREFIX, index as default };
