import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, cleanup, fireEvent } from '@testing-library/svelte';
import { createRawSnippet } from 'svelte';
import Sheet from './Sheet.svelte';

afterEach(() => cleanup());

function bodySnippet(text: string) {
    return createRawSnippet(() => ({
        render: () => `<p>${text}</p>`
    }));
}

describe('Sheet', () => {
    it('renders nothing when open=false', () => {
        render(Sheet, {
            props: {
                open: false,
                title: 'Filter',
                onClose: () => {},
                children: bodySnippet('hello')
            }
        });
        expect(screen.queryByRole('dialog')).toBeNull();
    });

    it('renders the dialog with title and body when open=true', () => {
        render(Sheet, {
            props: {
                open: true,
                title: 'Filter',
                onClose: () => {},
                children: bodySnippet('body content')
            }
        });
        const dialog = screen.getByRole('dialog', { name: 'Filter' });
        expect(dialog).toBeTruthy();
        expect(screen.getByText('body content')).toBeTruthy();
    });

    it('calls onClose when the X close button is clicked', () => {
        const onClose = vi.fn();
        render(Sheet, {
            props: {
                open: true,
                title: 'Filter',
                onClose,
                children: bodySnippet('x')
            }
        });
        screen.getByRole('button', { name: 'Close' }).click();
        expect(onClose).toHaveBeenCalledOnce();
    });

    it('calls onClose when the scrim is clicked (sheet variant always dismisses on scrim tap)', () => {
        const onClose = vi.fn();
        const { container } = render(Sheet, {
            props: {
                open: true,
                title: 'Filter',
                onClose,
                children: bodySnippet('x'),
                testid: 'filter-sheet'
            }
        });
        const scrim = container.querySelector('[data-testid="filter-sheet-scrim"]') as HTMLElement;
        scrim.click();
        expect(onClose).toHaveBeenCalledOnce();
    });

    it('calls onClose when Escape is pressed', async () => {
        const onClose = vi.fn();
        render(Sheet, {
            props: {
                open: true,
                title: 'Filter',
                onClose,
                children: bodySnippet('x')
            }
        });
        await fireEvent.keyDown(document, { key: 'Escape' });
        expect(onClose).toHaveBeenCalledOnce();
    });
});
