import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { MediaPosterCard } from './MediaPosterCard';
import type { LibraryBrowseItem } from '../api';

const movieItem = { artwork: '', id: 12, mediaType: 'Movie', title: 'Blade Runner' } as unknown as LibraryBrowseItem;

describe('MediaPosterCard', () => {
  afterEach(() => {
    cleanup();
  });

  it('renders the item title', () => {
    render(<MediaPosterCard item={movieItem} />);
    expect(screen.getByText('Blade Runner')).toBeTruthy();
  });

  it('calls onOpen when the card is clicked', () => {
    const onOpen = vi.fn();
    render(<MediaPosterCard item={movieItem} onOpen={onOpen} />);
    fireEvent.click(screen.getByRole('button'));
    expect(onOpen).toHaveBeenCalledWith(movieItem);
  });

  it('does not trigger open/select when the actions slot is clicked', () => {
    const onOpen = vi.fn();
    const onAction = vi.fn();
    render(
      <MediaPosterCard
        actions={
          <button onClick={onAction} type="button">
            Act
          </button>
        }
        item={movieItem}
        onOpen={onOpen}
      />
    );

    fireEvent.click(screen.getByRole('button', { name: 'Act' }));
    expect(onAction).toHaveBeenCalledTimes(1);
    expect(onOpen).not.toHaveBeenCalled();
  });

  it('still toggles selection from the card body while the actions slot stays isolated', () => {
    const onToggleSelect = vi.fn();
    const onAction = vi.fn();
    render(
      <MediaPosterCard
        actions={
          <button onClick={onAction} type="button">
            Act
          </button>
        }
        item={movieItem}
        onToggleSelect={onToggleSelect}
      />
    );

    fireEvent.click(screen.getByText('Blade Runner'));
    expect(onToggleSelect).toHaveBeenCalledWith(movieItem);

    fireEvent.click(screen.getByRole('button', { name: 'Act' }));
    expect(onToggleSelect).toHaveBeenCalledTimes(1);
  });
});
