import { create } from 'zustand'
import { persist } from 'zustand/middleware'

export type DownloadStatus = 'queued' | 'downloading' | 'done' | 'error'

export interface DownloadItem {
  id: string
  itemId: string
  name: string
  posterUrl?: string | null
  streamUrl: string
  subtitleUrl?: string | null
  status: DownloadStatus
  progress: number
  sizeBytes?: number
  localPath?: string
  error?: string
  createdAt: string
}

interface State {
  items: DownloadItem[]
  add: (item: Omit<DownloadItem, 'id' | 'status' | 'progress' | 'createdAt'>) => DownloadItem
  update: (id: string, patch: Partial<DownloadItem>) => void
  remove: (id: string) => void
  clearCompleted: () => void
  getByItemId: (itemId: string) => DownloadItem | undefined
}

function uid() {
  return 'dl_' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36)
}

export const useDownloads = create<State>()(
  persist(
    (set, get) => ({
      items: [],
      add: item => {
        const existing = get().items.find(i => i.itemId === item.itemId && i.status !== 'error')
        if (existing) return existing
        const next: DownloadItem = {
          ...item,
          id: uid(),
          status: 'queued',
          progress: 0,
          createdAt: new Date().toISOString(),
        }
        set(s => ({ items: [...s.items, next] }))
        return next
      },
      update: (id, patch) =>
        set(s => ({
          items: s.items.map(i => (i.id === id ? { ...i, ...patch } : i)),
        })),
      remove: id =>
        set(s => ({
          items: s.items.filter(i => i.id !== id),
        })),
      clearCompleted: () =>
        set(s => ({
          items: s.items.filter(i => i.status !== 'done'),
        })),
      getByItemId: itemId => get().items.find(i => i.itemId === itemId),
    }),
    { name: 'downloads-v1' },
  ),
)
