import { afterEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/svelte';
import type { TrackRef } from '$lib/api/types';
import { readable } from 'svelte/store';

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

vi.mock('$lib/api/likes', () => ({
  createLikedIdsQuery: () => readable({
    data: { track_ids: [], album_ids: [], artist_ids: [] },
    isPending: false,
    isError: false
  }),
  likeEntity: vi.fn(),
  unlikeEntity: vi.fn()
}));

vi.mock('@tanstack/svelte-query', async (orig) => {
  const actual = (await orig()) as Record<string, unknown>;
  return { ...actual, useQueryClient: () => ({}) };
});

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

const tracks: TrackRef[] = [
  {
    id: 't1', title: 'So What',
    album_id: 'xyz', album_title: 'Kind of Blue',
    artist_id: 'm-davis', artist_name: 'Miles Davis',
    track_number: 1, disc_number: 1,
    duration_sec: 545, stream_url: '/api/tracks/t1/stream'
  },
  {
    id: 't2', title: 'Freddie Freeloader',
    album_id: 'xyz', album_title: 'Kind of Blue',
    artist_id: 'm-davis', artist_name: 'Miles Davis',
    track_number: 2, disc_number: 1,
    duration_sec: 565, stream_url: '/api/tracks/t2/stream'
  }
];

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

describe('TrackRow', () => {
  test('renders track number, title, formatted duration', () => {
    render(TrackRow, { props: { tracks, index: 0 } });
    expect(screen.getByText('1')).toBeInTheDocument();
    expect(screen.getByText('So What')).toBeInTheDocument();
    expect(screen.getByText('9:05')).toBeInTheDocument();
  });

  test('track number falls back to dash when missing', () => {
    const noNum = [{ ...tracks[0], track_number: undefined }];
    render(TrackRow, { props: { tracks: noNum, index: 0 } });
    expect(screen.getByText('—')).toBeInTheDocument();
  });

  test('clicking the row calls playQueue(tracks, index)', async () => {
    render(TrackRow, { props: { tracks, index: 1 } });
    await fireEvent.click(screen.getByRole('button', { name: /Freddie Freeloader/ }));
    expect(playQueue).toHaveBeenCalledWith(tracks, 1);
  });

  test('Enter on the row activates play', async () => {
    render(TrackRow, { props: { tracks, index: 0 } });
    await fireEvent.keyDown(screen.getByRole('button', { name: /So What/ }), { key: 'Enter' });
    expect(playQueue).toHaveBeenCalledWith(tracks, 0);
  });

  test('Space on the row activates play', async () => {
    render(TrackRow, { props: { tracks, index: 0 } });
    await fireEvent.keyDown(screen.getByRole('button', { name: /So What/ }), { key: ' ' });
    expect(playQueue).toHaveBeenCalledWith(tracks, 0);
  });

  test('onPlay prop overrides default playQueue', async () => {
    const onPlay = vi.fn();
    render(TrackRow, { props: { tracks, index: 1, onPlay } });
    await fireEvent.click(screen.getByRole('button', { name: /Freddie Freeloader/ }));
    expect(onPlay).toHaveBeenCalledWith(tracks, 1);
    expect(playQueue).not.toHaveBeenCalled();
  });

  test('+ queue button calls enqueueTrack and does NOT trigger row play', async () => {
    render(TrackRow, { props: { tracks, index: 0 } });
    await fireEvent.click(screen.getByRole('button', { name: /add to queue/i }));
    expect(enqueueTrack).toHaveBeenCalledWith(tracks[0]);
    expect(playQueue).not.toHaveBeenCalled();
  });
});
