/**
 * 建图状态管理工具
 * 用于在页面间持久化保存建图进度状态
 */

const STORAGE_KEY = 'map_building_state'

/**
 * 保存建图状态
 * @param {Object} state - 建图状态对象
 * @param {string} state.mapName - 地图名称
 * @param {number} state.progress - 构建进度 (0-100)
 * @param {boolean} state.isBuilding - 是否正在构建
 * @param {number} state.startTime - 开始时间戳
 */
export function saveBuildingState(state) {
  try {
    const stateToSave = {
      ...state,
      lastUpdate: Date.now()
    }
    localStorage.setItem(STORAGE_KEY, JSON.stringify(stateToSave))
    console.log('[BuildingState] 状态已保存:', stateToSave)
    return true
  } catch (err) {
    console.error('[BuildingState] 保存状态失败:', err)
    return false
  }
}

/**
 * 获取建图状态
 * @returns {Object|null} 建图状态对象，如果不存在则返回 null
 */
export function getBuildingState() {
  try {
    const stateStr = localStorage.getItem(STORAGE_KEY)
    if (!stateStr) {
      return null
    }
    
    const state = JSON.parse(stateStr)
    
    // 检查状态是否过期（超过24小时）
    const now = Date.now()
    const maxAge = 24 * 60 * 60 * 1000 // 24小时
    if (state.lastUpdate && (now - state.lastUpdate > maxAge)) {
      console.log('[BuildingState] 状态已过期，自动清除')
      clearBuildingState()
      return null
    }
    
    console.log('[BuildingState] 获取状态:', state)
    return state
  } catch (err) {
    console.error('[BuildingState] 获取状态失败:', err)
    return null
  }
}

/**
 * 更新建图进度
 * @param {number} progress - 新的进度值 (0-100)
 */
export function updateBuildingProgress(progress) {
  const state = getBuildingState()
  if (state) {
    state.progress = progress
    state.lastUpdate = Date.now()
    saveBuildingState(state)
  }
}

/**
 * 清除建图状态
 */
export function clearBuildingState() {
  try {
    localStorage.removeItem(STORAGE_KEY)
    console.log('[BuildingState] 状态已清除')
    return true
  } catch (err) {
    console.error('[BuildingState] 清除状态失败:', err)
    return false
  }
}

/**
 * 检查是否有正在构建的地图
 * @returns {boolean}
 */
export function hasActiveBuilding() {
  const state = getBuildingState()
  return state && state.isBuilding === true
}

/**
 * 标记建图完成
 */
export function markBuildingComplete() {
  const state = getBuildingState()
  if (state) {
    state.isBuilding = false
    state.progress = 100
    state.completeTime = Date.now()
    saveBuildingState(state)
  }
}

/**
 * 获取建图持续时间（秒）
 * @returns {number|null}
 */
export function getBuildingDuration() {
  const state = getBuildingState()
  if (!state || !state.startTime) {
    return null
  }
  
  const endTime = state.completeTime || Date.now()
  return Math.floor((endTime - state.startTime) / 1000)
}

