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 { AlbumRef, Page } from '$lib/api/types';

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

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

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

vi.mock('$lib/api/client', () => ({
  api: { get: vi.fn() }
}));
vi.mock('$lib/player/store.svelte', () => ({
  enqueueTracks: 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 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', artist_id: 'a1', artist_name: 'Miles Davis',
  year: 1959, track_count: 5, duration_sec: 2630, cover_url: '/api/albums/al1/cover'
};

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