import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import App from './App.vue'
import router from './router'
import './style/index.scss'
import { errorHandler, handlePromiseError } from './utils/errorHandler'

const app = createApp(App)

// 设置页面标题（优先使用环境变量）
const appTitle = import.meta.env.VITE_APP_TITLE || '考培练系统'
if (document.title !== appTitle) {
  document.title = appTitle
}

// 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(createPinia())
app.use(router)
app.use(ElementPlus)

// 设置全局错误处理
app.config.errorHandler = (error, _instance, info) => {
  console.error('Vue Error:', error, info)
  errorHandler.handleError(error, `Vue Error: ${info}`)
}

// 处理未捕获的 Promise 错误
window.addEventListener('unhandledrejection', (event) => {
  handlePromiseError(event.reason, 'Unhandled Promise Rejection')
  event.preventDefault() // 防止错误在控制台中显示
})

// 处理全局未捕获的错误
window.addEventListener('error', (event) => {
  errorHandler.handleError(event.error || event.message, 'Global Error')
})

app.mount('#app')