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

import Info, { InfoPresentation } from '.';

mockMatchMedia();

describe('Info', () => {
  const defaultScreenReaderLabel = 'More information';
  const props = {
    content: 'content',
    className: 'className',
    title: 'title',
  };

  it('calls onClick on click event', async () => {
    const fn = jest.fn();
    await act(async () => {
      render(<Info {...props} onClick={fn} />);
    });
    await act(async () => {
      fireEvent.click(getTriggerButton());
    });
    expect(fn).toHaveBeenCalledTimes(1);
  });

  describe(`when in ${InfoPresentation.POPOVER} mode`, () => {
    it('renders help button trigger', async () => {
      render(<Info {...props} />);
      expect(getTriggerButton()).toBeInTheDocument();
    });
    it('opens popover onClick', async () => {
      render(<Info {...props} />);
      expect(getPopover()).not.toBeInTheDocument();
      await openPopover();
      expect(getPopover()).toBeInTheDocument();
    });
  });

  describe(`when in ${InfoPresentation.MODAL} mode`, () => {
    it('renders help button trigger', async () => {
      render(<Info {...props} />);

      expect(getTriggerButton()).toBeInTheDocument();
    });
    it('opens modal onClick', () => {
      render(<Info {...props} presentation={InfoPresentation.MODAL} />);

      expect(getModal()).not.toBeInTheDocument();

      fireEvent.click(getTriggerButton());

      expect(getModal()).toBeInTheDocument();
    });
  });

  it('accepts custom label for screen readers', () => {
    const customScreenReaderLabel = 'Custom message';
    render(<Info {...props} aria-label={customScreenReaderLabel} />);

    expect(screen.getByLabelText(customScreenReaderLabel)).toBeInTheDocument();
  });

  const getTriggerButton = () => screen.queryByLabelText(defaultScreenReaderLabel);
  const getPopover = () => screen.queryByRole('dialog');
  const getModal = () => screen.queryByRole('dialog');

  const openPopover = async () => {
    await act(async () => fireEvent.click(getTriggerButton()));
  };
});
