/**
 * @jest-environment jsdom
 */

import * as React from 'react';
import 'jest-canvas-mock';
import { fireEvent, render, screen } from '@testing-library/react';

import { RadioButtons, InputOption } from '../../../src/ts';

describe('Radio Buttons', () => {
    const options = ['Red', 'Green', 'Blue'].map(function (e) {
        return new InputOption(e, e);
    });

    test('Default selection', () => {
        const { container } = render(
            <RadioButtons
                options={options}
                inline={true}
                defaultSelection={'Green'}
            />
        );
        expect(
            container.querySelector('input:checked').getAttribute('value')
        ).toBe('Green');
    });

    test('No default', () => {
        const { container } = render(
            <RadioButtons options={options} inline={true} />
        );

        expect(
            container.querySelector('input:checked').getAttribute('value')
        ).toBe('Red');
    });

    test('No options', () => {
        global.console = { ...global.console, warn: jest.fn() };
        render(<RadioButtons inline={true} />);

        expect(console.warn).toBeCalledWith(
            'RadioButtons: No options are available.'
        );
    });

    test('Selection', () => {
        const selectionHandler = jest.fn();
        render(
            <RadioButtons
                options={options}
                inline={true}
                defaultSelection={'Green'}
                onSelection={selectionHandler}
            />
        );

        const blueRadio = screen.getByRole('radio', {
            name: 'Blue',
        }) as HTMLInputElement;
        const redRadio = screen.getByRole('radio', {
            name: 'Red',
        }) as HTMLInputElement;

        expect(blueRadio.checked).toEqual(false);
        expect(redRadio.checked).toEqual(false);

        fireEvent.click(blueRadio);
        expect(blueRadio.checked).toEqual(true);
        expect(selectionHandler).toHaveBeenCalled();

        fireEvent.click(redRadio);
        expect(blueRadio.checked).toEqual(false);
        expect(redRadio.checked).toEqual(true);
    });
});
