import type { Word } from './wordlist'

export interface GameConfig {
  topic: string | null
  difficulty: 1 | 2 | 3
  totalWords: number
}

export interface GameState {
  config: GameConfig
  queue: Word[]
  currentIndex: number
  correctCount: number
  passCount: number
}

interface PersistedState {
  game: GameState | null
  seenWords: string[] // wordKey list
}

const KEY = 'articulate:v1'
const MAX_SEEN = 5000

function isBrowser(): boolean {
  return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined'
}

export function loadState(): PersistedState {
  if (!isBrowser()) return { game: null, seenWords: [] }
  try {
    const raw = window.localStorage.getItem(KEY)
    if (!raw) return { game: null, seenWords: [] }
    const parsed = JSON.parse(raw) as Partial<PersistedState>
    return {
      game: parsed.game ?? null,
      seenWords: parsed.seenWords ?? [],
    }
  } catch {
    return { game: null, seenWords: [] }
  }
}

export function saveState(state: PersistedState): void {
  if (!isBrowser()) return
  try {
    // 限制 seen list 大小
    const seen = state.seenWords.slice(-MAX_SEEN)
    window.localStorage.setItem(KEY, JSON.stringify({ ...state, seenWords: seen }))
  } catch {
    // ignore
  }
}

export function addSeen(seen: string[], keys: string[]): string[] {
  const set = new Set(seen)
  const out = [...seen]
  for (const k of keys) {
    if (!set.has(k)) {
      set.add(k)
      out.push(k)
    }
  }
  return out.slice(-MAX_SEEN)
}
