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

export interface SavedLetterboxdList {
  /** Canonical URL: `https://letterboxd.com/{user}/list/{slug}/` */
  url: string
  addedAt: string
  /** Optional override - the user can rename a list locally. */
  customTitle?: string
}

interface State {
  lists: SavedLetterboxdList[]
  add: (url: string) => void
  remove: (url: string) => void
  rename: (url: string, customTitle: string | undefined) => void
}

export const useLetterboxdLists = create<State>()(
  persist(
    set => ({
      lists: [],
      add: url =>
        set(s => {
          if (s.lists.some(l => l.url === url)) return s
          return {
            lists: [...s.lists, { url, addedAt: new Date().toISOString() }],
          }
        }),
      remove: url =>
        set(s => ({ lists: s.lists.filter(l => l.url !== url) })),
      rename: (url, customTitle) =>
        set(s => ({
          lists: s.lists.map(l => (l.url === url ? { ...l, customTitle } : l)),
        })),
    }),
    { name: 'letterboxd-lists-v1' },
  ),
)
