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

const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/search/tracks?q=miles') }));

vi.mock('$app/state', () => pageUrlModule(state));

vi.mock('$lib/api/queries', () => ({
  createSearchTracksInfiniteQuery: vi.fn()
}));

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

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

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

import TracksOverflow from './+page.svelte';
import { createSearchTracksInfiniteQuery } from '$lib/api/queries';
import { playRadio } from '$lib/player/store.svelte';

function page<T>(items: T[], total: number, offset = 0, limit = 50): Page<T> {
  return { items, total, offset, limit };
}

const track = makeTrack({ title: 'So What' });

afterEach(() => {
  vi.clearAllMocks();
  state.pageUrl = new URL('http://localhost/search/tracks?q=miles');
});

describe('search tracks overflow', () => {
  test('renders a TrackRow per track', () => {
    (createSearchTracksInfiniteQuery as ReturnType<typeof vi.fn>).mockReturnValue(
      mockInfiniteQuery({ pages: [page([track], 1)] })
    );
    render(TracksOverflow);
    expect(screen.getByRole('button', { name: 'So What' })).toBeInTheDocument();
  });

  test('clicking a track row triggers playRadio with the track id', async () => {
    (createSearchTracksInfiniteQuery as ReturnType<typeof vi.fn>).mockReturnValue(
      mockInfiniteQuery({ pages: [page([track], 1)] })
    );
    render(TracksOverflow);
    await fireEvent.click(screen.getByRole('button', { name: 'So What' }));
    expect(playRadio).toHaveBeenCalledWith('t1');
  });

  test('Load more calls fetchNextPage', async () => {
    const fetchNextPage = vi.fn();
    (createSearchTracksInfiniteQuery as ReturnType<typeof vi.fn>).mockReturnValue(
      mockInfiniteQuery({
        pages: [page<TrackRef>([], 100)],
        hasNextPage: true,
        fetchNextPage
      })
    );
    render(TracksOverflow);
    await fireEvent.click(screen.getByRole('button', { name: /load more/i }));
    expect(fetchNextPage).toHaveBeenCalledTimes(1);
  });

  test('empty q shows a prompt', () => {
    state.pageUrl = new URL('http://localhost/search/tracks');
    render(TracksOverflow);
    expect(screen.getByText(/no query/i)).toBeInTheDocument();
  });
});
