import { afterEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/svelte';
import type { TrackRef } from '$lib/api/types';
import { emptyLikesMock } from '../../test-utils/mocks/likes';
import { emptyPlaylistsMock } from '../../test-utils/mocks/playlists';
import { emptyQuarantineMock } from '../../test-utils/mocks/quarantine';
import { makeTracks } from '$test-utils/fixtures/track';

vi.mock('$lib/api/likes', () => emptyLikesMock());

vi.mock('$lib/api/quarantine', () => emptyQuarantineMock());

vi.mock('$lib/api/playlists', () => emptyPlaylistsMock());

vi.mock('$lib/auth/store.svelte', () => ({
  user: { get value() { return { id: 'u1', username: 'u', is_admin: false }; } }
}));

vi.mock('$app/navigation', () => ({ goto: vi.fn() }));

vi.mock('$lib/player/store.svelte', () => ({
  playQueue: vi.fn(),
  enqueueTrack: vi.fn(),
  playNext: vi.fn()
}));

import CompactTrackCard from './CompactTrackCard.svelte';
import { playQueue, enqueueTrack } from '$lib/player/store.svelte';

const titles = ['First', 'Second', 'Third'];
const tracks: TrackRef[] = makeTracks(3, { artist_name: 'Artist' }).map((t, i) => ({
  ...t,
  title: titles[i]
}));

afterEach(() => vi.clearAllMocks());

describe('CompactTrackCard', () => {
  test('clicking the card calls playQueue with sectionTracks at the right index', async () => {
    render(CompactTrackCard, {
      props: { track: tracks[1], sectionTracks: tracks, index: 1 }
    });
    await fireEvent.click(screen.getByRole('button', { name: /play second/i }));
    expect(playQueue).toHaveBeenCalledWith(tracks, 1);
  });

  test('renders title and artist name', () => {
    render(CompactTrackCard, {
      props: { track: tracks[0], sectionTracks: tracks, index: 0 }
    });
    expect(screen.getByText('First')).toBeInTheDocument();
    expect(screen.getByText('Artist')).toBeInTheDocument();
  });

  test('+ queue button calls enqueueTrack', async () => {
    render(CompactTrackCard, {
      props: { track: tracks[0], sectionTracks: tracks, index: 0 }
    });
    await fireEvent.click(screen.getByRole('button', { name: /add first to queue/i }));
    expect(enqueueTrack).toHaveBeenCalledWith(tracks[0]);
  });
});
