import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider } from '../../theme';
import RelationSelect from './RelationSelect';

const OPTIONS = [
  { code: 'parent', label: 'Parent' },
  { code: 'self', label: 'Myself' },
];

function renderSelect(value: string | null) {
  const onChange = jest.fn();
  const utils = render(
    <ThemeProvider>
      <RelationSelect options={OPTIONS} value={value} onChange={onChange} />
    </ThemeProvider>,
  );
  return { ...utils, onChange };
}

describe('<RelationSelect/> component', () => {
  it('renders every relation option', () => {
    renderSelect(null);
    expect(screen.getByText('Parent')).toBeInTheDocument();
    expect(screen.getByText('Myself')).toBeInTheDocument();
  });

  it('marks the selected option as checked', () => {
    const { container } = renderSelect('self');
    expect(container.querySelector('[data-code="self"]')).toHaveAttribute('aria-checked', 'true');
    expect(container.querySelector('[data-code="parent"]')).toHaveAttribute('aria-checked', 'false');
  });

  it('calls onChange with the picked code', async () => {
    const user = userEvent.setup();
    const { onChange } = renderSelect(null);
    await user.click(screen.getByText('Parent'));
    expect(onChange).toHaveBeenCalledWith('parent');
  });

  it('renders a check icon on the selected card, not only a border color (WCAG 1.4.1)', () => {
    const { container } = renderSelect('self');
    const selectedCard = container.querySelector('[data-code="self"]');
    const unselectedCard = container.querySelector('[data-code="parent"]');
    expect(selectedCard?.querySelector('svg')).toBeInTheDocument();
    expect(unselectedCard?.querySelector('svg')).not.toBeInTheDocument();
  });
});
