/**
 * 多标签页 WebSocket：每页签独立持连，频道仅用于登出同步与消息透传
 */
const TAB_ID = `${Date.now()}-${Math.random()}`
const CHANNEL_NAME = 'tsb-ws-tab'

let channel = null
let coordinatorInited = false

const handlers = {
  onTabLogout: null,
  onBroadcastMessage: null
}

function postChannel(type, payload) {
  if (!channel) {
    return
  }
  channel.postMessage({ type, payload, from: TAB_ID })
}

function onChannelMessage(evt) {
  const { type, payload, from } = evt.data || {}
  if (from === TAB_ID) {
    return
  }
  if (type === 'ws-message') {
    handlers.onBroadcastMessage?.(payload)
  } else if (type === 'ws-logout') {
    handlers.onTabLogout?.()
  }
}

export function initTabCoordinator(options = {}) {
  Object.assign(handlers, options)
  if (coordinatorInited) {
    return
  }
  coordinatorInited = true

  if (typeof BroadcastChannel === 'undefined') {
    return
  }

  channel = new BroadcastChannel(CHANNEL_NAME)
  channel.onmessage = onChannelMessage
}

/** 每页签独立持连，本页始终视为可持有本地 WebSocket */
export function isLeaderTab() {
  return true
}

export function isFollowerConnected() {
  return false
}

export function broadcastWsMessage(message) {
  postChannel('ws-message', message)
}

/** 连接状态仅本页签维护，不再跨页签广播 */
export function broadcastWsStatus() {}

export function notifyLogout() {
  postChannel('ws-logout', {})
}

export function destroyTabCoordinator() {
  if (channel) {
    channel.close()
    channel = null
  }
  coordinatorInited = false
}
