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

/**
 * Persisted snapshots of library filter state. The user picks a combo
 * they want to revisit (e.g. "Unwatched 4K HDR sci-fi") and we save it
 * by name; loading restores all the filter knobs in one click.
 *
 * Scope is per library type ('movies' / 'shows') so a "noir from the
 * 90s" search on Movies doesn't pollute the TV shows page.
 */

export interface SavedSearch {
  id: string
  name: string
  scope: 'movies' | 'shows'
  filters: SavedSearchFilters
  createdAt: string
}

export interface SavedSearchFilters {
  sortBy: string
  watched: 'any' | 'played' | 'unplayed'
  genre: string | null
  decade: number | null
  only4K: boolean
  onlyHdr: boolean
}

interface State {
  searches: SavedSearch[]
  add: (scope: 'movies' | 'shows', name: string, filters: SavedSearchFilters) => SavedSearch
  remove: (id: string) => void
}

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

export const useSavedSearches = create<State>()(
  persist(
    set => ({
      searches: [],
      add: (scope, name, filters) => {
        const next: SavedSearch = {
          id: uid(),
          name: name.trim(),
          scope,
          filters,
          createdAt: new Date().toISOString(),
        }
        set(s => ({ searches: [...s.searches, next] }))
        return next
      },
      remove: id => set(s => ({ searches: s.searches.filter(x => x.id !== id) })),
    }),
    { name: 'saved-searches-v1' },
  ),
)
