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 { apiClientMock } from '../../../test-utils/mocks/client';
import { pageUrlModule } from '$test-utils/mocks/appState';
import type { AlbumRef, Page } from '$lib/api/types';

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

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

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

vi.mock('$lib/api/client', () => apiClientMock());
vi.mock('$lib/player/store.svelte', () => ({
  enqueueTracks: vi.fn()
}));

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

import AlbumsOverflow from './+page.svelte';
import { createSearchAlbumsInfiniteQuery } from '$lib/api/queries';

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

const album: AlbumRef = {
  id: 'al1', title: 'Kind of Blue', sort_title: 'Kind of Blue', artist_id: 'a1', artist_name: 'Miles Davis',
  year: 1959, track_count: 5, duration_sec: 2630, cover_url: '/api/albums/al1/cover', cover_art_source: null
};

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

describe('search albums overflow', () => {
  test('renders an AlbumCard per album', () => {
    (createSearchAlbumsInfiniteQuery as ReturnType<typeof vi.fn>).mockReturnValue(
      mockInfiniteQuery({ pages: [page([album], 1)] })
    );
    render(AlbumsOverflow);
    expect(screen.getByRole('link', { name: /Kind of Blue/ })).toHaveAttribute('href', '/albums/al1');
  });

  test('Load more calls fetchNextPage', async () => {
    const fetchNextPage = vi.fn();
    (createSearchAlbumsInfiniteQuery as ReturnType<typeof vi.fn>).mockReturnValue(
      mockInfiniteQuery({
        pages: [page<AlbumRef>([], 100)],
        hasNextPage: true,
        fetchNextPage
      })
    );
    render(AlbumsOverflow);
    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/albums');
    render(AlbumsOverflow);
    expect(screen.getByText(/no query/i)).toBeInTheDocument();
  });
});
