<template>
  <div id="app">
    <NavBar/>
    <div style="margin-top: 60px">
      <router-view />
    </div>

    <LoadingSpinner v-if="store.state.loading.isLoading"/>
  </div>
</template>

<script setup>
import {onMounted, watch} from 'vue'
import {useStore} from 'vuex'
import NavBar from "./components/NavBar.vue";
import LoadingSpinner from "./components/LoadingSpinner.vue";
import AuthService from "../services/auth.js";

const store = useStore()

// 根据主题更新 body 上的类
const updateGlobalTheme = (theme) => {
  if (!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
    document.body.classList.add('theme-light')
    return;
  }
  if (theme === 'light') {
    document.body.classList.add('theme-light')
  } else {
    document.body.classList.remove('theme-light')
  }
}

// 挂载时根据 store 中的主题状态更新全局样式
onMounted(async () => {
  if (await AuthService.getToken()) {
    AuthService.setSelfInfo();
  } else {
    AuthService.logout();
  }
  updateGlobalTheme(store.state.theme)
})

// 监听 Vuex 主题状态的变化，更新全局样式
watch(
    () => store.state.theme,
    (newTheme) => {
      updateGlobalTheme(newTheme)
    }
)
</script>
