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

afterEach(() => {
  cleanup();
  window.history.replaceState(null, '', '/');
  vi.restoreAllMocks();
});

test('renders vehicle platform shell', () => {
  render(<App />);
  expect(screen.getByText('车辆服务中台')).toBeInTheDocument();
  expect(screen.getAllByText('总览工作台').length).toBeGreaterThanOrEqual(1);
});

test('opens vehicle detail from shareable hash', async () => {
  window.history.replaceState(null, '', '/#/detail?keyword=%E7%B2%A4AG18312');
  vi.spyOn(globalThis, 'fetch').mockResolvedValue({
    ok: true,
    json: async () => ({
      data: {
        vin: 'LB9A32A24R0LS1426',
        lookupKey: '粤AG18312',
        lookupResolved: true,
        resolution: {
          lookupKey: '粤AG18312',
          resolved: true,
          vin: 'LB9A32A24R0LS1426',
          plate: '粤AG18312',
          phone: '13307795425',
          oem: 'G7s',
          protocols: ['GB32960', 'JT808'],
          online: true,
          lastSeen: '2026-07-03 20:12:10'
        },
        sources: ['GB32960', 'JT808'],
        sourceStatus: [],
        realtime: [],
        history: { items: [], total: 0, limit: 20, offset: 0 },
        raw: { items: [], total: 0, limit: 10, offset: 0 },
        mileage: { items: [], total: 0, limit: 20, offset: 0 },
        quality: { items: [], total: 0, limit: 20, offset: 0 }
      },
      traceId: 'trace-test',
      timestamp: 1783094400000
    })
  } as Response);

  render(<App />);

  expect(await screen.findByDisplayValue('粤AG18312')).toBeInTheDocument();
  expect(screen.getAllByText('车辆服务').length).toBeGreaterThanOrEqual(1);
});

test('applies protocol from shareable history hash to API requests', async () => {
  window.history.replaceState(null, '', '/#/history?keyword=%E7%B2%A4AG18312&protocol=JT808');
  const fetchMock = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
    const path = String(input);
    if (path.includes('/api/ops/health')) {
      return {
        ok: true,
        json: async () => ({
          data: { linkHealth: [], kafkaLag: 0, redisOnlineKeys: 0, tdengineWritable: true, mysqlWritable: true, runtime: { requestTimeoutMs: 5000 } },
          traceId: 'trace-test',
          timestamp: 1783094400000
        })
      } as Response;
    }
    return {
      ok: true,
      json: async () => ({
        data: { items: [], total: 0, limit: 10, offset: 0 },
        traceId: 'trace-test',
        timestamp: 1783094400000
      })
    } as Response;
  });

  render(<App />);

  await waitFor(() => {
    expect(fetchMock).toHaveBeenCalledWith(expect.stringContaining('/api/history/locations?'), undefined);
  });
  expect(fetchMock).toHaveBeenCalledWith(expect.stringContaining('protocol=JT808'), undefined);
  expect(fetchMock).toHaveBeenCalledWith('/api/history/raw-frames/query', expect.objectContaining({
    method: 'POST',
    body: expect.stringContaining('"protocol":"JT808"')
  }));
});

test('keeps row protocol when opening vehicle service from history results', async () => {
  window.history.replaceState(null, '', '/#/history?keyword=%E7%B2%A4AG18312&protocol=JT808');
  vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
    const path = String(input);
    if (path.includes('/api/ops/health')) {
      return {
        ok: true,
        json: async () => ({
          data: { linkHealth: [], kafkaLag: 0, redisOnlineKeys: 0, tdengineWritable: true, mysqlWritable: true, runtime: { requestTimeoutMs: 5000 } },
          traceId: 'trace-test',
          timestamp: 1783094400000
        })
      } as Response;
    }
    if (path.includes('/api/history/locations')) {
      return {
        ok: true,
        json: async () => ({
          data: {
            items: [{
              vin: 'VIN-JT808-001',
              plate: '粤AG18312',
              protocol: 'JT808',
              longitude: 113.2,
              latitude: 23.1,
              speedKmh: 30,
              socPercent: 0,
              totalMileageKm: 100,
              lastSeen: '2026-07-03 20:12:10',
              deviceTime: '2026-07-03 20:12:10',
              serverTime: '2026-07-03 20:12:11'
            }],
            total: 1,
            limit: 10,
            offset: 0
          },
          traceId: 'trace-test',
          timestamp: 1783094400000
        })
      } as Response;
    }
    if (path.includes('/api/vehicles/resolve')) {
      return {
        ok: true,
        json: async () => ({
          data: {
            lookupKey: 'VIN-JT808-001',
            resolved: true,
            vin: 'VIN-JT808-001',
            plate: '粤AG18312',
            phone: '13307795425',
            oem: 'G7s',
            protocols: ['JT808'],
            online: true,
            lastSeen: '2026-07-03 20:12:10'
          },
          traceId: 'trace-test',
          timestamp: 1783094400000
        })
      } as Response;
    }
    return {
      ok: true,
      json: async () => ({
        data: { items: [], total: 0, limit: 10, offset: 0 },
        traceId: 'trace-test',
        timestamp: 1783094400000
      })
    } as Response;
  });

  render(<App />);

  expect(await screen.findByText('VIN-JT808-001')).toBeInTheDocument();
  fireEvent.click(screen.getAllByRole('button', { name: '车辆服务' })[0]);

  await waitFor(() => {
    expect(window.location.hash).toBe('#/detail?keyword=VIN-JT808-001&protocol=JT808');
  });
});

test('keeps primary protocol when opening vehicle service from realtime vehicles', async () => {
  window.history.replaceState(null, '', '/#/realtime');
  vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
    const path = String(input);
    if (path.includes('/api/realtime/vehicles')) {
      return {
        ok: true,
        json: async () => ({
          data: {
            items: [{
              vin: 'VIN-MQTT-001',
              plate: '川AHTWO1',
              phone: '',
              oem: '宇通',
              protocols: ['GB32960', 'YUTONG_MQTT'],
              sourceCount: 2,
              onlineSourceCount: 1,
              online: true,
              primaryProtocol: 'YUTONG_MQTT',
              longitude: 113.2,
              latitude: 23.1,
              speedKmh: 30,
              socPercent: 78,
              totalMileageKm: 119925,
              lastSeen: '2026-07-03 20:12:10'
            }],
            total: 1,
            limit: 50,
            offset: 0
          },
          traceId: 'trace-test',
          timestamp: 1783094400000
        })
      } as Response;
    }
    if (path.includes('/api/vehicles/resolve')) {
      return {
        ok: true,
        json: async () => ({
          data: {
            lookupKey: 'VIN-MQTT-001',
            resolved: true,
            vin: 'VIN-MQTT-001',
            plate: '川AHTWO1',
            phone: '',
            oem: '宇通',
            protocols: ['GB32960', 'YUTONG_MQTT'],
            online: true,
            lastSeen: '2026-07-03 20:12:10'
          },
          traceId: 'trace-test',
          timestamp: 1783094400000
        })
      } as Response;
    }
    return {
      ok: true,
      json: async () => ({
        data: { items: [], total: 0, limit: 10, offset: 0 },
        traceId: 'trace-test',
        timestamp: 1783094400000
      })
    } as Response;
  });

  render(<App />);

  expect(await screen.findByText('VIN-MQTT-001')).toBeInTheDocument();
  fireEvent.click(screen.getByRole('button', { name: '车辆服务' }));

  await waitFor(() => {
    expect(window.location.hash).toBe('#/detail?keyword=VIN-MQTT-001&protocol=YUTONG_MQTT');
  });
});

test('switches vehicle detail to a source from the coverage cards', async () => {
  window.history.replaceState(null, '', '/#/detail?keyword=VIN001');
  const fetchMock = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
    const path = String(input);
    if (path.includes('/api/vehicles/detail')) {
      return {
        ok: true,
        json: async () => ({
          data: {
            vin: 'VIN001',
            lookupKey: 'VIN001',
            lookupResolved: true,
            resolution: {
              lookupKey: 'VIN001',
              resolved: true,
              vin: 'VIN001',
              plate: '粤AG18312',
              phone: '13307795425',
              oem: 'G7s',
              protocols: ['GB32960', 'JT808', 'YUTONG_MQTT'],
              online: true,
              lastSeen: '2026-07-03 20:12:10'
            },
            realtimeSummary: {
              vin: 'VIN001',
              plate: '粤AG18312',
              phone: '13307795425',
              oem: 'G7s',
              protocols: ['GB32960', 'JT808', 'YUTONG_MQTT'],
              sourceCount: 3,
              onlineSourceCount: 2,
              online: true,
              primaryProtocol: 'GB32960',
              longitude: 113.2,
              latitude: 23.1,
              speedKmh: 30,
              socPercent: 78,
              totalMileageKm: 100,
              lastSeen: '2026-07-03 20:12:10'
            },
            sources: ['GB32960', 'JT808', 'YUTONG_MQTT'],
            sourceStatus: [
              { protocol: 'GB32960', online: true, lastSeen: '2026-07-03 20:12:10', hasRealtime: true, hasHistory: true, hasRaw: true, hasMileage: true },
              { protocol: 'JT808', online: true, lastSeen: '2026-07-03 20:12:08', hasRealtime: true, hasHistory: true, hasRaw: true, hasMileage: true },
              { protocol: 'YUTONG_MQTT', online: false, lastSeen: '2026-07-03 20:10:00', hasRealtime: true, hasHistory: false, hasRaw: true, hasMileage: false }
            ],
            realtime: [],
            history: { items: [], total: 0, limit: 20, offset: 0 },
            raw: { items: [], total: 0, limit: 10, offset: 0 },
            mileage: { items: [], total: 0, limit: 20, offset: 0 },
            quality: { items: [], total: 0, limit: 20, offset: 0 }
          },
          traceId: 'trace-test',
          timestamp: 1783094400000
        })
      } as Response;
    }
    return {
      ok: true,
      json: async () => ({
        data: { items: [], total: 0, limit: 10, offset: 0 },
        traceId: 'trace-test',
        timestamp: 1783094400000
      })
    } as Response;
  });

  render(<App />);

  expect(await screen.findByText('VIN001')).toBeInTheDocument();
  fireEvent.click(screen.getByRole('button', { name: '仅看 JT808' }));

  await waitFor(() => {
    expect(window.location.hash).toBe('#/detail?keyword=VIN001&protocol=JT808');
  });
  expect(fetchMock).toHaveBeenCalledWith(expect.stringContaining('/api/vehicles/detail?keyword=VIN001&protocol=JT808'), undefined);
});

test('opens history with the currently selected vehicle detail source', async () => {
  window.history.replaceState(null, '', '/#/detail?keyword=VIN001');
  vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
    const path = String(input);
    if (path.includes('/api/vehicles/detail')) {
      return {
        ok: true,
        json: async () => ({
          data: {
            vin: 'VIN001',
            lookupKey: 'VIN001',
            lookupResolved: true,
            resolution: {
              lookupKey: 'VIN001',
              resolved: true,
              vin: 'VIN001',
              plate: '粤AG18312',
              phone: '13307795425',
              oem: 'G7s',
              protocols: ['GB32960', 'JT808'],
              online: true,
              lastSeen: '2026-07-03 20:12:10'
            },
            realtimeSummary: {
              vin: 'VIN001',
              plate: '粤AG18312',
              phone: '13307795425',
              oem: 'G7s',
              protocols: ['GB32960', 'JT808'],
              sourceCount: 2,
              onlineSourceCount: 2,
              online: true,
              primaryProtocol: 'GB32960',
              longitude: 113.2,
              latitude: 23.1,
              speedKmh: 30,
              socPercent: 78,
              totalMileageKm: 100,
              lastSeen: '2026-07-03 20:12:10'
            },
            sources: ['GB32960', 'JT808'],
            sourceStatus: [
              { protocol: 'GB32960', online: true, lastSeen: '2026-07-03 20:12:10', hasRealtime: true, hasHistory: true, hasRaw: true, hasMileage: true },
              { protocol: 'JT808', online: true, lastSeen: '2026-07-03 20:12:08', hasRealtime: true, hasHistory: true, hasRaw: true, hasMileage: true }
            ],
            realtime: [],
            history: { items: [], total: 0, limit: 20, offset: 0 },
            raw: { items: [], total: 0, limit: 10, offset: 0 },
            mileage: { items: [], total: 0, limit: 20, offset: 0 },
            quality: { items: [], total: 0, limit: 20, offset: 0 }
          },
          traceId: 'trace-test',
          timestamp: 1783094400000
        })
      } as Response;
    }
    return {
      ok: true,
      json: async () => ({
        data: { items: [], total: 0, limit: 10, offset: 0 },
        traceId: 'trace-test',
        timestamp: 1783094400000
      })
    } as Response;
  });

  render(<App />);

  fireEvent.click(await screen.findByRole('button', { name: '仅看 JT808' }));
  fireEvent.click(screen.getByRole('button', { name: '查看历史' }));

  await waitFor(() => {
    expect(window.location.hash).toBe('#/history?keyword=VIN001&protocol=JT808');
  });
});

test('opens vehicle service from an empty history query with the current filters', async () => {
  window.history.replaceState(null, '', '/#/history?keyword=VIN404&protocol=JT808');
  vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
    const path = String(input);
    if (path.includes('/api/vehicles/resolve')) {
      return {
        ok: true,
        json: async () => ({
          data: {
            lookupKey: 'VIN404',
            resolved: true,
            vin: 'VIN404',
            plate: '',
            phone: '',
            oem: '',
            protocols: ['JT808'],
            online: false,
            lastSeen: ''
          },
          traceId: 'trace-test',
          timestamp: 1783094400000
        })
      } as Response;
    }
    return {
      ok: true,
      json: async () => ({
        data: path.includes('/api/ops/health')
          ? { linkHealth: [], kafkaLag: 0, redisOnlineKeys: 0, tdengineWritable: true, mysqlWritable: true, runtime: { requestTimeoutMs: 5000 } }
          : { items: [], total: 0, limit: 10, offset: 0 },
        traceId: 'trace-test',
        timestamp: 1783094400000
      })
    } as Response;
  });

  render(<App />);

  fireEvent.click(await screen.findByRole('button', { name: '当前车辆服务' }));

  await waitFor(() => {
    expect(window.location.hash).toBe('#/detail?keyword=VIN404&protocol=JT808');
  });
});
