<template>
  <a-config-provider :locale="zhCN" :theme="themeStore.antThemeConfig">
    <SplashScreen
      v-if="loading"
      :status="loadingStatus"
      :error="loadError"
      :on-retry="retryBootstrap"
    />
    <router-view v-else />
  </a-config-provider>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ConfigProvider as AConfigProvider } from 'ant-design-vue'
import zhCN from 'ant-design-vue/es/locale/zh_CN'
import { useRouter } from 'vue-router'
import { useThemeStore } from './stores/theme'
import { useAuthStore } from './stores/auth'
import { isTauri } from './api/tauri'
import {
  setTokenProvider,
  setRefreshProvider,
  setUnauthorizedHandler,
  setPreEmptiveRefreshProvider,
} from './api/base'
import SplashScreen from './components/layout/SplashScreen.vue'

const themeStore = useThemeStore()
const authStore = useAuthStore()
const router = useRouter()

const loading = ref(isTauri())
const loadError = ref('')
// Mirror the auth store's bootstrap progress so the SplashScreen shows
// "正在启动后端..." / "正在检查服务..." etc.
const loadingStatus = computed(() => authStore.bootstrapStatus || '正在初始化...')

onMounted(async () => {
  // Wire the auth store into the API client so every request gets a JWT
  // attached automatically, and 401s trigger a token refresh.
  setTokenProvider(() => authStore.accessToken)
  setRefreshProvider(async () => {
    const pair = await authStore.silentRefresh()
    return pair?.access_token ?? null
  })
  setPreEmptiveRefreshProvider(() => authStore.shouldRefresh)
  setUnauthorizedHandler(() => {
    void authStore.logoutLocal()
    router.replace({ name: 'login' })
  })

  // The cold-start (Tauri backend bootstrap + whoami) was kicked off in
  // ``main.ts`` before mount. ``router.beforeEach`` already awaited it,
  // so by the time we get here the startup state is final. We still
  // await ``waitForStartup()`` for the SplashScreen to transition
  // correctly based on the result.
  if (isTauri()) {
    const result = await authStore.waitForStartup()
    if (result === 'valid') {
      loading.value = false
    } else if (result === 'error') {
      loadError.value = authStore.error || '后端服务不可用'
    }
    // 'invalid' → loading stays true briefly but the router guard has
    // already redirected to /login; flip loading off so /login renders.
    if (result === 'invalid') {
      loading.value = false
    }
  } else {
    // Non-Tauri (browser): the router guard awaited the probe too;
    // no splash needed.
    loading.value = false
  }
})

/** User-triggered retry from the error screen. */
async function retryBootstrap(): Promise<void> {
  loadError.value = ''
  loading.value = true
  const result = await authStore.retryStartup()
  if (result === 'valid') {
    loading.value = false
  } else if (result === 'error') {
    loadError.value = authStore.error || '后端服务不可用'
  } else if (result === 'invalid') {
    // Refresh token turned out invalid — send the user to /login.
    loading.value = false
    router.replace({ name: 'login' })
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body, #app {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
    'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
    'Noto Sans Emoji';
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: var(--text-primary, #1a1a1a);
  background: var(--bg-secondary, #fbfbfa);
}

/* Notion-style scrollbar */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background: var(--color-gray-300, #dfdfde);
  border-radius: var(--radius-full, 9999px);
}

::-webkit-scrollbar-thumb:hover {
  background: var(--color-gray-400, #cececd);
}

/* Ant Design overrides for Notion-style feel */
.ant-btn {
  font-weight: var(--font-weight-medium, 500);
}

.ant-card {
  border-color: var(--border-color, #ededec) !important;
}

.ant-card-hoverable:hover {
  border-color: var(--color-primary-light, #eef2ff) !important;
  box-shadow: var(--shadow-md, 0 2px 8px rgba(0, 0, 0, 0.06), 0 1px 2px rgba(0, 0, 0, 0.04)) !important;
}

.ant-tabs-tab {
  transition: color var(--transition-fast, 150ms ease) !important;
}

.ant-tag {
  border-radius: var(--radius-sm, 4px) !important;
}

.ant-modal-content {
  border-radius: var(--radius-xl, 14px) !important;
}

.ant-select-selector {
  border-radius: var(--radius-md, 6px) !important;
}
</style>
