/**
 * useGuardContext — Guard context hook
 *
 * Reads all atoms needed for the gesture guard context and returns
 * a ref that is updated every render. The ref is stable and safe
 * to read inside useGesture callbacks without stale closure issues.
 */

import { useRef } from 'react';
import { useAtomValue } from 'jotai';
import { selectedNodeIdsAtom, focusedNodeIdAtom } from '../core/selection-store';
import { draggingNodeIdAtom, edgeCreationAtom } from '../core/graph-store';
import { isStylusActiveAtom, fingerCountAtom } from '../core/input-store';
import { inputModeAtom, keyboardInteractionModeAtom } from '../core/interaction-store';
import { selectionPathAtom } from '../core/selection-path-store';
import { isFilterActiveAtom } from '../core/search-store';
import { commandLineVisibleAtom } from '../commands/store';
import type { GuardContext, HeldKeysState } from './types';
import { NO_HELD_KEYS } from './types';

export function useGuardContext(heldKeys: HeldKeysState = NO_HELD_KEYS): React.RefObject<GuardContext> {
	const isStylusActive = useAtomValue(isStylusActiveAtom);
	const fingerCount = useAtomValue(fingerCountAtom);
	const draggingNodeId = useAtomValue(draggingNodeIdAtom);
	const focusedNodeId = useAtomValue(focusedNodeIdAtom);
	const selectedNodeIds = useAtomValue(selectedNodeIdsAtom);
	const inputMode = useAtomValue(inputModeAtom);
	const keyboardInteractionMode = useAtomValue(keyboardInteractionModeAtom);
	const selectionPath = useAtomValue(selectionPathAtom);
	const edgeCreation = useAtomValue(edgeCreationAtom);
	const isSearchActive = useAtomValue(isFilterActiveAtom);
	const commandLineVisible = useAtomValue(commandLineVisibleAtom);

	const guardRef = useRef<GuardContext>({
		isStylusActive: false,
		fingerCount: 0,
		isDragging: false,
		isResizing: false,
		isSplitting: false,
		inputMode: { type: 'normal' },
		keyboardInteractionMode: 'navigate',
		selectedNodeIds: new Set(),
		focusedNodeId: null,
		isSearchActive: false,
		commandLineVisible: false,
		heldKeys: NO_HELD_KEYS,
		custom: {},
	});

	guardRef.current = {
		isStylusActive,
		fingerCount,
		isDragging: draggingNodeId !== null,
		isResizing: false,
		isSplitting: false,
		inputMode,
		keyboardInteractionMode,
		selectedNodeIds,
		focusedNodeId,
		isSearchActive,
		commandLineVisible,
		heldKeys,
		custom: {
			isSelecting: selectionPath !== null,
			isCreatingEdge: edgeCreation.isCreating,
		},
	};

	return guardRef;
}
