<script setup>
import { onMounted, onUnmounted } from 'vue'
import { listen } from '@tauri-apps/api/event'
import { useDeviceStore } from '@/stores/deviceStore'
import { useChatStore } from '@/stores/chatStore'
import { EventNames } from '@/types'
import Sidebar from '@/components/Sidebar.vue'

const deviceStore = useDeviceStore()
const chatStore = useChatStore()

let unlistenFns = []

// 初始化主题
function initTheme() {
  const theme = localStorage.getItem('theme') || 'system'
  const root = document.documentElement
  if (theme === 'system') {
    const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    root.classList.toggle('dark', isDark)
  } else {
    root.classList.toggle('dark', theme === 'dark')
  }
}

onMounted(async () => {
  // 初始化主题
  initTheme()
  
  // 初始化应用
  await deviceStore.initialize()

  // 监听设备发现事件
  unlistenFns.push(
    await listen(EventNames.DEVICE_FOUND, (event) => {
      deviceStore.addDevice(event.payload)
    })
  )

  // 监听设备离线事件
  unlistenFns.push(
    await listen(EventNames.DEVICE_LOST, (event) => {
      deviceStore.removeDevice(event.payload.deviceId)
    })
  )

  // 监听消息接收事件
  unlistenFns.push(
    await listen(EventNames.MESSAGE_RECEIVED, (event) => {
      chatStore.receiveMessage(event.payload)
    })
  )

  // 监听 WebSocket 连接事件
  unlistenFns.push(
    await listen(EventNames.WEBSOCKET_CONNECTED, (event) => {
      deviceStore.setDeviceConnected(event.payload.deviceId, true)
    })
  )

  // 监听 WebSocket 断开事件
  unlistenFns.push(
    await listen(EventNames.WEBSOCKET_DISCONNECTED, (event) => {
      deviceStore.setDeviceConnected(event.payload.deviceId, false)
    })
  )

  // 监听文件传输进度
  unlistenFns.push(
    await listen(EventNames.TRANSFER_PROGRESS, (event) => {
      chatStore.updateTransferProgress(event.payload)
    })
  )
})

onUnmounted(() => {
  // 清理事件监听
  unlistenFns.forEach(fn => fn())
})
</script>

<template>
  <div class="flex h-screen bg-surface-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100">
    <!-- 侧边栏 -->
    <Sidebar />
    
    <!-- 主内容区 -->
    <main class="flex-1 overflow-hidden">
      <router-view v-slot="{ Component }">
        <transition name="fade" mode="out-in">
          <component :is="Component" />
        </transition>
      </router-view>
    </main>
  </div>
</template>
