/**
 * useDragLifecycleEffect
 *
 * Fires onDragStart/onDragEnd callbacks by watching the draggingNodeIdAtom.
 * When it transitions null → id, fires onDragStart with all selected node IDs.
 * When it transitions id → null, fires onDragEnd with final positions.
 */

import { useEffect, useRef } from 'react';
import { useAtomValue, useStore } from 'jotai';
import { draggingNodeIdAtom, graphAtom } from '../core/graph-store';
import { selectedNodeIdsAtom } from '../core/selection-store';
import type { GraphNodeAttributes } from '../core/types';

export function useDragLifecycleEffect(
	onDragStart?: (nodeIds: string[]) => void,
	onDragEnd?: (nodeIds: string[], positions: Map<string, { x: number; y: number }>) => void
) {
	const draggingNodeId = useAtomValue(draggingNodeIdAtom);
	const store = useStore();
	const prevDraggingRef = useRef<string | null>(null);
	const draggedNodeIdsRef = useRef<string[]>([]);

	useEffect(() => {
		const prev = prevDraggingRef.current;
		prevDraggingRef.current = draggingNodeId;

		if (prev === null && draggingNodeId !== null) {
			// Drag started
			const selectedIds = Array.from(store.get(selectedNodeIdsAtom));
			draggedNodeIdsRef.current = selectedIds;
			onDragStart?.(selectedIds);
		} else if (prev !== null && draggingNodeId === null) {
			// Drag ended — read final positions from graph
			const nodeIds = draggedNodeIdsRef.current;
			if (onDragEnd && nodeIds.length > 0) {
				const graph = store.get(graphAtom);
				const positions = new Map<string, { x: number; y: number }>();
				for (const id of nodeIds) {
					if (graph.hasNode(id)) {
						const attrs = graph.getNodeAttributes(id) as GraphNodeAttributes;
						positions.set(id, { x: attrs.x, y: attrs.y });
					}
				}
				onDragEnd(nodeIds, positions);
			}
			draggedNodeIdsRef.current = [];
		}
	}, [draggingNodeId, store, onDragStart, onDragEnd]);
}
