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 { useMobileLayout } from '../hooks/useMobileLayout';
import { VehicleSourceEvidencePanel } from './VehicleSourceEvidencePanel';

vi.mock('../hooks/useMobileLayout', () => ({ useMobileLayout: vi.fn(() => false) }));

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', providerOverride: '', 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: '北斗平台', providerOverride: '', 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();
  vi.mocked(useMobileLayout).mockReturnValue(false);
});

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

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

  expect(view.container.querySelector('.v2-source-evidence')).toHaveClass('semi-card');
  expect(sourceEvidence).not.toHaveBeenCalled();
  fireEvent.click(screen.getByRole('button', { name: '查看全部来源' }));
  await waitFor(() => expect(sourceEvidence).toHaveBeenCalledTimes(1));
  expect(await screen.findByText('北斗平台')).toBeInTheDocument();
  expect(view.container.querySelectorAll('.v2-source-evidence-card.semi-card')).toHaveLength(3);
  expect(screen.getAllByText('当前推荐').every((item) => item.closest('.semi-tag'))).toBe(true);
  expect(screen.getAllByText('当前推荐').length).toBeGreaterThan(0);
  expect(screen.queryByText('13307795425')).not.toBeInTheDocument();
  client.clear();
});

test('opens source evidence in a Semi bottom SideSheet on mobile without expanding the page card', async () => {
  vi.mocked(useMobileLayout).mockReturnValue(true);
  const sourceEvidence = vi.spyOn(api, 'vehicleSourceEvidence').mockResolvedValue(evidence);
  const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });

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

  fireEvent.click(screen.getByRole('button', { name: '查看全部来源' }));

  await waitFor(() => expect(sourceEvidence).toHaveBeenCalledTimes(1));
  expect(view.container.querySelector('.v2-source-evidence.is-mobile-sheet')).toHaveClass('is-open');
  expect(view.container.querySelector('.v2-source-evidence > .semi-card-body > .v2-source-evidence-body')).not.toBeInTheDocument();
  expect(await screen.findByText('北斗平台')).toBeInTheDocument();
  expect(document.querySelector('.v2-source-evidence-sidesheet')).toHaveClass('v2-workspace-detail-sidesheet');
  expect(document.querySelector('.v2-source-evidence-sidesheet .v2-workspace-config-title > .semi-tag')).toHaveTextContent('3 个来源');
  expect(document.querySelectorAll('.v2-source-evidence-sidesheet .v2-source-evidence-card')).toHaveLength(3);

  fireEvent.click(screen.getByRole('button', { name: '关闭来源证据' }));
  await waitFor(() => expect(view.container.querySelector('.v2-source-evidence')).not.toHaveClass('is-open'));
  client.clear();
});
