/**
 * Accessibility tests for ConfirmDialog (T4). The dialog had role="dialog" +
 * aria-modal but no keyboard handling: Escape didn't close it and focus was
 * never moved into it (WCAG 2.1.2 / 2.4.3). These tests pin the fixes.
 */
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ConfirmDialog } from '../ConfirmDialog';

function setup(overrides = {}) {
    const props = {
        isOpen: true,
        onClose: jest.fn(),
        onConfirm: jest.fn(),
        title: 'Delete monitor?',
        description: 'This cannot be undone.',
        ...overrides,
    };
    render(<ConfirmDialog {...props} />);
    return props;
}

describe('<ConfirmDialog> accessibility', () => {
    it('calls onClose when Escape is pressed', async () => {
        const { onClose } = setup();
        await userEvent.keyboard('{Escape}');
        expect(onClose).toHaveBeenCalledTimes(1);
    });

    it('moves focus into the dialog when opened', () => {
        setup();
        const dialog = screen.getByRole('dialog');
        expect(dialog.contains(document.activeElement)).toBe(true);
    });

    it('associates the description with the dialog via aria-describedby', () => {
        setup();
        const dialog = screen.getByRole('dialog');
        const describedById = dialog.getAttribute('aria-describedby');
        expect(describedById).toBeTruthy();
        expect(document.getElementById(describedById as string)).toHaveTextContent(
            'This cannot be undone.',
        );
    });

    // Regression: the focus-management effect must not depend on the (inline,
    // unstable) onClose, or it re-runs on every parent re-render and steals
    // focus out of the reason textarea on each keystroke.
    it('does not re-steal focus from its input when the parent re-renders', () => {
        const base = {
            isOpen: true as const,
            onConfirm: jest.fn(),
            title: 'Delete monitor?',
            description: 'Type to confirm.',
            inputPlaceholder: 'Reason',
        };
        const { rerender } = render(<ConfirmDialog {...base} onClose={() => {}} />);
        const input = screen.getByPlaceholderText('Reason');
        input.focus();
        expect(document.activeElement).toBe(input);

        rerender(<ConfirmDialog {...base} onClose={() => {}} />);
        expect(document.activeElement).toBe(input);
    });
});
