import { create } from 'zustand'

/**
 * Multi-select state for the library grid. Lives outside React Query so
 * the selection can survive remounts / pagination scrolls but is reset
 * when the user explicitly clears it (Esc, click outside, batch action).
 *
 * Page state is intentionally *not* persisted - selection is ephemeral.
 */
interface State {
  selected: Set<string>
  toggle: (itemId: string) => void
  add: (itemId: string) => void
  remove: (itemId: string) => void
  setMany: (itemIds: string[]) => void
  clear: () => void
}

export const useLibrarySelection = create<State>(set => ({
  selected: new Set(),
  toggle: itemId =>
    set(s => {
      const next = new Set(s.selected)
      if (next.has(itemId)) next.delete(itemId)
      else next.add(itemId)
      return { selected: next }
    }),
  add: itemId =>
    set(s => {
      if (s.selected.has(itemId)) return s
      const next = new Set(s.selected)
      next.add(itemId)
      return { selected: next }
    }),
  remove: itemId =>
    set(s => {
      if (!s.selected.has(itemId)) return s
      const next = new Set(s.selected)
      next.delete(itemId)
      return { selected: next }
    }),
  setMany: itemIds => set({ selected: new Set(itemIds) }),
  clear: () => set({ selected: new Set() }),
}))
