import { createApp } from 'vue'
import { createPinia } from 'pinia'
import naive from 'naive-ui'
import router from './router'
import App from './App.vue'
import './assets/styles/global.scss'

// 创建应用实例
const app = createApp(App)

// 使用插件
app.use(createPinia())
app.use(router)
app.use(naive)

// 全局主题应用：从 localStorage 读取并设置 data-theme 属性
const applyTheme = () => {
  const saved = localStorage.getItem('theme') || 'auto'
  if (saved === 'dark') {
    document.documentElement.setAttribute('data-theme', 'dark')
  } else if (saved === 'light') {
    document.documentElement.removeAttribute('data-theme')
  } else {
    const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
    if (prefersDark) document.documentElement.setAttribute('data-theme', 'dark')
    else document.documentElement.removeAttribute('data-theme')

    // 🔧 v3.13.5: 使用 MediaQueryList.onchange 替代 addEventListener
    // 避免内存泄漏，因为应用级别的监听器在 SPA 中不需要移除
    if (window.matchMedia) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      
      // 使用 onchange 属性，自动替换而非累积
      mediaQuery.onchange = (e) => {
        const t = localStorage.getItem('theme') || 'auto'
        if (t === 'auto') {
          if (e.matches) document.documentElement.setAttribute('data-theme', 'dark')
          else document.documentElement.removeAttribute('data-theme')
        }
      }
    }
  }
}

applyTheme()

// 挂载应用
app.mount('#app')
