/**
 * Command Store — State Atoms
 *
 * Core state and derived atoms for the command line system.
 * Action atoms live in ./store.ts.
 */

import { atom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
import type {
	InputMode,
	CommandLineState,
	FeedbackState,
} from './types';

// =============================================================================
// Core State Atoms
// =============================================================================

/**
 * Input mode - controls how canvas interactions are routed.
 * When type is not 'normal', canvas clicks are intercepted by the command system.
 */
export const inputModeAtom = atom<InputMode>({ type: 'normal' });

/**
 * Whether the command line UI is visible.
 */
export const commandLineVisibleAtom = atom(false);

/**
 * Command line state machine.
 */
export const commandLineStateAtom = atom<CommandLineState>({ phase: 'idle' });

/**
 * Visual feedback state for the canvas overlay.
 */
export const commandFeedbackAtom = atom<FeedbackState>(null);

/**
 * Command history (persisted to localStorage).
 */
export const commandHistoryAtom = atomWithStorage<string[]>('canvas-command-history', []);

/**
 * Currently selected suggestion index for keyboard navigation.
 */
export const selectedSuggestionIndexAtom = atom(0);

// =============================================================================
// Input Resolution
// =============================================================================

/**
 * Resolver for pending input. Used to communicate between canvas and command system.
 */
export const pendingInputResolverAtom = atom<unknown | null>(null);

// =============================================================================
// Derived Atoms
// =============================================================================

/**
 * Whether a command is currently being executed or inputs collected.
 */
export const isCommandActiveAtom = atom((get) => {
	const state = get(commandLineStateAtom);
	return state.phase === 'collecting' || state.phase === 'executing';
});

/**
 * Current input definition (if collecting).
 */
export const currentInputAtom = atom((get) => {
	const state = get(commandLineStateAtom);
	if (state.phase !== 'collecting') return null;
	return state.command.inputs[state.inputIndex];
});

/**
 * Progress through current command (e.g., "2/3").
 */
export const commandProgressAtom = atom((get) => {
	const state = get(commandLineStateAtom);
	if (state.phase !== 'collecting') return null;
	return {
		current: state.inputIndex + 1,
		total: state.command.inputs.length,
	};
});
