import { Position } from '../common';
import { render, fireEvent, screen, mockMatchMedia } from '../test-utils';

import Modal, { ModalProps } from './Modal';

mockMatchMedia();

describe('Modal', () => {
  const props: ModalProps = {
    onClose: jest.fn(),
    body: 'Some body',
    position: Position.TOP,
    open: true,
  };

  beforeEach(() => {
    jest.clearAllMocks();
  });

  it(`doesn't calls onClose when click is inside modal`, () => {
    render(<Modal {...props} />);

    fireEvent.click(getDialog());
    expect(props.onClose).not.toHaveBeenCalled();
  });

  it('calls onClose if click outside the content', () => {
    render(<Modal {...props} />);
    expect(props.onClose).not.toHaveBeenCalled();

    fireEvent.click(screen.getByRole('presentation'));
    expect(props.onClose).toHaveBeenCalledTimes(1);
  });

  it("doesn't call onClose if click outside the content and closing on dimmer is disabled", () => {
    render(<Modal {...props} disableDimmerClickToClose />);

    fireEvent.click(screen.getByRole('presentation'));

    expect(props.onClose).not.toHaveBeenCalled();
  });

  it('calls onClose when Escape is pressed on Modal', () => {
    render(<Modal {...props} />);
    expect(props.onClose).not.toHaveBeenCalled();

    fireEvent.keyDown(getDialog(), { key: 'Escape' });
    expect(props.onClose).toHaveBeenCalledTimes(1);
  });

  it('calls onClose when Escape is pressed on document', () => {
    render(<Modal {...props} />);
    expect(props.onClose).not.toHaveBeenCalled();

    fireEvent.keyDown(document, { key: 'Escape' });
    expect(props.onClose).toHaveBeenCalledTimes(1);
  });

  const getDialog = () => screen.getByRole('dialog');
});
