import { describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
import { mockQuery } from '../../../test-utils/query';
import { emptyQuarantineMock } from '../../../test-utils/mocks/quarantine';
import type { PlaylistDetail } from '$lib/api/types';

// Project canonical: $app/state (rune-state), not $app/stores (legacy
// reactive store). The page module exports an object with a `params`
// getter rather than a Svelte store.
vi.mock('$app/state', () => ({
  page: { params: { id: 'p1' } }
}));

vi.mock('$app/navigation', () => ({ goto: vi.fn() }));

vi.mock('$lib/api/playlists', () => ({
  createPlaylistQuery: vi.fn(),
  updatePlaylist: vi.fn().mockResolvedValue(undefined),
  deletePlaylist: vi.fn().mockResolvedValue(undefined),
  removePlaylistTrack: vi.fn().mockResolvedValue(undefined),
  reorderPlaylist: vi.fn().mockResolvedValue(undefined),
  refreshSystem: vi.fn().mockResolvedValue({ playlist_id: 'p1', track_count: 5, track_ids: [] })
}));

vi.mock('$lib/auth/store.svelte', () => ({
  user: { value: { id: 'u-self', username: 'me', is_admin: false } }
}));

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

// Cascade through PlaylistTrackRow's mocks (LikeButton + TrackMenu transitively).
vi.mock('$lib/api/likes', () => ({
  createLikedIdsQuery: () => ({ subscribe: () => () => {}, data: { track_ids: [], album_ids: [], artist_ids: [] } }),
  likeEntity: vi.fn(),
  unlikeEntity: vi.fn()
}));
vi.mock('$lib/api/quarantine', () => emptyQuarantineMock());

import PlaylistDetailPage from './+page.svelte';
import { createPlaylistQuery, deletePlaylist, refreshSystem } from '$lib/api/playlists';

const mockedQuery = createPlaylistQuery as ReturnType<typeof vi.fn>;

const ownDetail: PlaylistDetail = {
  id: 'p1', user_id: 'u-self', owner_username: 'me', name: 'Mine',
  description: '', is_public: false, kind: 'user', system_variant: null, refreshable: false, seed_artist_id: null, cover_url: '', track_count: 2, duration_sec: 274,
  created_at: '', updated_at: '',
  tracks: [
    { position: 0, track_id: 't1', album_id: 'a1', artist_id: 'ar1', title: 'A', artist_name: 'X', album_title: 'Y', duration_sec: 137, stream_url: '/api/tracks/t1/stream', added_at: '' },
    { position: 1, track_id: 't2', album_id: 'a1', artist_id: 'ar1', title: 'B', artist_name: 'X', album_title: 'Y', duration_sec: 137, stream_url: '/api/tracks/t2/stream', added_at: '' }
  ]
};

describe('Playlist detail page', () => {
  test('renders header + tracks for owner', () => {
    mockedQuery.mockReturnValue(mockQuery({ data: ownDetail }));
    render(PlaylistDetailPage);
    expect(screen.getByText('Mine')).toBeInTheDocument();
    expect(screen.getByText('A')).toBeInTheDocument();
    expect(screen.getByText('B')).toBeInTheDocument();
    expect(screen.getByLabelText(/edit playlist/i)).toBeInTheDocument();
    expect(screen.getByLabelText(/delete playlist/i)).toBeInTheDocument();
  });

  test('hides edit + delete for non-owner', () => {
    mockedQuery.mockReturnValue(mockQuery({
      data: { ...ownDetail, user_id: 'u-other', owner_username: 'bob', is_public: true }
    }));
    render(PlaylistDetailPage);
    expect(screen.queryByLabelText(/edit playlist/i)).not.toBeInTheDocument();
    expect(screen.queryByLabelText(/delete playlist/i)).not.toBeInTheDocument();
  });

  test('Copy-link button appears only when owner AND playlist is public', async () => {
    // Owner + private → no button
    mockedQuery.mockReturnValue(mockQuery({ data: ownDetail }));
    const { unmount } = render(PlaylistDetailPage);
    expect(screen.queryByLabelText(/copy public link/i)).not.toBeInTheDocument();
    unmount();

    // Owner + public → button appears
    mockedQuery.mockReturnValue(mockQuery({ data: { ...ownDetail, is_public: true } }));
    render(PlaylistDetailPage);
    expect(screen.getByLabelText(/copy public link/i)).toBeInTheDocument();
  });

  test('Copy-link writes the absolute /playlists/[id] URL to clipboard', async () => {
    mockedQuery.mockReturnValue(mockQuery({ data: { ...ownDetail, is_public: true } }));
    const writeText = vi.fn().mockResolvedValue(undefined);
    Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
    render(PlaylistDetailPage);
    await fireEvent.click(screen.getByLabelText(/copy public link/i));
    // jsdom's window.location.origin is "http://localhost" by default.
    // Match by suffix to stay resilient to vitest config changes.
    await waitFor(() =>
      expect(writeText).toHaveBeenCalledWith(expect.stringMatching(/\/playlists\/p1$/))
    );
  });

  test('Delete button confirms then deletes', async () => {
    mockedQuery.mockReturnValue(mockQuery({ data: ownDetail }));
    const confirmSpy = vi.spyOn(globalThis, 'confirm').mockReturnValue(true);
    render(PlaylistDetailPage);
    await fireEvent.click(screen.getByLabelText(/delete playlist/i));
    await waitFor(() => expect(deletePlaylist).toHaveBeenCalledWith('p1'));
    confirmSpy.mockRestore();
  });

  test('renders Refresh button on a refreshable system playlist', () => {
    const discoverDetail: PlaylistDetail = {
      ...ownDetail,
      kind: 'system',
      system_variant: 'discover',
      refreshable: true
    };
    mockedQuery.mockReturnValue(mockQuery({ data: discoverDetail }));
    render(PlaylistDetailPage);
    expect(screen.getByLabelText(/refresh playlist/i)).toBeInTheDocument();
  });

  test('renders Refresh button on For You too (also refreshable now)', () => {
    const forYouDetail: PlaylistDetail = {
      ...ownDetail,
      kind: 'system',
      system_variant: 'for_you',
      refreshable: true
    };
    mockedQuery.mockReturnValue(mockQuery({ data: forYouDetail }));
    render(PlaylistDetailPage);
    expect(screen.getByLabelText(/refresh playlist/i)).toBeInTheDocument();
  });

  test('does not render Refresh on a non-refreshable system playlist', () => {
    const songsLike: PlaylistDetail = {
      ...ownDetail,
      kind: 'system',
      system_variant: 'songs_like_artist',
      refreshable: false
    };
    mockedQuery.mockReturnValue(mockQuery({ data: songsLike }));
    render(PlaylistDetailPage);
    expect(screen.queryByLabelText(/refresh playlist/i)).not.toBeInTheDocument();
  });

  test('does not render Refresh button on user playlists', () => {
    mockedQuery.mockReturnValue(mockQuery({ data: ownDetail }));
    render(PlaylistDetailPage);
    expect(screen.queryByLabelText(/refresh playlist/i)).not.toBeInTheDocument();
  });

  test('Refresh button calls refreshSystem with the variant', async () => {
    const discoverDetail: PlaylistDetail = {
      ...ownDetail,
      kind: 'system',
      system_variant: 'discover',
      refreshable: true
    };
    mockedQuery.mockReturnValue(mockQuery({ data: discoverDetail }));
    render(PlaylistDetailPage);
    await fireEvent.click(screen.getByLabelText(/refresh playlist/i));
    await waitFor(() => expect(refreshSystem).toHaveBeenCalledWith('discover'));
  });
});
