<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900 flex flex-col">
    <Header />
    <main class="flex-grow w-full">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <router-view></router-view>
      </div>
    </main>
    <Footer />
    <Toast 
      :visible="visible"
      :message="message"
      :type="type"
    />
    <BackToTop />
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import Header from './components/Header.vue'
import Footer from './components/Footer.vue'
import Toast from './components/Toast.vue'
import BackToTop from './components/BackToTop.vue'
import { useToast } from './composables/useToast'
import { useAuthStore } from './store/auth'
import { http } from './utils/http'
import { authUtils } from './utils/auth'

const { visible, message, type } = useToast()
const authStore = useAuthStore()

// 在应用启动时初始化认证状态
onMounted(async () => {
  const encryptedToken = localStorage.getItem('token')
  if (encryptedToken) {
    const token = authUtils.decrypt(encryptedToken)
    if (token) {
      if (authUtils.isTokenNearExpiry(token)) {
        try {
          await http.refreshToken()
        } catch (error) {
          console.error('Failed to refresh token:', error)
          authStore.clearAuth()
          return
        }
      }
      http.setToken(token)
      try {
        await authStore.getCurrentUser()
      } catch (error) {
        console.error('Failed to get current user:', error)
        authStore.clearAuth()
      }
    }
  }
})
</script>