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();
  });
});

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

  it('renders the third "any" option', () => {
    renderAnyToggle(null);
    expect(screen.getByText('Any')).toBeInTheDocument();
  });

  it('calls onChange with "any" when picked', async () => {
    const user = userEvent.setup();
    const { onChange } = renderAnyToggle(null);
    await user.click(screen.getByText('Any'));
    expect(onChange).toHaveBeenCalledWith('any');
  });

  it('does not render the "any" option when allowAny is omitted', () => {
    renderToggle(null);
    expect(screen.queryByText('Any')).not.toBeInTheDocument();
  });
});
