<template>
  <!-- 全局错误兜底界面 -->
  <template v-if="hasError">
    <div class="global-error-fallback">
      <div class="error-content">
        <h2>页面出现异常</h2>
        <p>抱歉,页面渲染过程中发生了错误,请尝试刷新页面。</p>
        <n-button type="primary" @click="handleReset">刷新页面</n-button>
      </div>
    </div>
  </template>
  <!-- 正常渲染 -->
  <template v-else>
    <n-config-provider :theme="appStore.isDark ? darkTheme : undefined" :theme-overrides="themeOverrides">
      <n-message-provider>
        <n-dialog-provider>
          <n-notification-provider>
            <router-view />
          </n-notification-provider>
        </n-dialog-provider>
      </n-message-provider>
    </n-config-provider>
  </template>
</template>

<script setup lang="ts">
import { ref, watch, onErrorCaptured } from 'vue'
import { darkTheme, type GlobalThemeOverrides } from 'naive-ui'
import { useAppStore } from '@/stores/app'
import { useRouter } from 'vue-router'

const appStore = useAppStore()
appStore.init()
const router = useRouter()

/** 是否存在未捕获的错误 */
const hasError = ref(false)

/** 路由切换时自动重置错误状态,避免单个页面错误永久锁定整个应用 */
watch(() => router.currentRoute.value.path, () => {
  if (hasError.value) {
    hasError.value = false
  }
})

/** 捕获子组件的错误,防止向上传播导致整个应用崩溃 */
onErrorCaptured((err: any, _instance, info: string) => {
  console.error('[全局错误捕获]', err)
  console.error('[错误来源]', info)

  // 跳过已知的非致命动画/插件初始化错误,避免锁定整个应用
  const errMsg = err?.message || String(err)
  const ignorablePrefixes = ['getThemeColors', 'Missing plugin']
  const isIgnorable = ignorablePrefixes.some(p => errMsg.startsWith(p)) || errMsg === 'gsap'
  if (isIgnorable) {
    console.warn('[全局错误捕获] 已忽略非致命错误:', errMsg)
    return false
  }

  // 显示兜底界面
  hasError.value = true
  // 阻止错误继续向上传播
  return false
})

/** 重置错误状态并刷新页面 */
function handleReset() {
  hasError.value = false
  window.location.reload()
}

const themeOverrides: GlobalThemeOverrides = {
  common: {
    primaryColor: '#7c3aed',
    primaryColorHover: '#8b5cf6',
    primaryColorPressed: '#6d28d9',
    primaryColorSuppl: '#a78bfa',
    borderRadius: '6px',
    borderRadiusSmall: '4px',
    fontFamily: `-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`
  },
  Button: {
    borderRadiusMedium: '6px',
    borderRadiusSmall: '4px'
  },
  Card: {
    borderRadius: '10px'
  },
  Input: {
    borderRadius: '6px'
  },
  Menu: {
    itemBorderRadius: '6px'
  },
  Tag: {
    borderRadius: '99px'
  }
}
</script>

<style scoped>
.global-error-fallback {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: var(--ty-bg-page);
}

.error-content {
  text-align: center;
  padding: 40px;
  border-radius: 12px;
  background: var(--ty-bg-card);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.error-content h2 {
  margin-bottom: 12px;
  color: var(--ty-text);
  font-size: 20px;
}

.error-content p {
  margin-bottom: 24px;
  color: var(--ty-text-secondary);
  font-size: 14px;
}
</style>