/**
 * useSelectionChangeEffect
 *
 * Fires a callback whenever node or edge selection changes.
 */

import { useEffect, useRef } from 'react';
import { useAtomValue } from 'jotai';
import { selectedNodeIdsAtom, selectedEdgeIdAtom } from '../core/selection-store';

export function useSelectionChangeEffect(
	onSelectionChange?: (selectedNodeIds: Set<string>, selectedEdgeId: string | null) => void
) {
	const selectedNodeIds = useAtomValue(selectedNodeIdsAtom);
	const selectedEdgeId = useAtomValue(selectedEdgeIdAtom);
	const isFirstRender = useRef(true);

	useEffect(() => {
		// Skip the initial render to avoid firing on mount
		if (isFirstRender.current) {
			isFirstRender.current = false;
			return;
		}
		onSelectionChange?.(selectedNodeIds, selectedEdgeId);
	}, [selectedNodeIds, selectedEdgeId, onSelectionChange]);
}
