// localStorage 包装。SSR safe。

export interface GameState {
  playerRoles: string[]
  pendingConfirm: number[]
  deadPlayers: number[]
  startedAt: number
}

export interface HistoryEntry {
  playerCount: number
  roles: Record<string, number>
}

interface PersistedState {
  game: GameState | null
  history: HistoryEntry[]
}

const KEY = 'werewolf:v1'
const MAX_HISTORY = 50

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

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

export function saveState(state: PersistedState): void {
  if (!isBrowser()) return
  try {
    window.localStorage.setItem(KEY, JSON.stringify(state))
  } catch {
    // 配额满 / 隐私模式，静默
  }
}

/** 加一条历史，去重（同 playerCount + 同 roles dict）+ 截断到 MAX_HISTORY。 */
export function addHistory(history: HistoryEntry[], entry: HistoryEntry): HistoryEntry[] {
  const filtered = history.filter(
    (h) => !(h.playerCount === entry.playerCount && rolesEqual(h.roles, entry.roles)),
  )
  return [entry, ...filtered].slice(0, MAX_HISTORY)
}

function rolesEqual(a: Record<string, number>, b: Record<string, number>): boolean {
  const ka = Object.keys(a)
  const kb = Object.keys(b)
  if (ka.length !== kb.length) return false
  for (const k of ka) {
    if (a[k] !== b[k]) return false
  }
  return true
}
