import { getText } from "../../../../locales/index.js";
import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import IconFont from "../../../iconfont/index.js";
import PisellCards from "../../../PisellCards/index.js";
import { PisellFind } from "../../../pisellFind/index.js";
import PisellSuperTabs_default from "../../../PisellSuperTabs/index.js";
import { getExpandConfig } from "../../constants.js";
import useActiveKey from "../../hooks/useActiveKey.js";
import useExpand from "../../hooks/useExpand.js";
import mock_default from "../../mock.js";
import { DEFAULT_LEVEL_CONFIG, LEVEL_ADD_ITEMS } from "./constants.js";
import { addDataSourceItemsByKey, getDefaultActiveKey } from "./utils/index.js";
import React, { forwardRef, useCallback, useEffect, useId, useImperativeHandle, useMemo, useRef } from "react";
import classNames from "classnames";
import "../../PisellTabbar.less";
//#region src/components/PisellTabbar/template/Template1/PisellTabbar.tsx
/**
* PisellTabbar - 多层级 Tabbar 组件
*
* 支持最多 3 层级的 Tab 导航，每层级可独立展开/收起
*
* @component
* @example
* ```tsx
* <PisellTabbar
*   dataSource={categoryData}
*   value={[1, 10, 100]}
*   onChange={(value) => console.log('当前选中:', value)}
* />
* ```
*/
const PisellTabbar = (props, ref) => {
	const { dataSource = (props === null || props === void 0 ? void 0 : props.__designMode) ? mock_default : mock_default, value, onChange, className, style, levelConfig: customLevelConfig, expandConfig: customExpandConfig, maxLevel = 3, onSearch } = props;
	const containerRef = useRef(null);
	const searchRef = useRef(null);
	/**
	* 每个 PisellTabbarTemplate1 实例使用独立的 DOM id（保留历史前缀），
	* 避免同页面有多个 Tabbar（如资源选择 modal + View All modal 同时挂载，
	* 或前一个 modal 的 destroyOnClose 还在动画延迟期）时 `document.querySelector`
	* 命中错误那一个：PisellFind 的搜索弹窗 portal 会挂到隐藏节点 → 看似"无反应"，
	* 二级 panel 的 portalContainer 也会渲染到错误位置。
	*
	* 使用 `useId()` 保证 SSR 一致并避免 hydration 失配；冒号在 id selector 里
	* 不合法，统一替换。
	*/
	const reactId = useId();
	const tabbarId = useMemo(() => `sku-list-tabbar-temp1-${reactId.replace(/:/g, "")}`, [reactId]);
	const { setActiveKey, getActiveKey, _setActiveKey, activeKey, setCacheActiveKey, resetActiveKey } = useActiveKey({
		initialActiveKey: value || getDefaultActiveKey(dataSource, "id"),
		onChange
	});
	const { expand, toggleExpand, getExpand } = useExpand();
	const expandConfig = customExpandConfig || getExpandConfig();
	const level1Value = useMemo(() => {
		return getActiveKey(0);
	}, [activeKey]);
	const level2Value = useMemo(() => {
		return getActiveKey(1);
	}, [activeKey]);
	const level3Value = useMemo(() => {
		return getActiveKey(2);
	}, [activeKey]);
	/**
	* 打开搜索模式
	*/
	const openSearchMode = () => {
		setCacheActiveKey(activeKey);
		_setActiveKey([]);
		onChange === null || onChange === void 0 || onChange([]);
	};
	/**
	* 关闭搜索模式
	*/
	const closeSearchMode = () => {
		onSearch === null || onSearch === void 0 || onSearch("");
		resetActiveKey();
	};
	useImperativeHandle(ref, () => {
		var _searchRef$current;
		if (props === null || props === void 0 ? void 0 : props.__designMode) return containerRef.current;
		return { closeSearchMode: searchRef === null || searchRef === void 0 || (_searchRef$current = searchRef.current) === null || _searchRef$current === void 0 ? void 0 : _searchRef$current.close };
	});
	/**
	* 同步外部 value 到内部状态
	*/
	useEffect(() => {
		if (value) _setActiveKey(value);
	}, [JSON.stringify(value)]);
	/**
	* 获取层级配置
	*/
	const getLevelConfig = useCallback((level) => {
		return _objectSpread2(_objectSpread2({}, DEFAULT_LEVEL_CONFIG[level]), customLevelConfig === null || customLevelConfig === void 0 ? void 0 : customLevelConfig[level]);
	}, [customLevelConfig]);
	/**
	* 处理一级 Tab 切换
	*/
	const handleLevel1Change = useCallback((key, item) => {
		var _item$children;
		setActiveKey(0, key, (item === null || item === void 0 || (_item$children = item.children) === null || _item$children === void 0 ? void 0 : _item$children.length) ? 0 : void 0);
	}, [setActiveKey, activeKey]);
	/**
	* 处理二级 Tab 切换
	*/
	const handleLevel2Change = useCallback((key, item) => {
		var _item$children2;
		setActiveKey(1, key, (item === null || item === void 0 || (_item$children2 = item.children) === null || _item$children2 === void 0 ? void 0 : _item$children2.length) ? 0 : void 0);
	}, [setActiveKey, activeKey]);
	/**
	* 处理三级 Tab 切换
	*/
	const handleLevel3Change = useCallback((key) => {
		setActiveKey(2, key);
	}, [setActiveKey, activeKey]);
	/**
	* 渲染 level2/level3 自定义点击卡片（展开按钮）
	*/
	const renderExpandCard = useCallback((cardProps, level, isExpanded) => {
		var _cardProps$active;
		const config = expandConfig[isExpanded ? "active" : "inactive"];
		const levelCfg = getLevelConfig(level);
		return /* @__PURE__ */ React.createElement(PisellCards.TextCard, _objectSpread2(_objectSpread2({}, cardProps), {}, {
			text: config.text,
			variant: "outlined",
			widthMode: "auto",
			prefixIcon: /* @__PURE__ */ React.createElement(IconFont, {
				type: config.icon,
				style: {
					color: "#000",
					fontSize: 20
				}
			}),
			textConfig: {
				textAlign: "center",
				color: "#000000",
				flex: "none"
			},
			style: {
				borderRadius: "20px",
				background: "#ffffff",
				display: "flex",
				alignItems: "center",
				justifyContent: "center",
				height: levelCfg.cardHeight,
				minWidth: 100
			},
			width: "auto",
			active: _objectSpread2(_objectSpread2({}, cardProps.active), {}, { style: _objectSpread2(_objectSpread2({}, (_cardProps$active = cardProps.active) === null || _cardProps$active === void 0 ? void 0 : _cardProps$active.style), {}, {
				color: "#ffffff",
				background: "#7f56d9"
			}) })
		}));
	}, [
		expandConfig,
		activeKey,
		getLevelConfig
	]);
	const renderSearch = useCallback((itemProps, level) => {
		return /* @__PURE__ */ React.createElement(PisellFind, {
			showHistory: false,
			modalWidth: "100%",
			ref: searchRef,
			onSearch: (e) => {
				onSearch === null || onSearch === void 0 || onSearch(e);
			},
			getContainer: () => {
				return document.querySelector(`#${tabbarId}`) || document.body;
			},
			modalStyle: { width: "100%" },
			onOpen: openSearchMode,
			onClose: closeSearchMode,
			trigger: /* @__PURE__ */ React.createElement(PisellCards.MultilevelCard, _objectSpread2(_objectSpread2({}, itemProps), {}, { card: (cardProps) => {
				return renderNormalCard(_objectSpread2(_objectSpread2({}, cardProps), {}, { text: /* @__PURE__ */ React.createElement("div", { style: {
					display: "flex",
					alignItems: "center",
					gap: 4
				} }, /* @__PURE__ */ React.createElement(IconFont, {
					type: "pisell2-search-lg",
					style: {
						color: "#000",
						fontSize: 20
					}
				}), /* @__PURE__ */ React.createElement(IconFont, {
					type: "pisell2-scan",
					style: {
						color: "#000",
						fontSize: 20
					}
				}), /* @__PURE__ */ React.createElement("span", null, getText("table-filter-find"))) }), level);
			} }))
		});
	}, [activeKey, tabbarId]);
	/**
	* 渲染 level2/level3 普通卡片
	*/
	const renderNormalCard = useCallback((cardProps, level) => {
		var _cardProps$active2;
		const { dataSource: itemData } = cardProps;
		const levelCfg = getLevelConfig(level);
		return /* @__PURE__ */ React.createElement(PisellCards.TextCard, _objectSpread2(_objectSpread2({ text: itemData.name }, cardProps), {}, {
			variant: "outlined",
			widthMode: "auto",
			textConfig: {
				textAlign: "center",
				color: "#000",
				maxLines: 2,
				ellipsis: true
			},
			style: {
				height: levelCfg.cardHeight,
				borderRadius: "20px",
				background: "#ffffff",
				minWidth: 100
			},
			width: "auto",
			active: _objectSpread2(_objectSpread2({}, cardProps.active), {}, { style: _objectSpread2(_objectSpread2({}, (_cardProps$active2 = cardProps.active) === null || _cardProps$active2 === void 0 ? void 0 : _cardProps$active2.style), {}, {
				color: "#fff",
				background: "#7f56d9"
			}) })
		}));
	}, [getLevelConfig]);
	/**
	* 一级 Tabbar 数据源
	*/
	const level1DataSource = useMemo(() => addDataSourceItemsByKey(dataSource, LEVEL_ADD_ITEMS.level1), [dataSource]);
	/**
	* 渲染一级 Tab Item
	*/
	const renderLevel1Item = useCallback((itemProps) => {
		const { dataSource: itemData } = itemProps;
		const isExpanded = getExpand("level1");
		if (itemData === null || itemData === void 0 ? void 0 : itemData.customClick) {
			if (itemProps.dataSource.key === "search") return renderSearch(itemProps, "level1");
			if (itemProps.dataSource.key === "expand") return /* @__PURE__ */ React.createElement(PisellCards.MultilevelCard, _objectSpread2(_objectSpread2({}, itemProps), {}, {
				card: (cardProps) => renderExpandCard(cardProps, "level1", isExpanded),
				onClick: () => toggleExpand("level1")
			}));
			return null;
		}
		return /* @__PURE__ */ React.createElement(PisellCards.MultilevelCard, _objectSpread2(_objectSpread2({}, itemProps), {}, {
			card: (cardProps) => renderNormalCard(cardProps, "level1"),
			panel: (panelProps) => {
				var _panelProps$dataSourc;
				if ((panelProps === null || panelProps === void 0 || (_panelProps$dataSourc = panelProps.dataSource) === null || _panelProps$dataSourc === void 0 || (_panelProps$dataSourc = _panelProps$dataSourc.children) === null || _panelProps$dataSourc === void 0 ? void 0 : _panelProps$dataSourc.length) && maxLevel >= 2) return renderLevel2Panel(panelProps);
				return null;
			},
			panelContainer: () => document.querySelector(`.pisell-super-tabs-slot-bottom-${tabbarId}`)
		}));
	}, [
		getLevelConfig,
		getExpand,
		toggleExpand,
		maxLevel,
		activeKey,
		tabbarId
	]);
	/**
	* 渲染二级 Tabbar 面板
	*/
	const renderLevel2Panel = useCallback((panelProps) => {
		if (maxLevel < 2) return null;
		let _dataSource = panelProps.dataSource.children || [];
		if (_dataSource.length) _dataSource = addDataSourceItemsByKey(_dataSource, LEVEL_ADD_ITEMS.level2);
		const level2Config = getLevelConfig("level2");
		const isExpanded2 = getExpand("level2");
		const skuId = `sku-list-tabbar-${panelProps.dataSource.id}`;
		return /* @__PURE__ */ React.createElement(PisellSuperTabs_default, {
			id: skuId,
			isControlled: true,
			tabItemStyle: {},
			dataSource: _dataSource,
			value: level2Value,
			onChange: handleLevel2Change,
			rowKey: "id",
			style: {
				flex: 1,
				background: level2Config.superTabsBg
			},
			gridProps: {
				direction: "horizontal",
				gap: 4,
				wrap: isExpanded2 ? "wrap" : "nowrap",
				startSlot: /* @__PURE__ */ React.createElement("div", { style: { paddingLeft: level2Config.paddingLeft } }, /* @__PURE__ */ React.createElement(IconFont, {
					type: "pisell2-trend-down-01",
					style: {
						color: "#fff",
						fontSize: 24,
						marginRight: 8
					}
				}))
			},
			scrollViewProps: {
				style: { padding: "4px 8px" },
				overflow: !isExpanded2 ? "x" : "hidden",
				scrollbarStyle: "none",
				scrollActionsConfig: {
					type: "lrArrows",
					show: true
				}
			},
			renderItem: (itemProps) => {
				const { dataSource: itemData } = itemProps;
				if (itemData === null || itemData === void 0 ? void 0 : itemData.customClick) return /* @__PURE__ */ React.createElement(PisellCards.MultilevelCard, _objectSpread2(_objectSpread2({}, itemProps), {}, {
					card: (cardProps) => renderExpandCard(cardProps, "level2", isExpanded2),
					onClick: () => toggleExpand("level2")
				}));
				return /* @__PURE__ */ React.createElement(PisellCards.MultilevelCard, _objectSpread2(_objectSpread2({}, itemProps), {}, {
					card: (cardProps) => renderNormalCard(cardProps, "level2"),
					panel: (panelProps2) => {
						var _panelProps2$dataSour;
						if ((panelProps2 === null || panelProps2 === void 0 || (_panelProps2$dataSour = panelProps2.dataSource) === null || _panelProps2$dataSour === void 0 || (_panelProps2$dataSour = _panelProps2$dataSour.children) === null || _panelProps2$dataSour === void 0 ? void 0 : _panelProps2$dataSour.length) && maxLevel >= 3) return renderLevel3Panel(panelProps2);
						return null;
					},
					panelContainer: () => document.querySelector(`.pisell-super-tabs-slot-bottom-${skuId}`)
				}));
			}
		});
	}, [
		level2Value,
		maxLevel,
		activeKey,
		getActiveKey,
		handleLevel2Change,
		getExpand,
		toggleExpand,
		getLevelConfig,
		renderExpandCard,
		renderNormalCard
	]);
	/**
	* 渲染三级 Tabbar 面板
	*/
	const renderLevel3Panel = useCallback((panelProps2) => {
		if (maxLevel < 3) return null;
		let _dataSource2 = panelProps2.dataSource.children || [];
		if (_dataSource2.length) _dataSource2 = addDataSourceItemsByKey(_dataSource2, LEVEL_ADD_ITEMS.level3);
		const level3Config = getLevelConfig("level3");
		const isExpanded3 = getExpand("level3");
		const skuId = `sku-list-tabbar-${panelProps2.dataSource.id}`;
		return /* @__PURE__ */ React.createElement(PisellSuperTabs_default, {
			id: skuId,
			isControlled: true,
			tabItemStyle: {},
			dataSource: _dataSource2,
			value: level3Value,
			onChange: handleLevel3Change,
			rowKey: "id",
			style: {
				flex: 1,
				background: level3Config.superTabsBg
			},
			gridProps: {
				direction: "horizontal",
				gap: 4,
				wrap: isExpanded3 ? "wrap" : "nowrap",
				startSlot: /* @__PURE__ */ React.createElement("div", { style: { paddingLeft: level3Config.paddingLeft } }, /* @__PURE__ */ React.createElement(IconFont, {
					type: "pisell2-trend-down-01",
					style: {
						color: "#fff",
						fontSize: 24,
						marginRight: 8
					}
				}))
			},
			scrollViewProps: {
				style: { padding: "4px 8px" },
				overflow: !isExpanded3 ? "x" : "hidden",
				scrollbarStyle: "none",
				scrollActionsConfig: {
					type: "lrArrows",
					show: true
				}
			},
			renderItem: (itemProps) => {
				const { dataSource: itemData } = itemProps;
				if (itemData === null || itemData === void 0 ? void 0 : itemData.customClick) return /* @__PURE__ */ React.createElement(PisellCards.MultilevelCard, _objectSpread2(_objectSpread2({}, itemProps), {}, {
					card: (cardProps) => renderExpandCard(cardProps, "level3", isExpanded3),
					onClick: () => toggleExpand("level3")
				}));
				return /* @__PURE__ */ React.createElement(PisellCards.MultilevelCard, _objectSpread2(_objectSpread2({}, itemProps), {}, { card: (cardProps) => renderNormalCard(cardProps, "level3") }));
			}
		});
	}, [
		level3Value,
		maxLevel,
		activeKey,
		getActiveKey,
		handleLevel3Change,
		getExpand,
		toggleExpand,
		getLevelConfig,
		renderExpandCard,
		renderNormalCard
	]);
	/**
	* 渲染一级 Tabbar
	*/
	const level1Config = getLevelConfig("level1");
	const isExpanded1 = getExpand("level1");
	return dataSource.length ? /* @__PURE__ */ React.createElement("div", {
		className: classNames("pisell-tabbar", className),
		style,
		ref: containerRef
	}, /* @__PURE__ */ React.createElement(PisellSuperTabs_default, {
		isControlled: true,
		id: tabbarId,
		tabItemStyle: {},
		dataSource: level1DataSource,
		value: level1Value,
		onChange: handleLevel1Change,
		rowKey: "id",
		style: {
			flex: 1,
			background: level1Config.superTabsBg
		},
		gridProps: {
			direction: "horizontal",
			gap: 4,
			wrap: isExpanded1 ? "wrap" : "nowrap"
		},
		scrollViewProps: {
			style: { padding: "4px 8px" },
			overflow: !isExpanded1 ? "x" : "hidden",
			scrollbarStyle: "none",
			scrollActionsConfig: {
				type: "lrArrows",
				show: true
			}
		},
		renderItem: renderLevel1Item
	})) : null;
};
PisellTabbar.displayName = "PisellTabbar";
var PisellTabbar_default = forwardRef(PisellTabbar);
//#endregion
export { PisellTabbar_default as default };
