import { describe, it, expect, beforeEach } from 'vitest';
import { createStore } from 'jotai';
import {
	inputModeAtom,
	commandLineVisibleAtom,
	commandLineStateAtom,
	commandFeedbackAtom,
	commandHistoryAtom,
	selectedSuggestionIndexAtom,
	pendingInputResolverAtom,
	isCommandActiveAtom,
	currentInputAtom,
	commandProgressAtom,
} from '../commands/store-atoms';

describe('store-atoms', () => {
	let store: ReturnType<typeof createStore>;

	beforeEach(() => {
		store = createStore();
	});

	it('inputModeAtom defaults to normal', () => {
		expect(store.get(inputModeAtom)).toEqual({ type: 'normal' });
	});

	it('commandLineVisibleAtom defaults to false', () => {
		expect(store.get(commandLineVisibleAtom)).toBe(false);
	});

	it('commandLineStateAtom defaults to idle', () => {
		expect(store.get(commandLineStateAtom).phase).toBe('idle');
	});

	it('commandFeedbackAtom defaults to null', () => {
		expect(store.get(commandFeedbackAtom)).toBeNull();
	});

	it('selectedSuggestionIndexAtom defaults to 0', () => {
		expect(store.get(selectedSuggestionIndexAtom)).toBe(0);
	});

	it('pendingInputResolverAtom defaults to null', () => {
		expect(store.get(pendingInputResolverAtom)).toBeNull();
	});

	it('isCommandActiveAtom is false when idle', () => {
		expect(store.get(isCommandActiveAtom)).toBe(false);
	});

	it('isCommandActiveAtom is true when executing', () => {
		store.set(commandLineStateAtom, { phase: 'executing', command: {} as any });
		expect(store.get(isCommandActiveAtom)).toBe(true);
	});

	it('isCommandActiveAtom is true when collecting', () => {
		store.set(commandLineStateAtom, {
			phase: 'collecting',
			command: { inputs: [{ name: 'x', type: 'text', prompt: 'pick' }] } as any,
			inputIndex: 0,
			collected: {},
		});
		expect(store.get(isCommandActiveAtom)).toBe(true);
	});

	it('currentInputAtom returns null when not collecting', () => {
		expect(store.get(currentInputAtom)).toBeNull();
	});

	it('currentInputAtom returns current input definition', () => {
		const input = { name: 'target', type: 'node', prompt: 'Pick' };
		store.set(commandLineStateAtom, {
			phase: 'collecting',
			command: { inputs: [input] } as any,
			inputIndex: 0,
			collected: {},
		});
		expect(store.get(currentInputAtom)).toEqual(input);
	});

	it('commandProgressAtom returns null when not collecting', () => {
		expect(store.get(commandProgressAtom)).toBeNull();
	});

	it('commandProgressAtom returns progress fraction', () => {
		store.set(commandLineStateAtom, {
			phase: 'collecting',
			command: { inputs: [{ name: 'a' }, { name: 'b' }, { name: 'c' }] } as any,
			inputIndex: 1,
			collected: {},
		});
		expect(store.get(commandProgressAtom)).toEqual({ current: 2, total: 3 });
	});
});
