import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/svelte';
import Toaster from './Toaster.svelte';
import { toast } from '$lib/toast.svelte';

afterEach(() => {
    cleanup();
    toast.clear();
});

describe('Toaster', () => {
    it('renders queued toasts with their message', async () => {
        toast.info('Saved');
        render(Toaster);
        expect(await screen.findByText('Saved')).toBeTruthy();
    });

    it('gives errors an assertive alert role and others a status role', () => {
        toast.error('Boom');
        toast.success('Yay');
        render(Toaster);
        const toasts = screen.getAllByTestId('toast');
        const error = toasts.find((t) => t.dataset.kind === 'error')!;
        const success = toasts.find((t) => t.dataset.kind === 'success')!;
        expect(error.getAttribute('role')).toBe('alert');
        expect(success.getAttribute('role')).toBe('status');
    });

    it('removes a toast when its dismiss button is clicked', async () => {
        toast.error('Dismiss me');
        render(Toaster);
        const btn = screen.getByLabelText('Dismiss notification');
        btn.click();
        await Promise.resolve();
        expect(screen.queryByText('Dismiss me')).toBeNull();
        expect(toast.toasts).toHaveLength(0);
    });
});
