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 ProductCardV2 from "./ProductCard/ProductCardV2.js";
import CategoryTabs from "./CategoryTabs/index.js";
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { locales } from "@pisell/utils";
import { Input, PisellEmpty } 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",
	"version",
	"cartElementId"
];
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, version = "v1", cartElementId } = _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("");
	const [scrollParent, setScrollParent] = useState(null);
	const isIndicatorVisibleRef = useRef(false);
	const containerRef = useRef(null);
	const _customScrollParent = customScrollParent || scrollDom;
	const gridComponents = useMemo(() => {
		return createGridComponents(layout);
	}, [layout]);
	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]);
	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(_categories[0].key);
		else if (!_categories.find((category) => category.key === activeKey)) switchCategory(_categories[0].key);
	}, [_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("");
	const handleItemIntersectionIn = useCallback((item) => {
		const _key = String(item.__categoryId);
		if (!isIndicatorVisibleRef.current && _key && _key !== lastActiveKeyRef.current) {
			setActiveKey(_key);
			lastActiveKeyRef.current = _key;
		}
	}, []);
	const _listContext = useMemo(() => {
		return {
			onItemIntersectionIn: handleItemIntersectionIn,
			onItemIntersectionOut: () => {}
		};
	}, [handleItemIntersectionIn]);
	const switchCategory = (key) => {
		setActiveKey(key);
		lastActiveKeyRef.current = key;
		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 }),
		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 ? /* @__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 : _groupedList,
		_customScrollParent: scrollParent,
		context: _listContext,
		components: gridComponents,
		itemContent: (index, item, context) => {
			if (loading) return /* @__PURE__ */ React.createElement(ProductCardSkeleton, {
				index,
				item
			});
			if (version === "v2") return /* @__PURE__ */ React.createElement(ProductCardV2, {
				index,
				item,
				context,
				value,
				onChange,
				decorateConfig: productListSetting,
				cartElementId
			});
			return /* @__PURE__ */ React.createElement(ProductCard$1, {
				index,
				item,
				context,
				onSelectCover: (e) => {
					_onChange(e, "cover");
				},
				onSelectInfo: (e) => {
					_onChange(e, "info");
				},
				isSelected: item.id === value,
				decorateConfig: productListSetting
			});
		}
	})));
};
//#endregion
export { PREFIX, index as default };
