/** @license MIT | @cube-dev/ui-kit v0.0.0-canary-af8d194 | Cube Dev Team */
import { useEvent } from "../../../_internal/hooks/use-event.js";
import { useCallback, useMemo } from "react";
import { ListDropTargetDelegate, ListKeyboardDelegate, useDraggableCollection, useDroppableCollection } from "react-aria";
import { useDraggableCollectionState, useDroppableCollectionState } from "react-stately";

//#region src/components/navigation/Tabs/DraggableTabList.tsx
const getAllowedDropOperations = () => ["move"];
/**
* Component that enables drag-and-drop reordering for tabs.
*
* This component encapsulates all drag/drop hook calls, ensuring they're only
* called when reordering is actually enabled. It uses the render prop pattern
* to pass the drag/drop states to its children.
*/
function DraggableTabList({ state, listRef, orderedKeys, onReorder, children }) {
	const handleReorder = useEvent((e) => {
		if (!onReorder) return;
		const { target, keys: movableKeys } = e;
		const { dropPosition, key: targetKey } = target;
		const movableKey = [...movableKeys][0];
		const movableIndex = orderedKeys.indexOf(movableKey);
		const targetIndex = orderedKeys.indexOf(String(targetKey));
		if (movableIndex === -1 || targetIndex === -1) return;
		onReorder(movableIndex !== targetIndex ? orderedKeys.reduce((arr, key, i) => {
			if (i === movableIndex) return arr;
			if (i === targetIndex) if (dropPosition === "before") {
				arr.push(movableKey);
				arr.push(key);
			} else {
				arr.push(key);
				arr.push(movableKey);
			}
			else arr.push(key);
			return arr;
		}, []) : orderedKeys);
	});
	const getItems = useCallback((keys) => {
		return [...keys].map((key) => {
			const item = state.collection.getItem(key);
			return { "text/plain": item?.textValue || String(key) };
		});
	}, [state.collection]);
	const dragState = useDraggableCollectionState({
		collection: state.collection,
		selectionManager: state.selectionManager,
		getItems,
		getAllowedDropOperations
	});
	useDraggableCollection({
		getItems,
		getAllowedDropOperations
	}, dragState, listRef);
	const dropState = useDroppableCollectionState({
		collection: state.collection,
		selectionManager: state.selectionManager,
		onReorder: handleReorder
	});
	const { collectionProps } = useDroppableCollection({
		keyboardDelegate: useMemo(() => new ListKeyboardDelegate(state.collection, state.disabledKeys, listRef), [
			state.collection,
			state.disabledKeys,
			listRef
		]),
		dropTargetDelegate: useMemo(() => new ListDropTargetDelegate(state.collection, listRef, { orientation: "horizontal" }), [state.collection, listRef]),
		onReorder: handleReorder
	}, dropState, listRef);
	return children(dragState, dropState, collectionProps);
}

//#endregion
export { DraggableTabList };
//# sourceMappingURL=DraggableTabList.js.map