import { create } from 'zustand'
import type { BaseItemDto } from '../api/types'

/**
 * Active playback queue. PlaylistView populates it when the user hits Play
 * or Shuffle; PlayerPage reads it to drive the prev / next chrome buttons
 * and to auto-advance on `ended`. Lives in memory only - we don't persist
 * the queue across reloads.
 *
 * `items` is already in play-order (shuffled if applicable). `originalOrder`
 * holds the un-shuffled list so toggling shuffle off mid-queue can restore
 * the natural sequence without re-fetching.
 */

export interface QueueSource {
  type: 'playlist'
  id: string
}

export interface QueueState {
  items: BaseItemDto[]
  originalOrder: BaseItemDto[]
  index: number
  shuffled: boolean
  source: QueueSource | null

  setQueue(args: {
    items: BaseItemDto[]
    index: number
    source: QueueSource | null
    shuffled: boolean
    originalOrder?: BaseItemDto[]
  }): void
  setIndex(index: number): void
  clear(): void
}

export const useQueueStore = create<QueueState>(set => ({
  items: [],
  originalOrder: [],
  index: 0,
  shuffled: false,
  source: null,

  setQueue: ({ items, index, source, shuffled, originalOrder }) =>
    set({
      items,
      originalOrder: originalOrder ?? items,
      index,
      shuffled,
      source,
    }),
  setIndex: index => set({ index }),
  clear: () => set({ items: [], originalOrder: [], index: 0, shuffled: false, source: null }),
}))
