import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { getRuntime } from './config/runtime'
import './styles.css'

const runtime = getRuntime()
if (runtime.iosApp) {
  document.documentElement.classList.add('wordloop-ios-app')
}

const CHUNK_RELOAD_KEY = 'wordloop-chunk-reload'

/** 部署后旧 bundle 引用已删除的 chunk 时，强制拉取最新 index.html */
function reloadOnStaleChunk(): void {
  if (runtime.embedded) return
  const attempts = Number(sessionStorage.getItem(CHUNK_RELOAD_KEY) || '0')
  if (attempts >= 2) return
  sessionStorage.setItem(CHUNK_RELOAD_KEY, String(attempts + 1))
  const url = new URL(window.location.href)
  url.searchParams.set('_cb', String(Date.now()))
  window.location.replace(url.toString())
}

function isStaleChunkError(reason: unknown): boolean {
  const msg = String(
    reason instanceof Error ? reason.message : reason ?? '',
  )
  return (
    msg.includes('Failed to fetch dynamically imported module') ||
    msg.includes('Loading chunk') ||
    msg.includes('ChunkLoadError')
  )
}

if (!runtime.embedded) {
  window.addEventListener('vite:preloadError', (event) => {
    event.preventDefault()
    reloadOnStaleChunk()
  })

  window.addEventListener('unhandledrejection', (event) => {
    if (!isStaleChunkError(event.reason)) return
    event.preventDefault()
    reloadOnStaleChunk()
  })

  router.onError((error) => {
    if (!isStaleChunkError(error)) return
    reloadOnStaleChunk()
  })
}

function bootApp() {
  try {
    const app = createApp(App).use(router)
    app.mount('#app')
    router.isReady().then(() => {
      sessionStorage.removeItem(CHUNK_RELOAD_KEY)
    })
  } catch (error) {
    window.__WORDLOOP_BOOT_ERROR__ = error instanceof Error ? error.message : String(error)
    throw error
  }
}

// iOS 内联脚本在 <head> 执行时 #app 尚未解析，必须等 DOM 就绪
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', bootApp, { once: true })
} else {
  bootApp()
}
