<template>
  <div class="page-idle" @click="goToMenu">
    <IdlePlayer @click="goToMenu" />
    <BroadcastOverlay :broadcast="screenStore.currentBroadcast" />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useScreenStore } from '@/stores/screen'
import { useWebSocketStore } from '@/stores/websocket'
import IdlePlayer from '@/components/IdlePlayer.vue'
import BroadcastOverlay from '@/components/BroadcastOverlay.vue'

const router = useRouter()
const screenStore = useScreenStore()
const wsStore = useWebSocketStore()

// 降级轮询定时器（WebSocket 不可用时使用）
const fallbackPollingTimer = ref(null)
const FALLBACK_POLL_INTERVAL = 30000 // 30 秒降级轮询

const goToMenu = () => {
  router.push('/menu')
}

/**
 * 停止降级轮询
 */
const stopFallbackPolling = () => {
  if (fallbackPollingTimer.value) {
    clearInterval(fallbackPollingTimer.value)
    fallbackPollingTimer.value = null
  }
}

/**
 * 开始降级轮询（WebSocket 不可用时）
 * 同时轮询播放方案和播报状态
 */
const startFallbackPolling = () => {
  stopFallbackPolling()
  // 立即请求一次
  screenStore.fetchPlayPlan()
  screenStore.fetchCurrentBroadcast()
  
  fallbackPollingTimer.value = setInterval(() => {
    console.log('[Idle] 降级轮询...')
    screenStore.fetchPlayPlan()
    screenStore.fetchCurrentBroadcast()
  }, FALLBACK_POLL_INTERVAL)
}

/**
 * 根据 WebSocket 连接状态决定是否启用降级轮询
 * 使用防抖避免快速状态变化导致的重复处理
 */
let handleWsTimer = null
const handleWsConnectionChange = (isConnected) => {
  // 防抖：100ms 内的重复调用只执行一次
  if (handleWsTimer) {
    clearTimeout(handleWsTimer)
  }
  handleWsTimer = setTimeout(() => {
    handleWsTimer = null
    if (isConnected) {
      // WebSocket 已连接，停止所有降级轮询
      console.log('[Idle] WebSocket 已连接，停止降级轮询')
      stopFallbackPolling()
      // 停止 screenStore 的播报轮询（使用 WebSocket 推送）
      screenStore.stopBroadcastPolling()
    } else {
      // WebSocket 断开，启用降级轮询
      console.log('[Idle] WebSocket 断开，启用降级轮询')
      // 播放方案轮询（30秒一次）
      startFallbackPolling()
      // 播报状态轮询（2秒一次，由 screenStore 统一管理）
      screenStore.startBroadcastPolling()
    }
  }, 100)
}

onMounted(() => {
  // 首次加载时请求配置
  screenStore.fetchScreenTheme()
  screenStore.fetchPlayPlan()
  screenStore.fetchRobotStatus()
  
  // 监听 WebSocket 连接状态变化
  watch(() => wsStore.isConnected, handleWsConnectionChange, { immediate: true })
})

onUnmounted(() => {
  // 组件销毁时停止轮询
  stopFallbackPolling()
  screenStore.stopBroadcastPolling()
  if (handleWsTimer) {
    clearTimeout(handleWsTimer)
    handleWsTimer = null
  }
})
</script>

<style scoped>
.page-idle {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}
</style>
