/**
 * 应用入口 — Yuto Water H5
 *
 * 初始化 Vue 应用，集成 Vant 4 UI、Pinia 状态管理、
 * Vue Router 路由、全局样式等核心模块。
 *
 * @module main
 */

import { createApp } from 'vue'
import { createPinia } from 'pinia'

// ── Vant 4 组件按需注册 ──
import {
  ConfigProvider,
  NavBar,
  Tabbar,
  TabbarItem,
  Button,
  Form,
  Field,
  Cell,
  CellGroup,
  Popup,
  Uploader,
  PullRefresh,
  List,
  Tabs,
  Tab,
  Divider,
  Loading,
  Icon,
  Grid,
  GridItem,
  Empty,
  Search,
  Card,
  Image,
  Tag,
  Picker,
  DatePicker,
  ActionSheet,
} from 'vant'

// ── Vant 样式（组件样式按需引入） ──
import 'vant/lib/index.css'

// ── MapLibre GL 样式 ──
import 'maplibre-gl/dist/maplibre-gl.css'

// ── 全局样式 ──
import './styles/index.scss'

// ── Store ──
import { useAppStore } from './stores/app'

// ── 路由 ──
import router from './router'

// ── 根组件 ──
import App from './App.vue'

// ══════════════════════════════════════════════
// 全局错误处理
// ══════════════════════════════════════════════

/** 捕获未处理的 Promise 拒绝 */
window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {
  console.error('[Yuto Water H5] 未处理的 Promise 拒绝:', event.reason)
  event.preventDefault()
})

/** 捕获全局 JavaScript 错误 */
window.addEventListener('error', (event: ErrorEvent) => {
  console.error('[Yuto Water H5] 全局错误:', event.message, 'at', event.filename, ':', event.lineno)
  // 防止错误冒泡导致白屏
  event.preventDefault()
})

// ══════════════════════════════════════════════
// 创建应用
// ══════════════════════════════════════════════

const app = createApp(App)

// ── 注册 Pinia ──
const pinia = createPinia()
app.use(pinia)

// ── 初始化暗黑模式（从 localStorage 读取并应用） ──
// useAppStore 内部已通过 watch(darkMode, ..., { immediate: true })
// 在首次创建时自动同步 dark 类名到 <html> 元素
useAppStore()

// ── 注册 Vant 组件（组件类） ──
// Toast / Dialog / ImagePreview 为函数式 API，
// 直接从 vant 导入即可使用，无需 app.use 注册。
const vantComponents = [
  ConfigProvider,
  NavBar,
  Tabbar,
  TabbarItem,
  Button,
  Form,
  Field,
  Cell,
  CellGroup,
  Popup,
  Uploader,
  PullRefresh,
  List,
  Tabs,
  Tab,
  Divider,
  Loading,
  Icon,
  Grid,
  GridItem,
  Empty,
  Search,
  Card,
  Image,
  Tag,
  Picker,
  DatePicker,
  ActionSheet,
]

for (const component of vantComponents) {
  app.use(component)
}

// ── 注册路由 ──
app.use(router)

// ══════════════════════════════════════════════
// 挂载应用（带错误处理）
// ══════════════════════════════════════════════

try {
  app.mount('#app')
} catch (err) {
  console.error('[Yuto Water H5] 应用挂载失败:', err)
  // 在 DOM 中展示降级错误信息
  const root = document.getElementById('app')
  if (root) {
    root.innerHTML = `
      <div style="
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100vh;
        font-family: -apple-system, BlinkMacSystemFont, sans-serif;
        color: #323233;
        text-align: center;
        padding: 24px;
      ">
        <h1 style="font-size: 20px; margin-bottom: 8px;">应用加载失败</h1>
        <p style="font-size: 14px; color: #969799;">
          ${err instanceof Error ? err.message : '未知错误'}
        </p>
        <button
          onclick="location.reload()"
          style="
            margin-top: 16px;
            padding: 8px 24px;
            border: none;
            border-radius: 8px;
            background: #2196F3;
            color: #fff;
            font-size: 14px;
            cursor: pointer;
          "
        >
          重新加载
        </button>
      </div>
    `
  }
}
