import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, expect, test, vi } from 'vitest';
import { VehicleCandidateList } from './VehicleCandidateList';

afterEach(cleanup);

const vehicles = [
  { vin: 'VIN001', plate: '粤A00001', protocols: ['GB32960', 'JT808'] },
  { vin: 'VIN002', plate: '粤A00002', protocols: ['JT808'] }
];

test('renders consistent Semi vehicle options and keeps plate first', () => {
  const onSelect = vi.fn();
  render(<VehicleCandidateList
    items={vehicles}
    selectedVins={new Set(['VIN002'])}
    selectedLabel="已分配"
    actionLabel="选择"
    showProtocols
    header="车辆候选"
    meta="1/20 已选"
    onSelect={onSelect}
  />);

  expect(screen.getByText('车辆候选')).toBeInTheDocument();
  expect(screen.getByText('1/20 已选')).toBeInTheDocument();
  const option = screen.getByRole('option', { name: '粤A00001 VIN001 GB/T 32960 JT/T 808 选择' });
  expect(option).toHaveClass('semi-button', 'v2-vehicle-option');
  expect(option).toHaveTextContent('粤A00001VIN001GB/T 32960JT/T 808选择');
  expect(option.querySelector('.semi-tag-blue-light')).toHaveTextContent('GB/T 32960');
  expect(option.querySelector('.semi-tag-cyan-light')).toHaveTextContent('JT/T 808');
  expect(screen.getByRole('option', { name: '粤A00002 VIN002 JT/T 808 已分配' })).toHaveAttribute('aria-selected', 'true');

  fireEvent.click(option);
  expect(onSelect).toHaveBeenCalledWith(vehicles[0]);
});

test('uses the shared retry and empty states', () => {
  const onRetry = vi.fn();
  const { rerender } = render(<VehicleCandidateList items={[]} error="车辆目录查询超时" onRetry={onRetry} onSelect={() => undefined} />);
  expect(screen.getByRole('alert')).toHaveTextContent('车辆目录查询超时');
  fireEvent.click(screen.getByRole('button', { name: '重试' }));
  expect(onRetry).toHaveBeenCalledOnce();

  rerender(<VehicleCandidateList items={[]} emptyText="没有已绑定车辆" onSelect={() => undefined} />);
  expect(screen.getByText('没有已绑定车辆')).toBeInTheDocument();
});
