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

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

vi.mock('$app/state', () => ({
  page: { get url() { return state.pageUrl; } }
}));

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

vi.mock('$lib/player/store.svelte', () => ({
  playQueue: vi.fn(),
  playRadio: 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: () => ({}) };
});

vi.mock('$lib/api/quarantine', () => ({
  flagTrack: vi.fn(),
  unflagTrack: vi.fn(),
  listMyQuarantine: vi.fn().mockResolvedValue([]),
  createMyQuarantineQuery: vi.fn()
}));

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: TrackRef = {
  id: 't1', title: 'So What',
  album_id: 'al1', album_title: 'Kind of Blue',
  artist_id: 'a1', artist_name: 'Miles Davis',
  track_number: 1, disc_number: 1, duration_sec: 545,
  stream_url: '/api/tracks/t1/stream'
};

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();
  });
});
