import { a as e, i as t, o as n, r, s as i, t as a } from "../chunks/SelectOptionContent-lfEtHXfO.js";
import { t as o } from "../chunks/ui.module-BisoTevy.js";
import { o as s } from "../chunks/input-CZLUUggm.js";
import { c, d as l, f as u, i as d, l as f, r as p, t as m, u as h } from "../chunks/picker-BZ05h_ZJ.js";
import { useEffect as g, useMemo as _, useRef as ee, useState as te } from "react";
import { cn as v } from "@ryuzaki13/react-foundation-lib/utils";
import { CheckIcon as y, ChevronRightIcon as ne, MinusIcon as b, XIcon as re } from "lucide-react";
import { Fragment as ie, jsx as x, jsxs as ae } from "react/jsx-runtime";
//#region src/tree-select/helpers.ts
function S(e) {
	return e ? { [e.codeKey]: [e.value] } : {};
}
//#endregion
//#region src/tree-select/model/buildODataTreeNodes.ts
function C(e, t, n) {
	return e ? `${e}/${t}:${n}` : `${t}:${n}`;
}
function w(e, t, n) {
	let r = n[t];
	return r && e[r] || e[t];
}
function oe(e) {
	return [...new Set(e.filter(Boolean))].join(" ");
}
function se(e) {
	return {
		id: C(e.parentId, e.codeKey, e.value),
		codeKey: e.codeKey,
		value: e.value,
		label: e.label,
		code: e.code,
		searchText: oe([
			e.value,
			e.label,
			e.code
		]),
		children: [],
		childByBranchKey: /* @__PURE__ */ new Map()
	};
}
function T(e) {
	return {
		id: e.id,
		codeKey: e.codeKey,
		value: e.value,
		label: e.label,
		code: e.code,
		searchText: e.searchText,
		children: e.children.length > 0 ? e.children.map(T) : void 0
	};
}
function ce({ items: e, orderedCodeKeys: t, keyPairsMap: n, hiddenCodeKeys: r, textValueCodeKeys: i }) {
	if (t.length === 0 || e.length === 0) return [];
	let a = [], o = /* @__PURE__ */ new Map();
	for (let s of e) {
		let e;
		for (let c of t) {
			let t = String(s[c] ?? "");
			if (!t) break;
			let l = String(w(s, c, n) ?? ""), u = i?.has(c) ? l : t, d = `${c}:${u}`, f = e ? e.childByBranchKey : o, p = f.get(d);
			p || (p = se({
				parentId: e?.id,
				codeKey: c,
				value: u,
				label: l,
				code: r.has(c) ? void 0 : t
			}), f.set(d, p), e ? e.children.push(p) : a.push(p)), e = p;
		}
	}
	return a.map(T);
}
//#endregion
//#region src/tree-select/model/resolveOrderedTreeSegmentItems.ts
function E(t, n) {
	return e(t, n);
}
//#endregion
//#region src/tree-select/model/useODataTreeData.ts
function D(e, n, r) {
	return t([{
		odata: e,
		segments: n,
		model: r
	}]);
}
function O(e) {
	return e[0]?.id;
}
function k({ odata: e, segments: t, model: a }) {
	let o = `${e.service}.${e.target}`, s = _(() => D(e, t, a), [
		e,
		t,
		a
	]), c = r([e]), l = _(() => E(s, c), [s, c]), u = _(() => l.map((e) => e.id), [l]), d = i({
		odata: e,
		model: n({
			codeKey: O(l) ?? Object.keys(t)[0],
			...a
		})
	}), { hiddenCodeKeys: f, textValueCodeKeys: p } = _(() => {
		let t = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set();
		for (let r of l) (r.segment.hideCode ?? e.hideCode) && t.add(r.id), r.segment.selectText && n.add(r.id);
		return {
			hiddenCodeKeys: t,
			textValueCodeKeys: n
		};
	}, [e.hideCode, l]), m = _(() => ce({
		items: d.data?.items ?? [],
		orderedCodeKeys: u,
		keyPairsMap: d.data?.keyPairsMap ?? {},
		hiddenCodeKeys: f,
		textValueCodeKeys: p
	}), [
		d.data?.items,
		d.data?.keyPairsMap,
		f,
		u,
		p
	]), h = l[0]?.segment.placeholder ?? "Выберите значение", g = !!c[o]?.length;
	return {
		nodes: m,
		orderedSegmentItems: l,
		orderedCodeKeys: u,
		isLoading: d.isLoading,
		isError: d.isError,
		placeholder: h,
		hasResolvedChain: g
	};
}
//#endregion
//#region src/tree-select/model/treeUtils.ts
function A(e, t) {
	return `${e}::${t}`;
}
function j(e) {
	let t = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), a = /* @__PURE__ */ new Map(), o = 0, s = (e, c) => {
		t.set(e.id, e), n.set(e.id, c), i.set(e.id, o++), a.set(A(e.codeKey, e.value), e.id);
		let l = (e.children ?? []).map((e) => e.id);
		r.set(e.id, l);
		for (let t of e.children ?? []) s(t, e.id);
	};
	for (let t of e) s(t);
	return {
		rootIds: e.map((e) => e.id),
		nodeById: t,
		parentById: n,
		childrenById: r,
		preorderIndexById: i,
		nodeIdByCodeValue: a
	};
}
function M(e, t) {
	if (e) return t.nodeIdByCodeValue.get(A(e.codeKey, e.value));
}
function N(e, t) {
	let n = /* @__PURE__ */ new Set();
	if (!e) return n;
	for (let [r, i] of Object.entries(e)) for (let e of i) {
		let i = t.nodeIdByCodeValue.get(A(r, e));
		i && n.add(i);
	}
	return z(n, t);
}
function P(e, t) {
	let n = [...e].sort((e, n) => (t.preorderIndexById.get(e) ?? 2 ** 53 - 1) - (t.preorderIndexById.get(n) ?? 2 ** 53 - 1)), r = {};
	for (let e of n) {
		let n = t.nodeById.get(e);
		n && (r[n.codeKey] = r[n.codeKey] ?? [], r[n.codeKey].push(n.value));
	}
	return r;
}
function F(e, t) {
	let n = [], r = t.parentById.get(e);
	for (; r;) n.push(r), r = t.parentById.get(r);
	return n;
}
function I(e, t, n) {
	let r = n.parentById.get(e);
	for (; r;) {
		if (r === t) return !0;
		r = n.parentById.get(r);
	}
	return !1;
}
function L(e, t, n) {
	for (let r of [...e]) I(r, t, n) && e.delete(r);
}
function R(e, t, n) {
	if (t.has(e)) return !0;
	let r = n.childrenById.get(e) ?? [];
	return r.length === 0 ? !1 : r.every((e) => R(e, t, n));
}
function z(e, t) {
	let n = new Set(e);
	for (let e of [...n]) F(e, t).some((e) => n.has(e)) && n.delete(e);
	let r = [...t.nodeById.keys()].sort((e, n) => (t.preorderIndexById.get(n) ?? 0) - (t.preorderIndexById.get(e) ?? 0));
	for (let e of r) {
		let r = t.childrenById.get(e) ?? [];
		r.length === 0 || n.has(e) || r.every((e) => R(e, n, t)) && (L(n, e, t), n.add(e));
	}
	return n;
}
function B(e, t, n) {
	let r = n.parentById.get(t);
	for (; r;) {
		if (e.has(r)) {
			e.delete(r);
			for (let t of n.childrenById.get(r) ?? []) e.add(t);
			return !0;
		}
		r = n.parentById.get(r);
	}
	return !1;
}
function V(e, t, n) {
	return t.has(e) ? !0 : F(e, n).some((e) => t.has(e));
}
function H(e, t, n, r) {
	let i = n.childrenById.get(e) ?? [];
	if (t.has(e)) return r.selectedIds.add(e), {
		selected: !0,
		partial: !1
	};
	if (i.length === 0) return {
		selected: !1,
		partial: !1
	};
	let a = i.map((e) => H(e, t, n, r)), o = a.every((e) => e.selected && !e.partial), s = a.some((e) => e.selected || e.partial);
	return o ? (r.selectedIds.add(e), {
		selected: !0,
		partial: !1
	}) : s ? (r.partialIds.add(e), {
		selected: !1,
		partial: !0
	}) : {
		selected: !1,
		partial: !1
	};
}
function U(e, t) {
	let n = {
		selectedIds: /* @__PURE__ */ new Set(),
		partialIds: /* @__PURE__ */ new Set()
	};
	for (let r of t.rootIds) H(r, e, t, n);
	return n;
}
function W(e, t, n) {
	let r = N(e, n), i = (e) => {
		if (V(e, r, n)) {
			if (r.has(e)) {
				r.delete(e);
				return;
			}
			B(r, e, n) && i(e);
			return;
		}
		L(r, e, n), r.add(e);
	};
	return i(t), P(z(r, n), n);
}
function le(e, t, n) {
	let r = t.parentById.get(e);
	for (; r;) n.add(r), r = t.parentById.get(r);
}
function ue(e, t) {
	let n = /* @__PURE__ */ new Set();
	for (let r of e) le(r, t, n);
	return n;
}
function G(e, t, n) {
	let r = (e.children ?? []).map((e) => G(e, t, n)).filter((e) => !!e);
	return !e.searchText.toLowerCase().includes(t) && r.length === 0 ? null : (r.length > 0 && n.add(e.id), r.length === 0 ? e : {
		...e,
		children: r
	});
}
function de(e, t) {
	let n = t.trim().toLowerCase();
	if (!n) return {
		nodes: [...e],
		expandedIds: /* @__PURE__ */ new Set()
	};
	let r = /* @__PURE__ */ new Set();
	return {
		nodes: e.map((e) => G(e, n, r)).filter((e) => !!e),
		expandedIds: r
	};
}
function fe(e, t) {
	let n = [], r = (e, i, a) => {
		let o = (e.children?.length ?? 0) > 0, s = o && t.has(e.id);
		if (n.push({
			node: e,
			level: i,
			parentId: a,
			hasChildren: o,
			isExpanded: s,
			isLeaf: !o
		}), s) for (let t of e.children ?? []) r(t, i + 1, e.id);
	};
	for (let t of e) r(t, 0);
	return n;
}
var K = {
	treeRow: "eMqOwq",
	treeRowSelected: "JKstO-",
	treeRowActive: "hKgr8e",
	treeNodeButton: "_6EH37F",
	treeIndent: "o5NWnX",
	treeExpander: "ibSd-S",
	treeExpanderPlaceholder: "lXezvv",
	treeExpanderIcon: "FMlLGX",
	treeExpanderIconExpanded: "d2Zt7U",
	treeSelection: "_8PN4hs",
	treeSelectionChecked: "_4JEoen",
	treeSelectionPartial: "GS8eEC",
	treeSelectionIcon: "T8gVno",
	treeSummary: "o6stdX",
	inputWithOverlay: "I5zvhe",
	valueOverlay: "KQ0PBI",
	treeActions: "_7hAQQA",
	treeClearButton: "XeUHNc"
};
//#endregion
//#region src/tree-select/TreeNodeContent.tsx
function pe({ node: e, level: t, highlight: n, hasChildren: r, isExpanded: i, selected: o, partial: s, selectionMode: c, onToggleExpand: l }) {
	return /* @__PURE__ */ ae(ie, { children: [
		/* @__PURE__ */ x("span", {
			className: K.treeIndent,
			style: { "--tree-level": t },
			"aria-hidden": "true"
		}),
		r ? /* @__PURE__ */ x("button", {
			type: "button",
			className: K.treeExpander,
			onClick: (e) => {
				e.stopPropagation(), l?.();
			},
			"aria-label": i ? "Свернуть ветку" : "Развернуть ветку",
			"data-ui": "tree-select-expander",
			"data-action": i ? "collapse-tree-select-node" : "expand-tree-select-node",
			children: /* @__PURE__ */ x(ne, { className: v(K.treeExpanderIcon, i && K.treeExpanderIconExpanded) })
		}) : /* @__PURE__ */ x("span", {
			className: K.treeExpanderPlaceholder,
			"aria-hidden": "true"
		}),
		c === "multi" && /* @__PURE__ */ x("span", {
			className: v(K.treeSelection, o && K.treeSelectionChecked, s && K.treeSelectionPartial),
			"aria-hidden": "true",
			children: o ? /* @__PURE__ */ x(y, { className: K.treeSelectionIcon }) : s ? /* @__PURE__ */ x(b, { className: K.treeSelectionIcon }) : null
		}),
		/* @__PURE__ */ x(a, {
			label: e.label,
			code: e.code,
			highlight: n
		})
	] });
}
//#endregion
//#region src/tree-select/TreePickerBase.tsx
function q({ label: e, description: t, disabled: n, placeholder: r, size: i, nodes: a, selectedIds: y, partialIds: ne, selectionMode: b, triggerMode: S = "display", selectedSummary: C, selectedSummaryText: w, query: oe, defaultQuery: se, onQuery: T, onNodeActivate: ce, onClearSelection: E, isLoading: D, error: O }) {
	let k = ee(null), A = ee(!1), [M, N] = te(() => /* @__PURE__ */ new Set()), P = S === "search" ? "search-single" : "display", F = _(() => j(a), [a]), { query: I, setQuery: L } = p({
		open: !0,
		query: oe,
		defaultQuery: se,
		onQuery: T,
		triggerMode: "display"
	}), { nodes: R, expandedIds: z } = _(() => de(a, I), [a, I]), B = _(() => ue(y, F), [y, F]), V = _(() => /* @__PURE__ */ new Set([
		...M,
		...z,
		...B
	]), [
		M,
		z,
		B
	]), H = _(() => fe(R, V), [R, V]), { open: U, activeIndex: W, context: le, floatingStyles: G, getFloatingProps: q, setReference: me, setFloating: J, setOptionRef: he, close: Y, openList: X, toggleOpen: ge, selectOption: _e, handleReferenceKeyDown: ve, handleFloatingKeyDown: ye, getOptionId: be, getActiveOptionId: xe } = d({
		options: H,
		selectedIndex: _(() => H.findIndex((e) => y.has(e.node.id)), [y, H]),
		onSelect: (e) => ce(e.node),
		disabled: n || D,
		closeOnSelect: b === "single",
		allowOpenWithoutOptions: !0,
		triggerMode: P
	}), Z = y.size > 0, Se = S === "search" && (U || I.length > 0), Ce = Se ? I : w ?? "", Q = S === "display" && !!C, $ = m({
		mode: P,
		open: U,
		currentQuery: I,
		hasDisplayValue: !!w,
		inputRef: k,
		setQuery: L,
		openList: X,
		close: Y,
		toggleOpen: ge
	});
	g(() => {
		A.current && !U && $.policy.resetQueryOnClose && L(""), A.current = U;
	}, [
		U,
		L,
		$.policy.resetQueryOnClose
	]);
	let we = (e) => {
		k.current = e;
	}, Te = () => {
		E?.(), L(""), Y();
	}, Ee = (e) => {
		e.hasChildren && N((t) => {
			let n = new Set(t);
			return n.has(e.node.id) ? n.delete(e.node.id) : n.add(e.node.id), n;
		});
	};
	return /* @__PURE__ */ x(u, {
		label: e,
		description: t,
		disabled: n,
		placeholder: r,
		size: i,
		children: ({ controlId: e, labelId: t, describedBy: i }) => {
			let a = `${e}-listbox`;
			return /* @__PURE__ */ ae(ie, { children: [/* @__PURE__ */ x(c, {
				ref: we,
				rootRef: me,
				id: e,
				type: "text",
				role: "combobox",
				autoComplete: "off",
				disabled: n || D,
				readOnly: S !== "search",
				value: S === "display" && Q ? "" : Ce,
				placeholder: S === "search" ? !w || Se ? r : void 0 : Z ? void 0 : r,
				"aria-labelledby": t,
				"aria-describedby": i,
				"aria-haspopup": "listbox",
				"aria-expanded": U,
				"aria-controls": U ? a : void 0,
				"aria-autocomplete": S === "search" ? "list" : "none",
				"aria-activedescendant": U && H.length > 0 ? xe(a) : void 0,
				inputClassName: v(Z && K.treeSummary, Q && K.inputWithOverlay),
				overlay: Q ? /* @__PURE__ */ x("div", {
					className: K.valueOverlay,
					children: C
				}) : void 0,
				endAdornment: /* @__PURE__ */ x(f, {
					open: U,
					disabled: n || D,
					onToggleMouseDown: $.handleToggleMouseDown,
					onToggleClick: $.handleToggleClick,
					children: Z && E ? /* @__PURE__ */ x("button", {
						type: "button",
						className: K.treeClearButton,
						onMouseDown: (e) => {
							e.preventDefault(), e.stopPropagation();
						},
						onClick: (e) => {
							e.preventDefault(), e.stopPropagation(), Te();
						},
						"aria-label": "Очистить выбор",
						children: /* @__PURE__ */ x(re, {})
					}) : null
				}),
				onChange: (e) => {
					S === "search" && $.handleTriggerInputChange(e.target.value);
				},
				onClick: $.handleTriggerClick,
				onFocus: (e) => {
					$.handleTriggerFocus(e.currentTarget);
				},
				onKeyDown: (e) => {
					ve(e), !e.defaultPrevented && $.handleTriggerKeyDown({
						event: e,
						onActivateWhenOpen: () => {
							let e = W >= 0 ? H[W] : void 0;
							e && _e(e);
						},
						enableSpaceActivation: S === "display"
					});
				}
			}), /* @__PURE__ */ x(l, {
				open: U,
				context: le,
				floatingStyles: G,
				listId: a,
				labelId: t,
				descriptionId: i,
				activeOptionId: H.length > 0 ? xe(a) : void 0,
				setFloating: J,
				getFloatingProps: q,
				onKeyDown: ye,
				className: v(o.uiPopupOptions, "scrollable"),
				header: S === "display" ? /* @__PURE__ */ x(s, {
					value: I,
					onChange: L,
					onClear: () => L(""),
					placeholder: "Поиск по дереву",
					onKeyDown: (e) => {
						e.key !== "Escape" && e.key !== "Tab" && e.stopPropagation();
					},
					onClick: (e) => {
						e.stopPropagation();
					}
				}) : void 0,
				children: /* @__PURE__ */ x("div", {
					className: "",
					children: H.length === 0 ? /* @__PURE__ */ x(h, {
						errorState: O,
						loadingState: D ? "Загрузка..." : void 0,
						emptyState: !O && !D ? "Нет данных" : void 0
					}) : H.map((e, t) => {
						let n = y.has(e.node.id), r = !n && ne.has(e.node.id), i = t === W;
						return /* @__PURE__ */ x("div", {
							id: be(a, t),
							ref: (e) => he(t, e),
							role: "option",
							"aria-selected": n,
							className: v(K.treeRow, i && K.treeRowActive, n && K.treeRowSelected),
							onMouseDown: (e) => {
								e.preventDefault();
							},
							onClick: () => _e(e),
							children: /* @__PURE__ */ x("div", {
								className: K.treeNodeButton,
								children: /* @__PURE__ */ x(pe, {
									node: e.node,
									level: e.level,
									highlight: I,
									hasChildren: e.hasChildren,
									isExpanded: e.isExpanded,
									selected: n,
									partial: r,
									selectionMode: b,
									onToggleExpand: () => Ee(e)
								})
							})
						}, e.node.id);
					})
				})
			})] });
		}
	});
}
//#endregion
//#region src/tree-select/TreeMultiSelect.tsx
function me(e, t) {
	if (e.size !== 0) {
		if (e.size === 1) {
			let n = t.nodeById.get([...e][0]);
			return n ? n.code && n.code !== n.label ? `${n.label} · ${n.code}` : n.label : void 0;
		}
		return `Выбрано ${e.size} узл.`;
	}
}
function J({ label: e, description: t, disabled: n, placeholder: r = "Выберите значения", size: i, nodes: a, value: o, onChange: s, query: c, defaultQuery: l, onQuery: u, isLoading: d, error: f }) {
	let p = _(() => j(a), [a]), m = _(() => N(o, p), [p, o]), h = _(() => U(m, p), [m, p]), g = _(() => me(m, p), [m, p]);
	return /* @__PURE__ */ x(q, {
		label: e,
		description: t,
		disabled: n,
		placeholder: r,
		size: i,
		nodes: a,
		selectedIds: h.selectedIds,
		partialIds: h.partialIds,
		selectionMode: "multi",
		triggerMode: "search",
		selectedSummary: g,
		query: c,
		defaultQuery: l,
		onQuery: u,
		onNodeActivate: (e) => s(W(o, e.id, p)),
		onClearSelection: () => s({}),
		isLoading: d,
		error: f
	});
}
//#endregion
//#region src/tree-select/ODataTreeMultiSelect.tsx
function he({ label: e, description: t, disabled: n, size: r, placeholder: i, query: a, defaultQuery: o, onQuery: s, value: c, onChange: l, odata: u, segments: d, model: f }) {
	let p = k({
		odata: u,
		segments: d,
		model: f
	});
	return /* @__PURE__ */ x(J, {
		label: e,
		description: t,
		disabled: n || p.isLoading,
		size: r,
		placeholder: i ?? p.placeholder,
		nodes: p.nodes,
		value: c,
		onChange: l,
		query: a,
		defaultQuery: o,
		onQuery: s,
		isLoading: p.isLoading,
		error: p.isError ? "Ошибка загрузки" : void 0
	});
}
//#endregion
//#region src/tree-select/TreeSelect.tsx
function Y(e) {
	if (e) return e.code && e.code !== e.label ? `${e.label} · ${e.code}` : e.label;
}
function X({ label: e, description: t, disabled: n, placeholder: r = "Выберите значение", size: i, nodes: a, value: o, onChange: s, query: c, defaultQuery: l, onQuery: u, isLoading: d, error: f, clearable: p = !1 }) {
	let m = _(() => j(a), [a]), h = M(o, m), g = h ? m.nodeById.get(h) : void 0;
	return /* @__PURE__ */ x(q, {
		label: e,
		description: t,
		disabled: n,
		placeholder: r,
		size: i,
		nodes: a,
		selectedIds: h ? /* @__PURE__ */ new Set([h]) : /* @__PURE__ */ new Set(),
		partialIds: /* @__PURE__ */ new Set(),
		selectionMode: "single",
		triggerMode: "search",
		selectedSummaryText: Y(g),
		query: c,
		defaultQuery: l,
		onQuery: u,
		onNodeActivate: (e) => s({
			codeKey: e.codeKey,
			value: e.value
		}),
		onClearSelection: p ? () => s(void 0) : void 0,
		isLoading: d,
		error: f
	});
}
//#endregion
//#region src/tree-select/ODataTreeSelect.tsx
function ge({ label: e, description: t, disabled: n, size: r, placeholder: i, query: a, defaultQuery: o, onQuery: s, value: c, onChange: l, odata: u, segments: d, model: f, clearable: p }) {
	let m = k({
		odata: u,
		segments: d,
		model: f
	});
	return /* @__PURE__ */ x(X, {
		label: e,
		description: t,
		disabled: n || m.isLoading,
		size: r,
		placeholder: i ?? m.placeholder,
		nodes: m.nodes,
		value: c,
		onChange: l,
		query: a,
		defaultQuery: o,
		onQuery: s,
		isLoading: m.isLoading,
		error: m.isError ? "Ошибка загрузки" : void 0,
		clearable: p
	});
}
//#endregion
export { he as ODataTreeMultiSelect, ge as ODataTreeSelect, J as TreeMultiSelect, X as TreeSelect, S as treeSelectValueToSelectedFilters };

//# sourceMappingURL=index.js.map