const require_runtime = require("../../_virtual/_rolldown/runtime.js");
const require_index = require("../../locales/index.js");
const require_asyncToGenerator = require("../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useSearchState = require("./hooks/useSearchState.js");
const require_trigger = require("./utils/trigger.js");
const require_useSearchHistory = require("./hooks/useSearchHistory.js");
const require_useDebounceSearch = require("./hooks/useDebounceSearch.js");
const require_LookupAuxiliary = require("./components/LookupAuxiliary.js");
const require_LookupTrigger = require("./components/LookupTrigger.js");
const require_LookupResultHost = require("./components/LookupResultHost.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _ant_design_icons = require("@ant-design/icons");
require("./PisellLookup.less");
//#region src/components/pisellLookup/PisellLookup.tsx
/**
* PisellLookup 组件
* 搜索交互协议组件，提供统一的搜索入口、状态管理和结果承载能力
*
* @example
* ```tsx
* // 基础用法
* <PisellLookup
*   placeholder="搜索商品"
*   onSearch={(keyword) => console.log('搜索:', keyword)}
*   resultRender={(keyword) => <div>搜索结果: {keyword}</div>}
* />
* ```
*/
const PisellLookupComponent = (0, react.forwardRef)((props, ref) => {
	const { triggerType = "input", trigger, triggerText, triggerIcon, buttonText = require_index.getText("pisell-lookup-button-text"), placeholder = require_index.getText("pisell-lookup-placeholder"), size = "middle", disabled = false, showPrefixIcon = false, prefixIcon, showClear = true, showConfirmButton = true, confirmButtonText = require_index.getText("pisell-lookup-confirm-button-text"), value, defaultValue, onChange, onSearch, searchMode = "realtime", debounceTime = 300, showScan = true, onScan, showHistory = false, historyKey = "pisell_lookup_history", maxHistoryCount = 10, onLoadHistory, onSaveHistory, historyRender, showSuggestions = false, onLoadSuggestions, suggestionsRender, showHotWords = false, onLoadHotWords, hotWordsRender, displayType: displayTypeProp, resultRender, loading = false, emptyRender, modalWidth, modalStyle, getContainer, drawerWidth, drawerPlacement, popupWidth, containerStyle, containerClassName, visible: visibleProp, defaultVisible, onVisibleChange, onOpen, onClose, mask = false, maskClosable, clearOnClose = false, className, style, zIndex } = props;
	/**
	* 智能判断展示类型
	*/
	const displayType = (0, react.useMemo)(() => {
		return displayTypeProp || require_trigger.getDefaultDisplayType(triggerType, !!trigger);
	}, [
		displayTypeProp,
		triggerType,
		trigger
	]);
	/**
	* 智能判断搜索模式
	* 如果不显示 Lookup 按钮，自动使用实时搜索模式
	*/
	const effectiveSearchMode = (0, react.useMemo)(() => {
		if (!showConfirmButton) return "realtime";
		return searchMode;
	}, [showConfirmButton, searchMode]);
	/**
	* 搜索状态管理
	*/
	const { keyword, setKeyword, visible, setVisible, open, close } = require_useSearchState.useSearchState({
		value,
		defaultValue,
		visible: visibleProp,
		defaultVisible,
		onChange,
		onVisibleChange,
		onOpen,
		onClose
	});
	/**
	* 搜索历史管理
	*/
	const { history, addHistory, removeHistory, clearAllHistory } = require_useSearchHistory.useSearchHistory({
		historyKey,
		maxHistoryCount,
		onLoadHistory,
		onSaveHistory
	});
	/**
	* 联想词状态
	*/
	const [suggestions, setSuggestions] = (0, react.useState)([]);
	/**
	* 热门搜索状态
	*/
	const [hotWords, setHotWords] = (0, react.useState)([]);
	/**
	* 记录上一次触发搜索的关键词（避免重复触发）
	*/
	const lastSearchKeywordRef = (0, react.useRef)("");
	/**
	* 记录是否是手动选择触发（避免触发实时搜索）
	*/
	const isManualSelectRef = (0, react.useRef)(false);
	/**
	* Modal/Drawer 中输入框的 ref
	*/
	const modalInputRef = (0, react.useRef)(null);
	/**
	* 暴露给外部的方法
	*/
	(0, react.useImperativeHandle)(ref, () => ({
		open,
		close,
		getKeyword: () => keyword,
		setKeyword
	}), [
		open,
		close,
		keyword,
		setKeyword
	]);
	/**
	* 处理关闭时的逻辑
	*/
	(0, react.useEffect)(() => {
		if (!visible && clearOnClose) setKeyword("");
	}, [
		visible,
		clearOnClose,
		setKeyword
	]);
	/**
	* 处理 Modal/Drawer 打开后的聚焦和选中逻辑
	*/
	const handleAfterOpen = (0, react.useCallback)(() => {
		setTimeout(() => {
			if (modalInputRef.current) {
				modalInputRef.current.focus();
				if (!clearOnClose && keyword) modalInputRef.current.select();
			}
			if (keyword) onSearch === null || onSearch === void 0 || onSearch(keyword);
		}, 100);
	}, [
		clearOnClose,
		keyword,
		onSearch
	]);
	/**
	* 加载联想词
	*/
	(0, react.useEffect)(() => {
		if (!showSuggestions || !onLoadSuggestions || !keyword || !visible) {
			setSuggestions([]);
			return;
		}
		(function() {
			var _ref = require_asyncToGenerator._asyncToGenerator(function* () {
				try {
					setSuggestions((yield Promise.resolve(onLoadSuggestions(keyword))) || []);
				} catch (error) {
					console.error("Failed to load suggestions:", error);
					setSuggestions([]);
				}
			});
			return function loadSuggestions() {
				return _ref.apply(this, arguments);
			};
		})()();
	}, [
		showSuggestions,
		onLoadSuggestions,
		keyword,
		visible
	]);
	/**
	* 加载热门搜索
	*/
	(0, react.useEffect)(() => {
		if (!showHotWords || !onLoadHotWords || !visible) {
			setHotWords([]);
			return;
		}
		(function() {
			var _ref2 = require_asyncToGenerator._asyncToGenerator(function* () {
				try {
					setHotWords((yield Promise.resolve(onLoadHotWords())) || []);
				} catch (error) {
					console.error("Failed to load hot words:", error);
					setHotWords([]);
				}
			});
			return function loadHotWords() {
				return _ref2.apply(this, arguments);
			};
		})()();
	}, [
		showHotWords,
		onLoadHotWords,
		visible
	]);
	/**
	* 处理搜索触发（实时搜索，不保存历史）
	*/
	const handleRealtimeSearch = (0, react.useCallback)((searchKeyword) => {
		if (lastSearchKeywordRef.current === searchKeyword) return;
		lastSearchKeywordRef.current = searchKeyword;
		onSearch === null || onSearch === void 0 || onSearch(searchKeyword);
	}, [onSearch]);
	/**
	* 处理确认搜索（保存历史）
	*/
	const handleConfirmSearch = (0, react.useCallback)((searchKeyword) => {
		if (lastSearchKeywordRef.current === searchKeyword) return;
		lastSearchKeywordRef.current = searchKeyword;
		if (showHistory && searchKeyword.trim()) addHistory(searchKeyword);
		onSearch === null || onSearch === void 0 || onSearch(searchKeyword);
	}, [
		showHistory,
		addHistory,
		onSearch
	]);
	/**
	* 防抖搜索（实时搜索模式）
	* 包括空关键词（用于恢复显示所有数据）
	*/
	require_useDebounceSearch.useDebounceSearch({
		keyword,
		debounceTime,
		onSearch: handleRealtimeSearch,
		enabled: effectiveSearchMode === "realtime" && visible && !isManualSelectRef.current,
		lastSearchKeyword: lastSearchKeywordRef.current
	});
	/**
	* 处理输入变化
	*/
	const handleInputChange = (0, react.useCallback)((newValue) => {
		setKeyword(newValue);
	}, [setKeyword]);
	/**
	* 处理触发器点击（非输入框触发器）
	*/
	const handleTriggerClick = (0, react.useCallback)(() => {
		open();
	}, [open]);
	/**
	* 处理输入框聚焦
	*/
	const handleInputFocus = (0, react.useCallback)(() => {
		if (displayType === "inline" || displayType === "popup") open();
	}, [displayType, open]);
	/**
	* 处理输入框失焦
	*/
	const handleInputBlur = (0, react.useCallback)(() => {
		if (displayType === "inline" || displayType === "popup") setTimeout(() => {
			close();
		}, 200);
	}, [displayType, close]);
	/**
	* 处理确认触发（点击 Lookup 按钮或按 Enter 键）。支持传入当前输入值，回车时由 Trigger 传入以避免受控下 keyword 未更新导致历史未保存。
	*/
	const handleConfirm = (0, react.useCallback)((valueFromTrigger) => {
		handleConfirmSearch(valueFromTrigger !== null && valueFromTrigger !== void 0 ? valueFromTrigger : keyword);
	}, [keyword, handleConfirmSearch]);
	/**
	* 处理清除
	*/
	const handleClear = (0, react.useCallback)(() => {
		isManualSelectRef.current = true;
		setKeyword("");
		lastSearchKeywordRef.current = "";
		onSearch === null || onSearch === void 0 || onSearch("");
		setTimeout(() => {
			isManualSelectRef.current = false;
		}, debounceTime + 100);
	}, [
		setKeyword,
		onSearch,
		debounceTime
	]);
	/**
	* 处理扫码
	* 标记为手动操作，避免 setKeyword 触发的重渲染时防抖 effect 仍用旧的 debouncedKeyword('') 再触发一次 onSearch('')
	*/
	const handleScan = (0, react.useCallback)((code) => {
		isManualSelectRef.current = true;
		setKeyword(code);
		handleConfirmSearch(code);
		onScan === null || onScan === void 0 || onScan(code);
		setTimeout(() => {
			isManualSelectRef.current = false;
		}, debounceTime + 100);
	}, [
		setKeyword,
		handleConfirmSearch,
		onScan,
		debounceTime
	]);
	/**
	* 处理选择辅助项（历史/联想词/热门搜索）
	*/
	const handleSelectAuxiliary = (0, react.useCallback)((selectedKeyword) => {
		isManualSelectRef.current = true;
		setKeyword(selectedKeyword);
		if (showHistory && selectedKeyword.trim()) addHistory(selectedKeyword);
		lastSearchKeywordRef.current = selectedKeyword;
		onSearch === null || onSearch === void 0 || onSearch(selectedKeyword);
		setTimeout(() => {
			isManualSelectRef.current = false;
		}, debounceTime + 100);
	}, [
		setKeyword,
		showHistory,
		addHistory,
		onSearch,
		debounceTime
	]);
	/**
	* 渲染触发器
	*/
	const renderTrigger = () => {
		require_trigger.isInputTrigger(triggerType);
		return /* @__PURE__ */ react.default.createElement(require_LookupTrigger.LookupTrigger, {
			type: triggerType,
			trigger,
			triggerText,
			triggerIcon,
			buttonText,
			disabled,
			placeholder,
			size,
			showPrefixIcon,
			prefixIcon,
			showClear,
			showConfirmButton,
			confirmButtonText,
			showScan,
			value: keyword,
			onChange: handleInputChange,
			onClick: handleTriggerClick,
			onFocus: handleInputFocus,
			onBlur: handleInputBlur,
			onConfirm: handleConfirm,
			onScan: handleScan,
			onClear: handleClear
		});
	};
	/**
	* 渲染辅助区（历史、联想词、热门搜索）
	*/
	const renderAuxiliary = () => {
		return /* @__PURE__ */ react.default.createElement(require_LookupAuxiliary.LookupAuxiliary, {
			keyword,
			showHistory,
			history,
			showSuggestions,
			suggestions,
			showHotWords,
			hotWords,
			onSelect: handleSelectAuxiliary,
			onRemoveHistory: removeHistory,
			onClearHistory: clearAllHistory,
			historyRender,
			suggestionsRender,
			hotWordsRender
		});
	};
	/**
	* 渲染结果区域
	*/
	const renderResults = () => {
		if (!resultRender) return null;
		if (loading) return /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lookup-loading" }, /* @__PURE__ */ react.default.createElement(antd.Spin, { tip: require_index.getText("pisell-lookup-loading") }));
		if (!keyword) {
			if (emptyRender) return emptyRender();
			return null;
		}
		return /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lookup-result" }, resultRender(keyword, close));
	};
	/**
	* 是否有辅助区内容（与 LookupAuxiliary 内判断一致，用于空时不展示 dropdown）
	*/
	const hasAuxiliaryContent = showHistory && history.length > 0 || showSuggestions && suggestions.length > 0 && !!keyword || showHotWords && hotWords.length > 0 && !keyword;
	/**
	* 是否有结果区内容（loading 或有关键词且提供了 resultRender）
	*/
	const hasResultsContent = Boolean(loading || keyword && resultRender);
	/**
	* 渲染内容区（辅助区 + 结果区）
	*/
	const renderContent = () => {
		if (!hasAuxiliaryContent && !hasResultsContent) return null;
		const auxiliary = renderAuxiliary();
		const results = renderResults();
		return /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lookup-content" }, auxiliary, results);
	};
	/**
	* 如果是 inline 或 popup 模式，触发器和内容在同一个容器中
	*/
	if (displayType === "inline" || displayType === "popup") return /* @__PURE__ */ react.default.createElement("div", {
		className: `pisell-lookup pisell-lookup-${displayType} ${className || ""}`,
		style
	}, renderTrigger(), /* @__PURE__ */ react.default.createElement(require_LookupResultHost.LookupResultHost, {
		displayType,
		visible,
		onClose: close,
		popupWidth,
		containerStyle,
		containerClassName,
		zIndex
	}, renderContent()));
	/**
	* 如果是 modal、drawer、detached 模式，触发器和内容分离
	*/
	return /* @__PURE__ */ react.default.createElement("div", {
		className: `pisell-lookup ${className || ""}`,
		style
	}, renderTrigger(), /* @__PURE__ */ react.default.createElement(require_LookupResultHost.LookupResultHost, {
		displayType,
		visible,
		onClose: close,
		modalWidth,
		modalStyle,
		getContainer,
		drawerWidth,
		drawerPlacement,
		containerStyle,
		containerClassName,
		mask,
		maskClosable,
		zIndex,
		onAfterOpen: handleAfterOpen
	}, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lookup-search-area-with-close" }, /* @__PURE__ */ react.default.createElement(require_LookupTrigger.LookupTrigger, {
		ref: modalInputRef,
		type: "input",
		disabled,
		placeholder,
		size: "large",
		showPrefixIcon,
		prefixIcon,
		showClear,
		showConfirmButton,
		confirmButtonText,
		showScan,
		value: keyword,
		onChange: handleInputChange,
		onConfirm: handleConfirm,
		onScan: handleScan,
		onClear: handleClear
	}), /* @__PURE__ */ react.default.createElement(antd.Button, {
		icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.CloseOutlined, null),
		onClick: close,
		className: "pisell-lookup-modal-close-btn"
	}, require_index.getText("pisell-lookup-close"))), renderContent()));
});
PisellLookupComponent.displayName = "PisellLookup";
const PisellLookup = PisellLookupComponent;
//#endregion
exports.PisellLookup = PisellLookup;
