import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, expect, test, vi } from 'vitest';
import { api } from '../../api/client';
import type { VehicleSourceEvidence } from '../../api/types';
import { VehicleSourceEvidencePanel } from './VehicleSourceEvidencePanel';

const evidence: VehicleSourceEvidence = {
  vin: 'VIN-001',
  plate: '粤A12345',
  mileageDate: '2026-07-16',
  recommendedLocationProtocol: 'JT808',
  recommendedLocationLabel: 'G7',
  locationConflict: true,
  conflictDistanceM: 328,
  locationSources: [
    {
      protocol: 'JT808', sourceLabel: 'G7', terminalLabel: '终端 133****5425', sourceKind: 'PLATFORM',
      selectedWithinProtocol: true, recommended: true, enabled: true, priority: 20, online: true,
      qualityStatus: 'OK', qualityReason: '', longitude: 113.26, latitude: 23.13, speedKmh: 20,
      totalMileageKm: 1000, eventTime: '2026-07-16 10:00:00', receivedAt: '2026-07-16 10:00:01'
    },
    {
      protocol: 'JT808', sourceLabel: '北斗平台', terminalLabel: '终端 139****1208', sourceKind: 'PLATFORM',
      selectedWithinProtocol: false, recommended: false, enabled: true, priority: 30, online: true,
      qualityStatus: 'OK', qualityReason: '', longitude: 113.27, latitude: 23.14, speedKmh: 18,
      totalMileageKm: 998, eventTime: '2026-07-16 09:59:55', receivedAt: '2026-07-16 09:59:57'
    }
  ],
  mileageSources: [{
    protocol: 'JT808', sourceLabel: 'G7', terminalLabel: '终端 133****5425', sourceKind: 'PLATFORM',
    selectedWithinProtocol: true, recommended: true, enabled: true, priority: 20, qualityStatus: 'OK',
    qualityReason: '', firstTotalMileageKm: 990, latestTotalMileageKm: 1000, dailyMileageKm: 10,
    sampleCount: 100, firstEventTime: '2026-07-16 00:00:00', latestEventTime: '2026-07-16 10:00:00'
  }],
  comparison: { locationMaxDistanceM: 328, totalMileageDeltaKm: 2, dailyMileageDeltaKm: 0, reportTimeDeltaSeconds: 6 },
  asOf: '2026-07-16T10:00:02+08:00'
};

afterEach(() => {
  cleanup();
  vi.restoreAllMocks();
});

test('loads all source evidence only after the user expands it', async () => {
  const sourceEvidence = vi.spyOn(api, 'vehicleSourceEvidence').mockResolvedValue(evidence);
  const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });

  render(<QueryClientProvider client={client}><VehicleSourceEvidencePanel vin="VIN-001" /></QueryClientProvider>);

  expect(sourceEvidence).not.toHaveBeenCalled();
  fireEvent.click(screen.getByRole('button', { name: '查看全部来源' }));
  await waitFor(() => expect(sourceEvidence).toHaveBeenCalledTimes(1));
  expect(await screen.findByText('北斗平台')).toBeInTheDocument();
  expect(screen.getAllByText('当前推荐').length).toBeGreaterThan(0);
  expect(screen.queryByText('13307795425')).not.toBeInTheDocument();
  client.clear();
});
