/**
 * 用户信息存储
 */

// 用户信息缓存
let userProfileCache = null
let teamInfoCache = null

/**
 * 设置用户信息缓存
 * @param {Object} memberProfile - 用户资料
 * @param {Object} teamInfo - 团队信息
 */
export function setUserInfo(memberProfile, teamInfo = null) {
  userProfileCache = memberProfile
  teamInfoCache = teamInfo

  // 可选：存储到localStorage以便持久化
  if (memberProfile) {
    localStorage.setItem('userProfile', JSON.stringify(memberProfile))
  }
  if (teamInfo) {
    localStorage.setItem('teamInfo', JSON.stringify(teamInfo))
  }
}

/**
 * 单独设置团队信息缓存
 * @param {Object} teamInfo - 团队信息
 */
export function setTeamInfo(teamInfo) {
  teamInfoCache = teamInfo
  
  // 存储到localStorage以便持久化
  if (teamInfo) {
    localStorage.setItem('teamInfo', JSON.stringify(teamInfo))
  } else {
    localStorage.removeItem('teamInfo')
  }
}

/**
 * 获取用户信息缓存
 * @returns {Object|null} 用户资料
 */
export function getUserProfile() {
  if (userProfileCache) {
    return userProfileCache
  }

  // 从localStorage恢复
  const stored = localStorage.getItem('userProfile')
  if (stored) {
    try {
      userProfileCache = JSON.parse(stored)
      return userProfileCache
    } catch (error) {
      console.error('解析用户缓存失败:', error)
    }
  }

  return null
}

/**
 * 获取团队信息缓存
 * @returns {Object|null} 团队信息
 */
export function getTeamInfo() {
  if (teamInfoCache) {
    return teamInfoCache
  }

  // 从localStorage恢复
  const stored = localStorage.getItem('teamInfo')
  if (stored) {
    try {
      teamInfoCache = JSON.parse(stored)
      return teamInfoCache
    } catch (error) {
      console.error('解析团队缓存失败:', error)
    }
  }

  return null
}

/**
 * 清除用户信息缓存
 */
export function clearUserProfile() {
  userProfileCache = null
  teamInfoCache = null
  localStorage.removeItem('userProfile')
  localStorage.removeItem('teamInfo')
}

/**
 * 获取用户ID
 * @returns {string|null}
 */
export function getUserId() {
  const profile = getUserProfile()
  return profile?.id || null
}

/**
 * 获取TeamID
 * @returns {string|null}
 */
export function getTeamId() {
  const profile = getTeamInfo()
  return profile?.id || null
}

/**
 * 获取用户昵称
 * @returns {string|null}
 */
export function getUserNickname() {
  const profile = getUserProfile()
  return profile?.userNickname || null
}

/**
 * 获取用户账号
 * @returns {string|null}
 */
export function getUserAccount() {
  const profile = getUserProfile()
  return profile?.account || null
}
