export const getLS = (k, def) => {
  try { const v = localStorage.getItem(k); return v ? JSON.parse(v) : def } catch { return def }
}
export const setLS = (k, v) => {
  try { localStorage.setItem(k, JSON.stringify(v)) } catch { }
}

export const KEYS = {
  mute: 'kk_mute',
  progress: 'kk_progress',
  friends: 'kk_friends',
  coins: 'kk_coins',
  xp: 'kk_xp',
  user: 'kk_user',
  role: 'kk_role',
  questionsMap: 'kk_questions_map'
}

export const getUser = () => getLS(KEYS.user, null)
export const setUser = (u) => {
  setLS(KEYS.user, u)
  window.dispatchEvent(new Event('kk_user_changed'))
}
export const getRole = () => getLS(KEYS.role, null)
export const setRole = (r) => setLS(KEYS.role, r)
export const getQuestionsMap = () => getLS(KEYS.questionsMap, {})
export const setQuestionsMap = (m) => setLS(KEYS.questionsMap, m)

// Color vision test
KEYS.colorTest = 'kk_color_test'
export const getColorTest = () => getLS(KEYS.colorTest, { status: 'not_started' })
export const setColorTest = (v) => setLS(KEYS.colorTest, v)
// Per-user map to avoid cross-user state
KEYS.colorTestMap = 'kk_color_test_map'
const defaultCT = { status: 'not_started' }
export const getColorTestFor = (userId) => {
  if (!userId) return getColorTest()
  const map = getLS(KEYS.colorTestMap, {})
  return map[userId] || defaultCT
}
export const setColorTestFor = (userId, v) => {
  if (!userId) return setColorTest(v)
  const map = getLS(KEYS.colorTestMap, {})
  map[userId] = v
  setLS(KEYS.colorTestMap, map)
}

// Users DB
KEYS.users = 'kk_users'
export const getUsers = () => getLS(KEYS.users, [])
export const setUsers = (arr) => setLS(KEYS.users, arr)
