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

const CODES = ['punctual', 'kind', 'clean'] as const;
const LABELS: Record<string, string> = { punctual: 'Punctual', kind: 'Kind', clean: 'Clean' };

function renderSelector(props: Partial<ReviewTagSelectorProps> = {}) {
  const onChange = jest.fn();
  const utils = render(
    <ThemeProvider>
      <ReviewTagSelector
        codes={CODES}
        selected={[]}
        onChange={onChange}
        labelFor={(code) => LABELS[code] ?? code}
        {...props}
      />
    </ThemeProvider>,
  );
  return { ...utils, onChange };
}

describe('<ReviewTagSelector/> component', () => {
  it('renders a chip per code with its label', () => {
    renderSelector();
    expect(screen.getByText('Punctual')).toBeInTheDocument();
    expect(screen.getByText('Kind')).toBeInTheDocument();
    expect(screen.getByText('Clean')).toBeInTheDocument();
  });

  it('adds a code to the selection when an unselected chip is clicked', async () => {
    const user = userEvent.setup();
    const { onChange } = renderSelector({ selected: ['punctual'] });
    await user.click(screen.getByText('Kind'));
    expect(onChange).toHaveBeenCalledWith(['punctual', 'kind']);
  });

  it('removes a code when a selected chip is clicked', async () => {
    const user = userEvent.setup();
    const { onChange } = renderSelector({ selected: ['punctual', 'kind'] });
    await user.click(screen.getByText('Punctual'));
    expect(onChange).toHaveBeenCalledWith(['kind']);
  });

  it('marks selected chips via aria-pressed', () => {
    renderSelector({ selected: ['clean'] });
    const cleanChip = screen.getByText('Clean').closest('[aria-pressed]');
    expect(cleanChip).toHaveAttribute('aria-pressed', 'true');
  });
});
