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

function renderToggle(value: 'male' | 'female' | null) {
  const onChange = jest.fn();
  const utils = render(
    <ThemeProvider>
      <GenderToggle value={value} onChange={onChange} maleLabel="Male" femaleLabel="Female" />
    </ThemeProvider>,
  );
  return { ...utils, onChange };
}

describe('<GenderToggle/> component', () => {
  it('renders both options', () => {
    renderToggle(null);
    expect(screen.getByText('Male')).toBeInTheDocument();
    expect(screen.getByText('Female')).toBeInTheDocument();
  });

  it('marks the selected value as pressed', () => {
    const { container } = renderToggle('female');
    expect(container.querySelector('[data-gender="female"]')).toHaveAttribute('aria-pressed', 'true');
    expect(container.querySelector('[data-gender="male"]')).toHaveAttribute('aria-pressed', 'false');
  });

  it('calls onChange with the picked gender', async () => {
    const user = userEvent.setup();
    const { onChange } = renderToggle(null);
    await user.click(screen.getByText('Male'));
    expect(onChange).toHaveBeenCalledWith('male');
  });

  it('does not fire onChange when the active value is clicked again (no deselect)', async () => {
    const user = userEvent.setup();
    const { onChange } = renderToggle('male');
    await user.click(screen.getByText('Male'));
    expect(onChange).not.toHaveBeenCalled();
  });
});
