import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
import { mockQuery } from '../../test-utils/query';
import { apiClientMock } from '../../test-utils/mocks/client';
import type { LidarrSearchResult } from '$lib/api/types';
import { pageUrlModule } from '../../test-utils/mocks/appState';

// $app/state / $app/navigation must be mocked or rendering the page
// pulls in SvelteKit's client runtime (`notifiable_store is not a
// function`) at module load. Same pattern as the other route tests.
const pageState = vi.hoisted(() => ({
  pageUrl: new URL('http://localhost/discover')
}));
vi.mock('$app/state', () => pageUrlModule(pageState));
vi.mock('$app/navigation', () => ({ goto: vi.fn() }));

// Lidarr search query factory and createRequest are mocked at the module
// level so each test can shape what the page sees without standing up a
// real QueryClient + network.
vi.mock('$lib/api/lidarr', () => ({
  createLidarrSearchQuery: vi.fn()
}));

// SuggestionFeed reaches for the snooze surface too (#2375). These are
// stubbed here even though this page-level suite asserts nothing about
// snoozing: a factory-shaped module mock must export everything the
// component tree imports, or rendering the feed throws before any
// assertion runs.
vi.mock('$lib/api/suggestions', () => ({
  createSuggestionsQuery: vi.fn(),
  createSnoozesQuery: vi.fn(),
  snoozeSuggestion: vi.fn().mockResolvedValue(undefined),
  unsnoozeSuggestion: vi.fn().mockResolvedValue(undefined)
}));

vi.mock('$lib/api/requests', () => ({
  createRequest: vi.fn().mockResolvedValue({ id: 'r1' })
}));

vi.mock('$lib/api/client', () => apiClientMock());

// The page calls useQueryClient() to invalidate qk.myRequests() after a
// submit (#369); stub it so rendering doesn't require a real QueryClient and
// we can assert the invalidation fires.
const queryClientMock = vi.hoisted(() => ({ invalidateQueries: vi.fn() }));
vi.mock('@tanstack/svelte-query', async (importOriginal) => {
  const actual = await importOriginal<typeof import('@tanstack/svelte-query')>();
  return { ...actual, useQueryClient: () => queryClientMock };
});

import DiscoverPage from './+page.svelte';
import { createLidarrSearchQuery } from '$lib/api/lidarr';
import { createSuggestionsQuery, createSnoozesQuery } from '$lib/api/suggestions';
import { createRequest } from '$lib/api/requests';

const mockedCreateQuery = createLidarrSearchQuery as ReturnType<typeof vi.fn>;
const mockedCreateSuggestionsQuery = createSuggestionsQuery as ReturnType<typeof vi.fn>;
const mockedCreateSnoozesQuery = createSnoozesQuery as ReturnType<typeof vi.fn>;
const mockedCreateRequest = createRequest as ReturnType<typeof vi.fn>;

function result(over: Partial<LidarrSearchResult> = {}): LidarrSearchResult {
  return {
    mbid: 'mbid-1',
    name: 'Boards of Canada',
    secondary_text: 'Electronic',
    image_url: '',
    artist_mbid: 'art-1',
    album_mbid: '',
    in_library: false,
    requested: false,
    ...over
  };
}

beforeEach(() => {
  // Default: empty results, non-pending. Tests override per-case.
  mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [] }));
  // Default: empty suggestion feed so its empty-state copy renders without
  // interfering with search-mode tests.
  mockedCreateSuggestionsQuery.mockReturnValue(mockQuery({ data: [] }));
  // Nothing parked, which keeps the feed's empty-state copy on the
  // "no signal yet" branch that this suite's assertions expect.
  mockedCreateSnoozesQuery.mockReturnValue(mockQuery({ data: [] }));
});

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

describe('Discover page', () => {
  test('initial state (no query) shows the suggestion feed', () => {
    render(DiscoverPage);
    expect(screen.getByText(/suggested for you/i)).toBeInTheDocument();
  });

  test('empty input shows the suggestion feed', () => {
    render(DiscoverPage);
    expect(screen.getByText(/suggested for you/i)).toBeInTheDocument();
    // Kind tabs should NOT be visible when input is empty.
    expect(
      screen.queryByRole('button', { name: 'Artists' })
    ).not.toBeInTheDocument();
  });

  test('typing replaces feed with search', async () => {
    vi.useFakeTimers();
    render(DiscoverPage);
    const input = screen.getByLabelText(/search lidarr/i);
    await fireEvent.input(input, { target: { value: 'miles' } });
    await vi.advanceTimersByTimeAsync(250);
    expect(screen.queryByText(/suggested for you/i)).not.toBeInTheDocument();
    expect(screen.getByText(/add music to the library/i)).toBeInTheDocument();
    // Kind tabs visible when searching.
    expect(screen.getByRole('button', { name: 'Artists' })).toBeInTheDocument();
    vi.useRealTimers();
  });

  test('debounced input fires query factory with typed value after 250ms', async () => {
    vi.useFakeTimers();
    render(DiscoverPage);
    const input = screen.getByLabelText(/search lidarr/i);
    await fireEvent.input(input, { target: { value: 'boards' } });
    // Before the timer elapses, the factory was called only with the
    // initial empty string — never with 'boards'.
    expect(mockedCreateQuery).not.toHaveBeenCalledWith('boards', 'artist');
    await vi.advanceTimersByTimeAsync(250);
    expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'artist');
    vi.useRealTimers();
  });

  test('switching tabs refetches with the new kind', async () => {
    vi.useFakeTimers();
    render(DiscoverPage);
    const input = screen.getByLabelText(/search lidarr/i);
    await fireEvent.input(input, { target: { value: 'boards' } });
    await vi.advanceTimersByTimeAsync(250);
    // Switch to Albums.
    await fireEvent.click(screen.getByRole('button', { name: 'Albums' }));
    expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'album');
    // Then to Tracks.
    await fireEvent.click(screen.getByRole('button', { name: 'Tracks' }));
    expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'track');
    vi.useRealTimers();
  });

  test('empty results state renders the voice-rule copy', async () => {
    vi.useFakeTimers();
    mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [] }));
    render(DiscoverPage);
    const input = screen.getByLabelText(/search lidarr/i);
    await fireEvent.input(input, { target: { value: 'zzz' } });
    await vi.advanceTimersByTimeAsync(250);
    await waitFor(() =>
      expect(
        screen.getByText(/nothing to add for that search yet\./i)
      ).toBeInTheDocument()
    );
    vi.useRealTimers();
  });

  test('artist-kind Request click calls createRequest immediately (no modal)', async () => {
    vi.useFakeTimers();
    const r = result({
      mbid: 'art-mbid',
      artist_mbid: 'art-mbid',
      name: 'Boards of Canada'
    });
    mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [r] }));
    render(DiscoverPage);
    const input = screen.getByLabelText(/search lidarr/i);
    await fireEvent.input(input, { target: { value: 'boards' } });
    await vi.advanceTimersByTimeAsync(250);
    vi.useRealTimers();

    const requestBtn = await screen.findByRole('button', {
      name: /request boards of canada/i
    });
    await fireEvent.click(requestBtn);
    expect(mockedCreateRequest).toHaveBeenCalledTimes(1);
    expect(mockedCreateRequest).toHaveBeenCalledWith(
      expect.objectContaining({ kind: 'artist' })
    );
    // Modal must not be present for non-track kinds.
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
  });

  test('requestable card flips to "Requested" after a successful request', async () => {
    vi.useFakeTimers();
    const r = result({
      mbid: 'art-mbid',
      artist_mbid: 'art-mbid',
      name: 'Boards of Canada'
    });
    mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [r] }));
    render(DiscoverPage);
    const input = screen.getByLabelText(/search lidarr/i);
    await fireEvent.input(input, { target: { value: 'boards' } });
    await vi.advanceTimersByTimeAsync(250);
    vi.useRealTimers();

    const requestBtn = await screen.findByRole('button', {
      name: /request boards of canada/i
    });
    await fireEvent.click(requestBtn);
    await waitFor(() => {
      const flipped = screen.getByRole('button', { name: /already requested/i });
      expect(flipped).toBeDisabled();
    });
  });

  test('submitting a request invalidates myRequests so /requests updates (#369)', async () => {
    vi.useFakeTimers();
    const r = result({ mbid: 'art-mbid', artist_mbid: 'art-mbid', name: 'Boards of Canada' });
    mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [r] }));
    render(DiscoverPage);
    const input = screen.getByLabelText(/search lidarr/i);
    await fireEvent.input(input, { target: { value: 'boards' } });
    await vi.advanceTimersByTimeAsync(250);
    vi.useRealTimers();

    const requestBtn = await screen.findByRole('button', {
      name: /request boards of canada/i
    });
    await fireEvent.click(requestBtn);
    await waitFor(() => {
      expect(queryClientMock.invalidateQueries).toHaveBeenCalledWith({
        queryKey: ['myRequests']
      });
    });
  });

  test('track-kind Request click opens confirm modal; Confirm calls createRequest', async () => {
    vi.useFakeTimers();
    const r = result({
      mbid: 'tr-mbid',
      artist_mbid: 'art-mbid',
      album_mbid: 'al-mbid',
      name: 'Roygbiv',
      secondary_text: 'Music Has The Right To Children · Boards of Canada'
    });
    mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [r] }));
    render(DiscoverPage);
    // Type first so the kind tabs become visible (empty-input mode shows the
    // suggestion feed and hides tabs).
    const input = screen.getByLabelText(/search lidarr/i);
    await fireEvent.input(input, { target: { value: 'roy' } });
    await vi.advanceTimersByTimeAsync(250);
    // Switch to track kind.
    await fireEvent.click(screen.getByRole('button', { name: 'Tracks' }));
    vi.useRealTimers();

    const requestBtn = await screen.findByRole('button', {
      name: /request roygbiv/i
    });
    await fireEvent.click(requestBtn);
    // Modal opens with the explanation copy.
    const dialog = await screen.findByRole('dialog');
    expect(dialog).toBeInTheDocument();
    expect(dialog.textContent).toMatch(/continue/i);
    // Confirm fires createRequest with kind=track.
    await fireEvent.click(screen.getByRole('button', { name: /add the album/i }));
    expect(mockedCreateRequest).toHaveBeenCalledTimes(1);
    expect(mockedCreateRequest).toHaveBeenCalledWith(
      expect.objectContaining({
        kind: 'track',
        lidarr_track_mbid: 'tr-mbid',
        lidarr_album_mbid: 'al-mbid',
        lidarr_artist_mbid: 'art-mbid'
      })
    );
  });

  test('track-kind modal Cancel does not call createRequest', async () => {
    vi.useFakeTimers();
    const r = result({
      mbid: 'tr-mbid',
      artist_mbid: 'art-mbid',
      album_mbid: 'al-mbid',
      name: 'Roygbiv',
      secondary_text: 'Music Has The Right To Children · Boards of Canada'
    });
    mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [r] }));
    render(DiscoverPage);
    const input = screen.getByLabelText(/search lidarr/i);
    await fireEvent.input(input, { target: { value: 'roy' } });
    await vi.advanceTimersByTimeAsync(250);
    await fireEvent.click(screen.getByRole('button', { name: 'Tracks' }));
    vi.useRealTimers();

    const requestBtn = await screen.findByRole('button', {
      name: /request roygbiv/i
    });
    await fireEvent.click(requestBtn);
    await screen.findByRole('dialog');
    await fireEvent.click(screen.getByRole('button', { name: /^cancel$/i }));
    expect(mockedCreateRequest).not.toHaveBeenCalled();
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
  });

  test('in_library result renders kept state regardless of requested', async () => {
    vi.useFakeTimers();
    const r = result({
      mbid: 'kept-1',
      name: 'Kind of Blue',
      in_library: true,
      requested: true
    });
    mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [r] }));
    render(DiscoverPage);
    const input = screen.getByLabelText(/search lidarr/i);
    await fireEvent.input(input, { target: { value: 'kind' } });
    await vi.advanceTimersByTimeAsync(250);
    vi.useRealTimers();

    await waitFor(() => {
      expect(screen.getByRole('button', { name: /in library/i })).toBeDisabled();
    });
  });
});
