import { createApp } from 'vue'
import App from '@/App.vue'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
// 导入 Element Plus 样式（必须）
import 'element-plus/dist/index.css'
// 导入 Element Plus 暗黑模式样式
import 'element-plus/theme-chalk/dark/css-vars.css'
import '@/assets/less/index.less'
import '@/assets/css/all.min.css'
import '@/assets/js/all.min.js'
import router from './router'
import { loadAndAddDynamicRoutes } from './router'
import { createPinia } from 'pinia'
import { useAuthStore } from './stores/auth'
// import { initTheme } from './utils/theme'
// 导入全局组件
import WangEditor from '@/views/components/WangEditor.vue';

const app = createApp(App)
const pinia = createPinia()
// 全局注册 WangEditor 组件
app.component('WangEditor', WangEditor);

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(pinia)
app.use(router)

// 初始化主题（必须在挂载前执行）
// initTheme()

// 初始化时检查认证状态
const authStore = useAuthStore()
authStore.checkAuth()

// 如果用户已登录，在应用启动时加载动态路由
if (authStore.isLoggedIn) {
  loadAndAddDynamicRoutes()
    .catch(err => {
      console.error('应用启动时加载动态路由失败:', err);
    })
    .then(() => {
      // 检查是否因为 token 无效而导致路由加载失败
      const token = localStorage.getItem('token');
      if (!token) {
        authStore.clearToken();
        window.location.href = '#/login';
      }
    });
}

app.mount('#app')