// Playlist 不可变操作。所有函数纯，返回新数组。

export interface Song {
  id: number
  singer: string
  title: string
}

export type Direction = 'up' | 'down' | 'first'

export function nextId(playlist: Song[]): number {
  let max = 0
  for (const s of playlist) if (s.id > max) max = s.id
  return max + 1
}

export function addSong(playlist: Song[], singer: string, title: string): Song[] {
  const s = singer.trim()
  const t = title.trim()
  if (!s || !t) return playlist
  return [...playlist, { id: nextId(playlist), singer: s, title: t }]
}

export function deleteSong(playlist: Song[], songId: number): Song[] {
  return playlist.filter((s) => s.id !== songId)
}

export function moveSong(playlist: Song[], songId: number, direction: Direction): Song[] {
  const idx = playlist.findIndex((s) => s.id === songId)
  if (idx === -1) return playlist
  const next = [...playlist]
  const [song] = next.splice(idx, 1)
  if (direction === 'first') {
    next.unshift(song)
  } else if (direction === 'up') {
    next.splice(Math.max(0, idx - 1), 0, song)
  } else {
    // 'down': insert at idx + 1 of original. After splice, original idx + 1
    // becomes position idx in `next`. So inserting at idx puts the song before
    // the element that *was* at idx + 1 — we want *after* it, hence idx + 1.
    next.splice(Math.min(next.length, idx + 1), 0, song)
  }
  return next
}

export function youtubeSearchUrl(song: Song): string {
  const q = encodeURIComponent(`${song.singer} ${song.title}`)
  return `https://www.youtube.com/results?search_query=${q}`
}
