import { describe, it, expect, beforeEach } from 'vitest';
import { createStore } from 'jotai';
import {
	isRepeatBlocked,
	getSelectedNodeIds,
	clearSelectionState,
	resolveFocusableNodeId,
	getCurrentSubject,
} from '../gestures/modifier-helpers';
import { selectedNodeIdsAtom, focusedNodeIdAtom } from '../core/selection-store';

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

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

	describe('isRepeatBlocked', () => {
		it('returns true for key repeat events', () => {
			const event = { kind: 'key' as const, phase: 'down' as const, key: 'a', code: 'KeyA', repeat: true, modifiers: {} };
			expect(isRepeatBlocked(event as any)).toBe(true);
		});

		it('returns false for non-repeat key events', () => {
			const event = { kind: 'key' as const, phase: 'down' as const, key: 'a', code: 'KeyA', repeat: false, modifiers: {} };
			expect(isRepeatBlocked(event as any)).toBe(false);
		});

		it('returns false for pointer events', () => {
			const event = { kind: 'pointer' as const };
			expect(isRepeatBlocked(event as any)).toBe(false);
		});
	});

	describe('getSelectedNodeIds', () => {
		it('returns empty array when no selection', () => {
			expect(getSelectedNodeIds(store)).toEqual([]);
		});

		it('returns selected node IDs', () => {
			store.set(selectedNodeIdsAtom, new Set(['n1', 'n2']));
			const ids = getSelectedNodeIds(store);
			expect(ids).toContain('n1');
			expect(ids).toContain('n2');
		});
	});

	describe('resolveFocusableNodeId', () => {
		it('returns null when nothing focused or selected', () => {
			expect(resolveFocusableNodeId(store)).toBeNull();
		});

		it('returns focused node ID if set', () => {
			store.set(focusedNodeIdAtom, 'focused-node');
			expect(resolveFocusableNodeId(store)).toBe('focused-node');
		});

		it('falls back to first selected node', () => {
			store.set(selectedNodeIdsAtom, new Set(['sel1', 'sel2']));
			const result = resolveFocusableNodeId(store);
			expect(result).toBeTruthy();
		});
	});

	describe('getCurrentSubject', () => {
		it('returns background when nothing active', () => {
			expect(getCurrentSubject(store)).toEqual({ kind: 'background' });
		});
	});
});
