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

afterEach(() => {
    cleanup();
    // @ts-expect-error — restore between tests
    delete window.matchMedia;
});

// jsdom has no matchMedia; stub it to drive the breakpoint branch.
function stubMatchMedia(matches: boolean) {
    window.matchMedia = vi.fn().mockImplementation((media: string) => ({
        matches,
        media,
        onchange: null,
        addEventListener: vi.fn(),
        removeEventListener: vi.fn(),
        addListener: vi.fn(),
        removeListener: vi.fn(),
        dispatchEvent: vi.fn()
    })) as unknown as typeof window.matchMedia;
}

const body = createRawSnippet(() => ({
    render: () => `<p data-testid="dlg-body">hello</p>`
}));

describe('AdaptiveDialog', () => {
    it('renders a centered Modal on desktop (the scrim is the Modal backdrop)', async () => {
        stubMatchMedia(false);
        render(AdaptiveDialog, {
            props: { open: true, title: 'Tag this page', onClose: () => {}, testid: 'dlg', children: body }
        });
        // Modal exposes a `${testid}-backdrop`; Sheet exposes `${testid}-scrim`.
        expect(await screen.findByTestId('dlg-backdrop')).toBeTruthy();
        expect(screen.queryByTestId('dlg-scrim')).toBeNull();
        expect(screen.getByRole('dialog', { name: 'Tag this page' })).toBeTruthy();
        expect(screen.getByTestId('dlg-body')).toBeTruthy();
    });

    it('renders a bottom Sheet on mobile', async () => {
        stubMatchMedia(true);
        render(AdaptiveDialog, {
            props: { open: true, title: 'Tag this page', onClose: () => {}, testid: 'dlg', children: body }
        });
        // The effect flips to mobile after mount; poll for the Sheet scrim.
        expect(await screen.findByTestId('dlg-scrim')).toBeTruthy();
        expect(screen.queryByTestId('dlg-backdrop')).toBeNull();
        expect(screen.getByRole('dialog', { name: 'Tag this page' })).toBeTruthy();
    });

    it('renders nothing when closed', () => {
        stubMatchMedia(false);
        render(AdaptiveDialog, {
            props: { open: false, title: 'Tag this page', onClose: () => {}, testid: 'dlg', children: body }
        });
        expect(screen.queryByRole('dialog')).toBeNull();
    });
});
