import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import StudentRecordDetailsView from '@/Components/Teacher/StudentRecordDetailsView';

/**
 * The record list doubles as the drill-down entry point on the teacher's
 * student profile. Totals roll up, so a top level skill can hold answers
 * without having any sub categories of its own — and selecting one of those
 * used to open an empty panel claiming the student had no data for a skill they
 * demonstrably had data for.
 */
describe('StudentRecordDetailsView', () => {
  const genre = { id: 1, parent_id: null, skill: 'Genre', depth: 1, total: 4, correct: 2, percentage: 50 };
  const analogy = { id: 2, parent_id: null, skill: 'Analogy', depth: 1, total: 2, correct: 2, percentage: 100 };

  const row = (name: string) => screen.getByRole('button', { name: new RegExp(name) });

  it('lists a row per record with its score', () => {
    render(<StudentRecordDetailsView records={[genre, analogy]} depth={1} />);

    expect(row('Analogy')).toHaveTextContent('2 / 2 (100%)');
    expect(row('Genre')).toHaveTextContent('2 / 4 (50%)');
  });

  it('leaves every row inert when no select handler is given', () => {
    render(<StudentRecordDetailsView records={[genre]} depth={1} />);

    expect(row('Genre')).toBeDisabled();
  });

  it('enables a row that canSelectSkill accepts', async () => {
    const onSelectSkill = vi.fn();

    render(
      <StudentRecordDetailsView
        records={[genre, analogy]}
        depth={1}
        canSelectSkill={(record) => record.id === genre.id}
        onSelectSkill={onSelectSkill}
      />
    );

    expect(row('Genre')).toBeEnabled();
    await userEvent.click(row('Genre'));

    expect(onSelectSkill).toHaveBeenCalledWith(expect.objectContaining({ id: genre.id }));
  });

  /** The fix: a skill with no sub categories must not be a dead end. */
  it('leaves a row that canSelectSkill rejects inert', async () => {
    const onSelectSkill = vi.fn();

    render(
      <StudentRecordDetailsView
        records={[genre, analogy]}
        depth={1}
        canSelectSkill={(record) => record.id === genre.id}
        onSelectSkill={onSelectSkill}
      />
    );

    expect(row('Analogy')).toBeDisabled();
    await userEvent.click(row('Analogy'));

    expect(onSelectSkill).not.toHaveBeenCalled();
  });

  it('selects every row when canSelectSkill is omitted', () => {
    render(
      <StudentRecordDetailsView records={[genre, analogy]} depth={1} onSelectSkill={vi.fn()} />
    );

    expect(row('Genre')).toBeEnabled();
    expect(row('Analogy')).toBeEnabled();
  });

  it('shows the empty state when there is nothing to list', () => {
    render(<StudentRecordDetailsView records={[]} depth={1} />);

    expect(screen.getByText(/No question answer data yet/i)).toBeInTheDocument();
  });
});
