import { describe, it, expect, afterEach, vi } from 'vitest';
import { toast } from './toast.svelte';

afterEach(() => {
    toast.clear();
    vi.useRealTimers();
});

describe('toast store', () => {
    it('shows a toast with the given message and kind, returning its id', () => {
        const id = toast.show('hello', 'info');
        expect(toast.toasts).toHaveLength(1);
        expect(toast.toasts[0]).toMatchObject({ id, message: 'hello', kind: 'info' });
    });

    it('stacks multiple toasts in insertion order with distinct ids', () => {
        const a = toast.info('first');
        const b = toast.error('second');
        expect(toast.toasts.map((t) => t.message)).toEqual(['first', 'second']);
        expect(a).not.toBe(b);
    });

    it('exposes kind helpers', () => {
        toast.error('boom');
        toast.success('yay');
        expect(toast.toasts.map((t) => t.kind)).toEqual(['error', 'success']);
    });

    it('dismisses a toast by id', () => {
        const id = toast.info('bye');
        toast.dismiss(id);
        expect(toast.toasts).toHaveLength(0);
    });

    it('auto-dismisses after the timeout', () => {
        vi.useFakeTimers();
        toast.show('temp', 'info', 3000);
        expect(toast.toasts).toHaveLength(1);
        vi.advanceTimersByTime(3000);
        expect(toast.toasts).toHaveLength(0);
    });

    it('does not auto-dismiss when the timeout is 0 (sticky)', () => {
        vi.useFakeTimers();
        toast.show('sticky', 'error', 0);
        vi.advanceTimersByTime(60_000);
        expect(toast.toasts).toHaveLength(1);
    });

    it('clear() removes everything and cancels pending timers', () => {
        vi.useFakeTimers();
        toast.info('a');
        toast.info('b');
        toast.clear();
        expect(toast.toasts).toHaveLength(0);
        // A previously-scheduled auto-dismiss must not fire against a new toast.
        const id = toast.info('c', 0);
        vi.advanceTimersByTime(60_000);
        expect(toast.toasts).toEqual([{ id, message: 'c', kind: 'info' }]);
    });
});
