import { describe, it, expect, vi, beforeEach } from 'vitest';
import React from 'react';

// Mock IntersectionObserver
class MockIntersectionObserver {
  observe = vi.fn();
  unobserve = vi.fn();
  disconnect = vi.fn();
}
vi.stubGlobal('IntersectionObserver', MockIntersectionObserver);

import { screen } from '@testing-library/react';
import { renderWithProviders as render } from '../../../test/render';
import { VideoPlayer } from './VideoPlayer';

// Mock HTMLVideoElement methods
beforeEach(() => {
  vi.clearAllMocks();
  window.HTMLMediaElement.prototype.play = vi.fn().mockResolvedValue(undefined);
  window.HTMLMediaElement.prototype.pause = vi.fn();
  window.HTMLMediaElement.prototype.load = vi.fn();
});

describe('VideoPlayer', () => {
  it('renders the video element with correct src', () => {
    const { container } = render(<VideoPlayer src="test-video.mp4" />);
    const video = container.querySelector('video');
    expect(video).toBeTruthy();
    expect(video?.getAttribute('src')).toBe('test-video.mp4');
  });

  it('renders with the given title', () => {
    const { container } = render(<VideoPlayer src="test.mp4" title="My Video" />);
    const video = container.querySelector('video');
    expect(video).toBeTruthy();
    expect(video?.getAttribute('title')).toBe('My Video');
  });

  it('renders the poster attribute when provided', () => {
    const { container } = render(<VideoPlayer src="test.mp4" poster="poster.jpg" />);
    const video = container.querySelector('video');
    expect(video).toBeTruthy();
    expect(video?.getAttribute('poster')).toBe('poster.jpg');
  });

  it('renders play/pause button with correct aria-label', () => {
    render(<VideoPlayer src="test.mp4" />);
    const playButton = screen.getByRole('button', { name: /Reproduzir/i });
    expect(playButton).toBeInTheDocument();
  });

  it('renders volume button', () => {
    render(<VideoPlayer src="test.mp4" />);
    const volumeButton = screen.getByRole('button', { name: /som/i });
    expect(volumeButton).toBeInTheDocument();
  });

  it('renders with default title when none is provided', () => {
    const { container } = render(<VideoPlayer src="test.mp4" />);
    const video = container.querySelector('video');
    expect(video?.getAttribute('title')).toBe('Vídeo');
  });

  it('does not autoPlay by default', () => {
    const { container } = render(<VideoPlayer src="test.mp4" />);
    const video = container.querySelector('video');
    expect(video?.autoplay).toBe(false);
  });

  it('applies custom className', () => {
    const { container } = render(<VideoPlayer src="test.mp4" className="custom-class" />);
    expect(container.firstChild).toHaveClass('custom-class');
  });
});
