/** 页签内设备会话（sessionStorage，同页签刷新保留，新页签无数据） */
const SESSION_KEY = 'tsb_device_session'

export function loadTsbDeviceSession() {
  try {
    const raw = sessionStorage.getItem(SESSION_KEY)
    return raw ? JSON.parse(raw) : null
  } catch (e) {
    return null
  }
}

export function saveTsbDeviceSession(payload) {
  sessionStorage.setItem(SESSION_KEY, JSON.stringify(payload))
}

export function clearTsbDeviceSession() {
  sessionStorage.removeItem(SESSION_KEY)
}

export function hasTsbDeviceSession() {
  const session = loadTsbDeviceSession()
  return !!(session && session.userInitiatedConnect && session.currentDevice && session.currentDevice.deviceSn != null)
}

export function buildDeviceSession(currentDevice, openedDevices, devicePanelMap) {
  const list = Array.isArray(openedDevices) ? openedDevices.slice() : []
  if (currentDevice && !list.some(d => d.deviceSn === currentDevice.deviceSn)) {
    list.push(currentDevice)
  }
  return {
    currentDevice,
    openedDevices: list,
    devicePanelMap: devicePanelMap || {},
    userInitiatedConnect: true
  }
}
