import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { ImportedMediaAsset } from '../../../src/app/application-state';
import { MediaBin } from '../../../src/components/MediaBin';

afterEach(cleanup);

describe('MediaBin', () => {
  it('shows browser metadata and offers optional detailed inspection', async () => {
    const user = userEvent.setup();
    const onInspect = vi.fn();
    const file = new File(['video'], 'lecture.mp4', { type: 'video/mp4' });
    const asset: ImportedMediaAsset = {
      id: 'lecture',
      file,
      objectUrl: 'blob:lecture',
      phase: 'idle',
      browserMetadata: {
        source: 'browser',
        file: {
          name: file.name,
          sizeBytes: file.size,
          declaredMimeType: file.type,
          inferredMimeType: file.type,
          lastModified: file.lastModified,
        },
        kind: 'video',
        durationSeconds: 2_622.48,
        width: 640,
        height: 480,
        hasVideo: true,
      },
    };

    render(
      <MediaBin
        assets={[asset]}
        selectedId={asset.id}
        onSelect={vi.fn()}
        onInspect={onInspect}
        onRemove={vi.fn()}
      />
    );

    expect(screen.getByText(/43:42\.48/u)).toBeVisible();
    expect(screen.getByText('Ready to play · Details on demand')).toBeVisible();
    expect(screen.getByText('lecture.mp4').closest('button')).toHaveAttribute(
      'aria-pressed',
      'true'
    );
    await user.click(
      screen.getByRole('button', {
        name: 'Inspect details for lecture.mp4',
      })
    );
    expect(onInspect).toHaveBeenCalledWith(asset.id);
  });

  it('keeps a source ready to play after detailed inspection fails', () => {
    const file = new File(['video'], 'lecture.mp4', { type: 'video/mp4' });
    const asset: ImportedMediaAsset = {
      id: 'lecture',
      file,
      objectUrl: 'blob:lecture',
      phase: 'error',
      error: 'Media inspection exceeded its safety limit.',
    };

    render(
      <MediaBin
        assets={[asset]}
        onSelect={vi.fn()}
        onInspect={vi.fn()}
        onRemove={vi.fn()}
      />
    );

    expect(screen.getByText('File ready · Details unavailable')).toBeVisible();
    expect(
      screen.getByRole('button', {
        name: 'Retry detailed inspection for lecture.mp4',
      })
    ).toBeEnabled();
    expect(
      screen.getByRole('button', {
        name: 'Retry detailed inspection for lecture.mp4',
      })
    ).toHaveAccessibleDescription(
      'Media inspection exceeded its safety limit.'
    );
  });
});
