import { render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { WorkSession } from '@solelog/shared';
import Live from './Live';
import { apiFetch } from '../lib/api';

vi.mock('../lib/api', () => ({
  apiFetch: vi.fn(),
}));

const mockApiFetch = vi.mocked(apiFetch);

function makeSession(over: Partial<WorkSession>): WorkSession {
  return {
    id: 1,
    user_id: 'u1',
    activity_id: 10,
    activity_name: 'Frezen',
    user_name: 'Jan',
    insole_type: 'Kurk',
    pair_count: 4,
    start_time: new Date(Date.now() - 65_000).toISOString(),
    end_time: null,
    duration_seconds: null,
    status: 'active',
    source: 'app',
    notes: null,
    created_at: new Date().toISOString(),
    ...over,
  };
}

function renderLive() {
  const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return render(
    <QueryClientProvider client={queryClient}>
      <Live />
    </QueryClientProvider>
  );
}

describe('Live', () => {
  beforeEach(() => {
    mockApiFetch.mockReset();
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it('renders a card per active session with header count', async () => {
    mockApiFetch.mockResolvedValue([
      makeSession({ id: 1, user_name: 'Jan', activity_name: 'Frezen', insole_type: 'Kurk' }),
      makeSession({ id: 2, user_name: 'Piet', activity_name: 'Lijmen', insole_type: 'Berk' }),
    ]);

    renderLive();

    expect(await screen.findByText('Actief nu (2)')).toBeInTheDocument();
    expect(screen.getByText('Jan')).toBeInTheDocument();
    expect(screen.getByText('Frezen')).toBeInTheDocument();
    expect(screen.getByText('Piet')).toBeInTheDocument();
    expect(screen.getByText('Lijmen')).toBeInTheDocument();
  });

  it('shows the empty state when nobody is working', async () => {
    mockApiFetch.mockResolvedValue([]);

    renderLive();

    expect(await screen.findByText('Niemand is nu aan het werk.')).toBeInTheDocument();
    expect(screen.getByText('Actief nu (0)')).toBeInTheDocument();
  });
});
