/**
 * useCommandLine Hook
 *
 * Main hook for managing command line state and actions.
 * Provides access to visibility, state, history, and actions.
 */

'use client';

import { useAtomValue, useSetAtom } from 'jotai';
import {
	commandLineVisibleAtom,
	commandLineStateAtom,
	openCommandLineAtom,
	closeCommandLineAtom,
	updateSearchQueryAtom,
	selectCommandAtom,
	commandHistoryAtom,
	currentInputAtom,
	commandProgressAtom,
} from '../commands/store';
import { commandRegistry } from '../commands/registry';

/**
 * Hook to manage command line state and actions.
 *
 * @example
 * ```tsx
 * function CommandLineToggle() {
 *   const { visible, open, close } = useCommandLine();
 *
 *   return (
 *     <button onClick={visible ? close : open}>
 *       {visible ? 'Close' : 'Open'} Command Line
 *     </button>
 *   );
 * }
 * ```
 */
export function useCommandLine() {
	const visible = useAtomValue(commandLineVisibleAtom);
	const state = useAtomValue(commandLineStateAtom);
	const history = useAtomValue(commandHistoryAtom);
	const currentInput = useAtomValue(currentInputAtom);
	const progress = useAtomValue(commandProgressAtom);

	const open = useSetAtom(openCommandLineAtom);
	const close = useSetAtom(closeCommandLineAtom);
	const updateQuery = useSetAtom(updateSearchQueryAtom);
	const selectCommand = useSetAtom(selectCommandAtom);

	return {
		// State
		visible,
		state,
		history,
		currentInput,
		progress,

		// Actions
		open,
		close,
		updateQuery,
		selectCommand,

		// Helpers
		isSearching: state.phase === 'searching',
		isCollecting: state.phase === 'collecting',
		isExecuting: state.phase === 'executing',
		hasError: state.phase === 'error',
		errorMessage: state.phase === 'error' ? state.message : null,

		// Registry access
		allCommands: commandRegistry.all(),
		searchCommands: (query: string) => commandRegistry.search(query),
	};
}
