"use client";
import { findTreeNode } from "../get-children-nodes-values/get-children-nodes-values.mjs";
//#region packages/@mantine/core/src/components/Tree/move-tree-node/move-tree-node.ts
function isDescendant(data, ancestorValue, value) {
	const ancestor = findTreeNode(ancestorValue, data);
	if (!ancestor || !ancestor.children) return false;
	function check(nodes) {
		for (const node of nodes) {
			if (node.value === value) return true;
			if (node.children && check(node.children)) return true;
		}
		return false;
	}
	return check(ancestor.children);
}
function removeNode(data, value) {
	let removed = null;
	return {
		data: data.reduce((acc, node) => {
			if (node.value === value) {
				removed = { ...node };
				return acc;
			}
			if (node.children) {
				const result = removeNode(node.children, value);
				if (result.removed) {
					removed = result.removed;
					acc.push({
						...node,
						children: result.data
					});
				} else acc.push(node);
			} else acc.push(node);
			return acc;
		}, []),
		removed
	};
}
function insertNode(data, node, targetValue, position) {
	if (position === "inside") return data.map((item) => {
		if (item.value === targetValue) return {
			...item,
			children: [...item.children || [], node]
		};
		if (item.children) return {
			...item,
			children: insertNode(item.children, node, targetValue, position)
		};
		return item;
	});
	const targetIndex = data.findIndex((item) => item.value === targetValue);
	if (targetIndex !== -1) {
		const result = [...data];
		const insertIndex = position === "before" ? targetIndex : targetIndex + 1;
		result.splice(insertIndex, 0, node);
		return result;
	}
	return data.map((item) => {
		if (item.children) return {
			...item,
			children: insertNode(item.children, node, targetValue, position)
		};
		return item;
	});
}
function moveTreeNode(data, payload) {
	const { draggedNode, targetNode, position } = payload;
	if (draggedNode === targetNode) return data;
	if (!findTreeNode(targetNode, data)) return data;
	if (isDescendant(data, draggedNode, targetNode)) return data;
	const { data: dataWithout, removed } = removeNode(data, draggedNode);
	if (!removed) return data;
	return insertNode(dataWithout, removed, targetNode, position);
}
//#endregion
export { moveTreeNode };

//# sourceMappingURL=move-tree-node.mjs.map