// @vitest-environment jsdom
/**
 * Component tests for SubtasksPanel — the sub-run progress panel shown on the
 * Overview tab. Verifies the header/progress fraction renders, the progress bar
 * width reflects completed/total, each subtask card shows its status badge +
 * title, and that the per-subtask activity/file queries stay dormant until a
 * card is expanded (lazy: enabled only when expanded).
 */
import '../../../test/dom-setup';
import { describe, it, expect, vi } from 'vitest';
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderWithProviders } from '../../../test/render-helpers';
import '../../../i18n';
import type { SubtaskInfo } from '../../../api';
import * as api from '../../../api';
import { SubtasksPanel } from './SubtasksPanel';

// Card expansion fires these; mock so an expand never hits the network.
vi.mock('../../../api', async (importOriginal) => {
  const actual = await importOriginal<typeof import('../../../api')>();
  return {
    ...actual,
    fetchSubtaskActivity: vi.fn().mockResolvedValue(''),
    fetchSubtaskFiles: vi.fn().mockResolvedValue({ categories: {} }),
  };
});

function subtask(overrides: Partial<SubtaskInfo> = {}): SubtaskInfo {
  return {
    id: 'job-sub-1',
    issueNumber: 7,
    status: 'succeeded',
    instruction: 'Summarize chapter one\nthen extract the key points',
    worktreePath: null,
    createdAt: '2026-06-01T00:00:00Z',
    updatedAt: '2026-06-01T00:00:00Z',
    ...overrides,
  };
}

describe('SubtasksPanel', () => {
  it('renders the header with the completed/total fraction', () => {
    renderWithProviders(
      <SubtasksPanel
        taskId={1}
        subtasks={[subtask()]}
        subtaskCount={2}
        subtaskCompleted={1}
      />,
    );
    expect(screen.getByText('Sub-runs')).toBeInTheDocument();
    expect(screen.getByText(/1\/2/)).toBeInTheDocument();
  });

  it('reflects progress as a percentage width on the bar', () => {
    const { container } = renderWithProviders(
      <SubtasksPanel taskId={1} subtasks={[subtask()]} subtaskCount={4} subtaskCompleted={1} />,
    );
    // 1/4 = 25%.
    const bar = container.querySelector('[style*="width: 25%"]');
    expect(bar).not.toBeNull();
  });

  it('renders a card per subtask with status badge and first-line title', () => {
    renderWithProviders(
      <SubtasksPanel
        taskId={1}
        subtasks={[subtask({ status: 'failed', issueNumber: 9 })]}
        subtaskCount={1}
        subtaskCompleted={0}
      />,
    );
    // Status badge label (Failed).
    expect(screen.getByText('Failed')).toBeInTheDocument();
    // Title = issue number + first line of instruction.
    expect(screen.getByText(/#9 Summarize chapter one/)).toBeInTheDocument();
  });

  it('does not fetch subtask activity/files until a card is expanded', async () => {
    const user = userEvent.setup();
    renderWithProviders(
      <SubtasksPanel taskId={5} subtasks={[subtask()]} subtaskCount={1} subtaskCompleted={1} />,
    );
    // Collapsed: no lazy fetches yet.
    expect(api.fetchSubtaskFiles).not.toHaveBeenCalled();
    // Expanding the card enables the file query.
    await user.click(screen.getByText(/#7 Summarize chapter one/));
    expect(api.fetchSubtaskFiles).toHaveBeenCalled();
  });
});
