import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import type { VocabTopic } from '@/types'

interface VocabStore {
  currentTopic: VocabTopic
  currentIndex: number
  knownWords: string[] // word IDs

  setTopic: (topic: VocabTopic) => void
  setCurrentIndex: (index: number) => void
  markKnown: (wordId: string) => void
  markNeedReview: (wordId: string) => void
  reset: () => void
}

export const useVocabStore = create<VocabStore>()(
  persist(
    (set) => ({
      currentTopic: 'Tất cả',
      currentIndex: 0,
      knownWords: [],

      setTopic: (currentTopic) => set({ currentTopic, currentIndex: 0 }),

      setCurrentIndex: (currentIndex) => set({ currentIndex }),

      markKnown: (wordId) =>
        set((state) => ({
          knownWords: [...new Set([...state.knownWords, wordId])],
        })),

      markNeedReview: (wordId) =>
        set((state) => ({
          knownWords: state.knownWords.filter((id) => id !== wordId),
        })),

      reset: () => set({ currentTopic: 'Tất cả', currentIndex: 0, knownWords: [] }),
    }),
    { name: 'vocab-store' },
  ),
)
