import './polyfills/node-globals'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { createI18n } from 'vue-i18n'
import App from './App.vue'
import router from './router'
import { messages, DEFAULT_LOCALE, LOCALE_STORAGE_KEY, type SupportedLocale } from '@/locales'

import '@/assets/styles/variables.css'
import '@/assets/styles/reset.css'
import '@/assets/styles/global.css'

function getInitialLocale(): SupportedLocale {
  try {
    const stored = localStorage.getItem(LOCALE_STORAGE_KEY) as SupportedLocale | null
    if (stored && stored in messages) return stored
  } catch {
    // ignore
  }
  const browserLang = navigator.language
  if (browserLang.startsWith('zh-TW') || browserLang.startsWith('zh-HK')) return 'zh-TW'
  if (browserLang.startsWith('zh')) return 'zh-CN'
  if (browserLang.startsWith('ko')) return 'ko'
  if (browserLang.startsWith('ja')) return 'ja'
  if (browserLang.startsWith('hi')) return 'hi'
  if (browserLang.startsWith('id')) return 'id'
  if (browserLang.startsWith('en')) return 'en'
  return DEFAULT_LOCALE
}

const locale = getInitialLocale()

export const i18n = createI18n({
  legacy: false,
  locale,
  fallbackLocale: DEFAULT_LOCALE,
  messages,
})

document.documentElement.lang = locale

const app = createApp(App)

app.use(createPinia())
app.use(router)
app.use(i18n)

// 防止第三方库（klinecharts）内部 watcher 错误触发 Vite HMR 冻结组件更新
app.config.errorHandler = (err, _vm, info) => {
  console.error('[Vue]', info, err)
}

app.mount('#app')
