/**
 * Regression: on refresh, the compare page must show the SSR-rendered data.
 *
 * The basket hydrates from the URL a beat after mount (selectedSchools is
 * empty for the first render), so the fetch effect must not blank the
 * SSR payload during that window — and must not refetch data the server
 * already provided.
 */

import { render, screen, waitFor } from '@testing-library/react';

import { ComparisonView } from '@/components/ComparisonView';
import { ComparisonProvider } from '@/context/ComparisonProvider';
import type { ComparisonData, School } from '@/lib/types';

const fetchComparison = jest.fn();
jest.mock('@/lib/api', () => ({
  fetchComparison: (...args: unknown[]) => fetchComparison(...args),
}));
jest.mock('@/lib/analytics', () => ({ track: jest.fn() }));

function school(urn: number, name: string): School {
  return {
    urn,
    school_name: name,
    local_authority: 'Testshire',
    school_type: 'Community school',
    rwm_expected_pct: 80,
    phase: 'Primary',
  } as School;
}

function data(urn: number, name: string): ComparisonData {
  return {
    school_info: school(urn, name),
    yearly_data: [{ year: 202425, rwm_expected_pct: 80 }] as ComparisonData['yearly_data'],
    ofsted: null,
    census: null,
    admissions: null,
    admissions_history: [],
    deprivation: null,
  };
}

const INITIAL_DATA = {
  '100': data(100, 'Alpha Primary'),
  '200': data(200, 'Beta Primary'),
};

beforeEach(() => {
  fetchComparison.mockReset();
});

test('renders SSR data on refresh without wiping it or refetching', async () => {
  render(
    <ComparisonProvider>
      <ComparisonView
        initialData={INITIAL_DATA}
        initialNationalAverages={{
          year: 202425,
          primary: { rwm_expected_pct: 62 },
          secondary: {},
          by_year: [],
        }}
        initialBenchmarks={undefined}
        initialUrns={[100, 200]}
        metrics={[]}
        selectedMetric="rwm_expected_pct"
      />
    </ComparisonProvider>,
  );

  // Both SSR-provided schools appear (data was not blanked during hydration)
  await waitFor(() => {
    expect(screen.getAllByText('Alpha Primary').length).toBeGreaterThan(0);
  });
  expect(screen.getAllByText('Beta Primary').length).toBeGreaterThan(0);
  expect(screen.getByRole('heading', { name: 'At a glance' })).toBeInTheDocument();

  // …and the client never refetched data the server already rendered.
  expect(fetchComparison).not.toHaveBeenCalled();
});
