/**
 * 接收并管理游戏状态
 * 支持多玩家：playerStates Map<playerId, state>
 */

let currentRoomId = null

/** Map<playerId, state> */
const playerStates = new Map()

/** 玩家队伍信息 Map<playerId, team> */
const playerTeams = new Map()

/** 倒计时状态 */
let countdownState = { active: false, value: 0 }

/** 游戏进行中的房间计时状态 */
let roomTimerState = { active: false, durationSec: 0, startAtMs: 0 }

export function setCurrentRoom(roomId) {
  currentRoomId = roomId
}

export function getCurrentRoom() {
  return currentRoomId
}

/**
 * 设置玩家队伍信息
 */
export function setPlayerTeam(playerId, team) {
  playerTeams.set(playerId, team)
}

/**
 * 获取玩家队伍信息
 */
export function getPlayerTeam(playerId) {
  // 优先从 playerTeams Map 查询，其次从 playerStates 中提取 team 字段
  const team = playerTeams.get(playerId)
  if (team) return team
  const state = playerStates.get(playerId)
  if (state && state.team) return state.team
  return 'A'
}

/**
 * 更新某个玩家的状态
 * state 中必须含 playerId 字段
 */
export function setGameState(state) {
  if (!state) return
  const pid = state.playerId ?? 1
  // 同步提取 team 信息，确保分组始终正确
  if (state.team) {
    playerTeams.set(pid, state.team)
  }
  // 已结束的玩家保留 isGameOver 标记，不被新帧覆盖
  const prev = playerStates.get(pid)
  if (prev && prev.isGameOver && !state.isGameOver) return
  playerStates.set(pid, state)
}

/**
 * 标记某个玩家游戏结束（收到 room:gameOver 或 room:timeUp 时调用）
 */
export function setPlayerGameOver(playerId, score, nickname) {
  const pid = playerId ?? 1
  const prev = playerStates.get(pid) || {}
  playerStates.set(pid, {
    ...prev,
    playerId: pid,
    isGameOver: true,
    score: score ?? prev.score ?? 0,
    nickname: nickname ?? prev.nickname,
  })
}

/**
 * 标记所有玩家游戏结束（room:timeUp 时调用）
 */
export function setAllGameOver() {
  for (const [pid, state] of playerStates) {
    playerStates.set(pid, { ...state, isGameOver: true })
  }
}

/**
 * 获取所有玩家状态，按 playerId 升序排列
 * @returns {Array<state>}
 */
export function getAllPlayerStates() {
  if (playerStates.size === 0) return []
  return [...playerStates.entries()]
    .sort((a, b) => a[0] - b[0])
    .map(([, state]) => state)
}

/**
 * 兼容旧接口：返回第一个玩家状态（或 null）
 */
export function getGameState() {
  const all = getAllPlayerStates()
  return all.length > 0 ? all[0] : null
}

/**
 * 根据 playerId 获取玩家状态
 */
export function getPlayerState(playerId) {
  return playerStates.get(playerId)
}

/**
 * 设置倒计时值（服务端 room:countdown 驱动）
 */
export function setCountdown(value) {
  countdownState = { active: true, value }
}

/**
 * 清除倒计时（游戏开始后）
 */
export function clearCountdown() {
  countdownState = { active: false, value: 0 }
}

/**
 * 获取当前倒计时状态
 */
export function getCountdown() {
  return countdownState
}

/**
 * 设置房间游戏计时
 */
export function setRoomTimer(durationSec, startAtMs = Date.now()) {
  const safeDuration = Number(durationSec) || 0
  if (safeDuration <= 0) {
    roomTimerState = { active: false, durationSec: 0, startAtMs: 0 }
    return
  }
  roomTimerState = {
    active: true,
    durationSec: safeDuration,
    startAtMs,
  }
}

/**
 * 清除房间游戏计时
 */
export function clearRoomTimer() {
  roomTimerState = { active: false, durationSec: 0, startAtMs: 0 }
}

/**
 * 获取当前房间剩余时间
 */
export function getRoomTimer(now = Date.now()) {
  if (!roomTimerState.active || roomTimerState.durationSec <= 0) {
    return { active: false, remainingSec: 0, durationSec: 0 }
  }

  const elapsedSec = Math.max(0, Math.floor((now - roomTimerState.startAtMs) / 1000))
  const remainingSec = Math.max(0, roomTimerState.durationSec - elapsedSec)

  return {
    active: true,
    durationSec: roomTimerState.durationSec,
    remainingSec,
  }
}

export function clearGameState() {
  playerStates.clear()
  playerTeams.clear()
  countdownState = { active: false, value: 0 }
  roomTimerState = { active: false, durationSec: 0, startAtMs: 0 }
}
