import { cleanup, render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CapabilityPanel } from '../../../src/components/CapabilityPanel';
import type {
  EngineState,
  FFmpegCapabilities,
} from '../../../src/ffmpeg/ffmpeg.types';
import { createResourcePolicy } from '../../../src/storage';

afterEach(cleanup);

describe('CapabilityPanel', () => {
  it('shows the active device-adjusted resource policy', async () => {
    const user = userEvent.setup();
    const policy = createResourcePolicy({
      softInputBytes: 128 * 1024 * 1024,
      hardSingleInputBytes: 512 * 1024 * 1024,
      hardTotalInputBytes: 768 * 1024 * 1024,
      softOutputEstimateBytes: 256 * 1024 * 1024,
      hardOutputEstimateBytes: 512 * 1024 * 1024,
    });

    render(
      <CapabilityPanel
        state={{ status: 'idle' }}
        preference="automatic"
        resourcePolicy={policy}
        deviceMemoryGiB={2}
        onPreferenceChange={vi.fn()}
        onInitialize={vi.fn()}
      />
    );

    await user.click(screen.getByText('Engine & browser'));
    expect(screen.getByText('Active resource limits')).toBeVisible();
    expect(screen.getByText('Adjusted for 2 GiB device memory')).toBeVisible();
    expect(screen.getByText('128 MiB / 512 MiB')).toBeVisible();
    expect(
      screen.getByText(/conservative estimates, not media format limits/i)
    ).toBeVisible();
  });

  it('reports the exact FFmpeg version, build flags, and capability counts', async () => {
    const user = userEvent.setup();
    render(
      <CapabilityPanel
        state={readyEngine()}
        preference="automatic"
        resourcePolicy={createResourcePolicy()}
        onPreferenceChange={vi.fn()}
        onInitialize={vi.fn()}
      />
    );

    await user.click(screen.getByText('Engine & browser'));
    expect(screen.getByTitle(/ffmpeg version n5\.1\.4/iu)).toHaveTextContent(
      'ffmpeg version n5.1.4'
    );
    expect(valueFor('Demuxers')).toHaveTextContent('3');
    expect(valueFor('Muxers')).toHaveTextContent('2');
    expect(valueFor('Decoders')).toHaveTextContent('4');
    expect(valueFor('Encoders')).toHaveTextContent('5');
    expect(valueFor('Filters')).toHaveTextContent('6');
    expect(
      screen.getByText('Detected capability inventory (20 entries)')
    ).toBeInTheDocument();
    expect(
      screen.getByText(
        /Demuxers \(3\)\s+matroska, mov, wav[\s\S]+Encoders \(5\)\s+aac, libvorbis, libvpx, libx264, png/u
      )
    ).toBeInTheDocument();
    expect(
      screen.getByText('FFmpeg build configuration (2 flags)')
    ).toBeInTheDocument();
    expect(
      screen.getByText(/--enable-gpl\s+--enable-libx264/u)
    ).toBeInTheDocument();
  });

  it('exposes controlled initialization failure details and retries', async () => {
    const user = userEvent.setup();
    const onInitialize = vi.fn();
    const state: EngineState = {
      status: 'error',
      error: {
        code: 'load-failed',
        message: 'The compatibility core could not be loaded.',
        details: 'worker bootstrap failed',
        exitCode: 1,
      },
    };

    render(
      <CapabilityPanel
        state={state}
        preference="automatic"
        resourcePolicy={createResourcePolicy()}
        onPreferenceChange={vi.fn()}
        onInitialize={onInitialize}
      />
    );

    await user.click(screen.getByText('Engine & browser'));
    expect(screen.getByRole('alert')).toHaveTextContent(
      'The compatibility core could not be loaded.'
    );
    expect(screen.getByText('load-failed')).toBeVisible();
    expect(screen.getByText('worker bootstrap failed')).toBeInTheDocument();
    await user.click(
      screen.getByRole('button', { name: 'Retry initialization' })
    );
    expect(onInitialize).toHaveBeenCalledOnce();
  });
});

function valueFor(label: string): HTMLElement {
  const container = screen.getByText(label).closest('div');
  if (!container) throw new Error(`Missing capability cell for ${label}`);
  return within(container).getByRole('definition');
}

function readyEngine(): EngineState {
  const capabilities: FFmpegCapabilities = {
    versionText:
      'ffmpeg version n5.1.4 Copyright the FFmpeg developers\nconfiguration: test',
    buildConfiguration: ['--enable-gpl', '--enable-libx264'],
    demuxers: new Set(['mov', 'matroska', 'wav']),
    muxers: new Set(['mp4', 'webm']),
    decoders: new Set(['h264', 'aac', 'vp8', 'vorbis']),
    encoders: new Set(['libx264', 'aac', 'libvpx', 'libvorbis', 'png']),
    filters: new Set(['scale', 'crop', 'fps', 'format', 'aresample', 'volume']),
  };
  return {
    status: 'ready',
    mode: 'single-thread',
    capabilities,
  };
}
