/**
 * Modifier Helpers
 *
 * Pure utility functions for gesture state queries — repeat detection,
 * selection lookup, subject resolution.
 *
 * Extracted from input-action-helpers.ts in v1.6.0.
 *
 * @since 1.6.0
 */

import type { Store } from 'jotai/vanilla/store';
import {
	draggingNodeIdAtom,
	edgeCreationAtom,
	focusedNodeIdAtom,
	selectedEdgeIdAtom,
	selectedNodeIdsAtom,
	clearSelectionAtom,
	clearEdgeSelectionAtom,
} from '../core';
import type { GestureSubject, InputEvent } from './types';
import { isKeyInputEvent } from './types';

/**
 * Whether the keyboard event is a held-down repeat.
 */
export function isRepeatBlocked(event: InputEvent): boolean {
	return isKeyInputEvent(event) && event.repeat;
}

/**
 * Get array of currently selected node IDs.
 */
export function getSelectedNodeIds(store: Store): string[] {
	return Array.from(store.get(selectedNodeIdsAtom));
}

/**
 * Clear both node and edge selection.
 */
export function clearSelectionState(store: Store): void {
	store.set(clearSelectionAtom);
	store.set(clearEdgeSelectionAtom);
}

/**
 * Resolve the best node ID to use for focus-based operations.
 */
export function resolveFocusableNodeId(store: Store): string | null {
	const focusedNodeId = store.get(focusedNodeIdAtom);
	if (focusedNodeId) return focusedNodeId;
	const selected = getSelectedNodeIds(store);
	return selected[0] ?? null;
}

/**
 * Determine what entity the current gesture targets.
 */
export function getCurrentSubject(store: Store): GestureSubject {
	const draggingNodeId = store.get(draggingNodeIdAtom);
	if (draggingNodeId) return { kind: 'node', nodeId: draggingNodeId };

	const edgeCreation = store.get(edgeCreationAtom);
	if (edgeCreation.isCreating && edgeCreation.sourceNodeId) {
		return { kind: 'node', nodeId: edgeCreation.sourceNodeId };
	}

	const focusedNodeId = resolveFocusableNodeId(store);
	if (focusedNodeId) return { kind: 'node', nodeId: focusedNodeId };

	const selectedEdgeId = store.get(selectedEdgeIdAtom);
	if (selectedEdgeId) return { kind: 'edge', edgeId: selectedEdgeId };

	return { kind: 'background' };
}

/**
 * Fill in the subject on key InputEvents if not already set.
 */
export function updateKeySubject(event: InputEvent, store: Store): void {
	if (event.kind === 'key' && event.subject === undefined) {
		event.subject = getCurrentSubject(store);
	}
}
