import { describe, it, expect, vi } from 'vitest';
import { createStore } from 'jotai';
import { canvasToastAtom, showToastAtom } from '../core/toast-store';

describe('toast-store', () => {
	it('starts with null', () => {
		const store = createStore();
		expect(store.get(canvasToastAtom)).toBeNull();
	});

	it('showToastAtom sets a toast with id, message, timestamp', () => {
		const store = createStore();
		store.set(showToastAtom, 'Hello');
		const toast = store.get(canvasToastAtom);
		expect(toast).not.toBeNull();
		expect(toast!.message).toBe('Hello');
		expect(toast!.id).toMatch(/^toast-/);
		expect(toast!.timestamp).toBeGreaterThan(0);
	});

	it('auto-clears after 2 seconds', () => {
		vi.useFakeTimers();
		const store = createStore();
		store.set(showToastAtom, 'Temp');
		expect(store.get(canvasToastAtom)).not.toBeNull();

		vi.advanceTimersByTime(2100);
		expect(store.get(canvasToastAtom)).toBeNull();
		vi.useRealTimers();
	});

	it('does not clear a newer toast when an older one expires', () => {
		vi.useFakeTimers();
		const store = createStore();
		store.set(showToastAtom, 'First');
		vi.advanceTimersByTime(1000);
		store.set(showToastAtom, 'Second');
		vi.advanceTimersByTime(1100); // First timer fires at 2000ms
		// Second toast should still be visible
		const toast = store.get(canvasToastAtom);
		expect(toast).not.toBeNull();
		expect(toast!.message).toBe('Second');

		vi.advanceTimersByTime(1000); // Second timer fires at 3000ms
		expect(store.get(canvasToastAtom)).toBeNull();
		vi.useRealTimers();
	});
});
