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

export interface SmartShelfRule {
  /** Stable id - uuid-ish, generated client-side. */
  id: string
  name: string
  /** "Movie" / "Series" / both ('any'). Mapped to includeItemTypes. */
  type: 'movie' | 'series' | 'any'
  genres: string[]
  /** Inclusive year range [min, max]. Either bound optional. */
  yearMin?: number
  yearMax?: number
  /** Watched / unwatched / either. */
  watched: 'any' | 'played' | 'unplayed'
  /** Minimum community rating (TMDB / Jellyfin). */
  minRating?: number
  sortBy: 'random' | 'recent' | 'rating' | 'name'
  /** Up to 100; we cap on the API side too. */
  limit: number
  createdAt: string
}

interface SmartShelvesState {
  shelves: SmartShelfRule[]
  add: (shelf: Omit<SmartShelfRule, 'id' | 'createdAt'>) => SmartShelfRule
  update: (id: string, patch: Partial<SmartShelfRule>) => void
  remove: (id: string) => void
}

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

export const useSmartShelves = create<SmartShelvesState>()(
  persist(
    set => ({
      shelves: [],
      add: shelf => {
        const next: SmartShelfRule = { ...shelf, id: uid(), createdAt: new Date().toISOString() }
        set(s => ({ shelves: [...s.shelves, next] }))
        return next
      },
      update: (id, patch) =>
        set(s => ({
          shelves: s.shelves.map(x => (x.id === id ? { ...x, ...patch } : x)),
        })),
      remove: id =>
        set(s => ({
          shelves: s.shelves.filter(x => x.id !== id),
        })),
    }),
    { name: 'smart-shelves-v1' },
  ),
)
