import { createApp } from 'vue'

import App from './App.vue'
import router from './router'
import './styles/index.scss'
import './styles/tailwindcss.css'
import 'element-plus/theme-chalk/dark/css-vars.css'
import 'virtual:svg-icons-register'
import { initService } from '@/utils/request.ts'
import websocket from '@/utils/websocket'
import { setupStore, useConfigStore } from '@/stores'
import { setupDirective } from '@/ directive'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
async function init() {
  const configStore = useConfigStore()
  await configStore.initConfig()
  const app = createApp(App)
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
  }
  setupStore(app)
  setupDirective(app)
  initService()

  // 初始化WebSocket连接
  try {
    // WebSocket需要直接连接到后端，不能通过代理
    const apiBaseUrl = configStore.config.apiBaseUrl || `${import.meta.env.BASE_URL || '/'}api`
    // 移除 /api 后缀，如果是相对路径则构造完整URL
    let wsUrl = apiBaseUrl.replace(/\/api$/, '')
    // 如果是相对路径（以/开头），使用当前host
    if (wsUrl.startsWith('/')) {
      wsUrl = `${window.location.protocol}//${window.location.host}${wsUrl}`
    }
    console.log('🔌 Connecting to WebSocket at:', wsUrl)
    await websocket.connect(wsUrl)
    console.log('✅ WebSocket initialized successfully')
  } catch (error) {
    console.warn('⚠️  WebSocket connection failed, will use REST API fallback:', error)
  }

  document.title = configStore.config.centerTitle
  app.use(router)
  app.mount('#app')
}

void init()
