import { describe, it, expect, beforeEach } from 'vitest';
import { createStore } from 'jotai';
import {
	eventMappingsAtom,
	activePresetIdAtom,
	allPresetsAtom,
	hasUnsavedChangesAtom,
	isPanelOpenAtom,
	setEventMappingAtom,
	applyPresetAtom,
	saveAsPresetAtom,
	deletePresetAtom,
	resetSettingsAtom,
	togglePanelAtom,
	setPanelOpenAtom,
	getActionForEvent,
} from '../core/settings-store';

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

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

	it('eventMappingsAtom returns an object', () => {
		const mappings = store.get(eventMappingsAtom);
		expect(typeof mappings).toBe('object');
	});

	it('allPresetsAtom contains built-in presets', () => {
		const presets = store.get(allPresetsAtom);
		expect(presets.length).toBeGreaterThan(0);
	});

	it('activePresetIdAtom has a default preset', () => {
		const id = store.get(activePresetIdAtom);
		expect(id).toBeTruthy();
	});

	it('isPanelOpenAtom starts false', () => {
		expect(store.get(isPanelOpenAtom)).toBe(false);
	});

	it('togglePanelAtom opens panel', () => {
		store.set(togglePanelAtom);
		expect(store.get(isPanelOpenAtom)).toBe(true);
	});

	it('setPanelOpenAtom sets panel state directly', () => {
		store.set(setPanelOpenAtom, true);
		expect(store.get(isPanelOpenAtom)).toBe(true);
		store.set(setPanelOpenAtom, false);
		expect(store.get(isPanelOpenAtom)).toBe(false);
	});

	it('resetSettingsAtom restores default preset', () => {
		const defaultPresetId = store.get(activePresetIdAtom);
		// Reset should preserve the default preset
		store.set(resetSettingsAtom);
		expect(store.get(activePresetIdAtom)).toBe(defaultPresetId);
	});

	it('getActionForEvent returns action for known event', () => {
		const mappings = store.get(eventMappingsAtom);
		const keys = Object.keys(mappings);
		if (keys.length > 0) {
			const action = getActionForEvent(mappings, keys[0] as any);
			expect(typeof action).toBe('string');
		}
	});
});
