<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from './stores/user'

const route = useRoute()
const userStore = useUserStore()

const currentRoute = computed(() => {
  return route.path
})

onMounted(() => {
  if (userStore.isLoggedIn) {
    userStore.fetchUserInfo()
    userStore.fetchUsdcBalance()
  }
})
</script>

<template>
  <v-app>
    <v-app-bar color="primary" dark>
      <v-btn
        v-if="currentRoute !== '/'"
        icon
        variant="text"
        class="back-btn"
        aria-label="返回"
        @click="$router.back()"
      >
        <v-icon>mdi-arrow-left</v-icon>
      </v-btn>
      <v-app-bar-title v-if="currentRoute === '/'">PolyMarket</v-app-bar-title>
      <v-spacer></v-spacer>
      <v-btn
        v-if="!userStore.isLoggedIn"
        text
        to="/login"
        :class="{ active: currentRoute === '/login' }"
      >
        Login
      </v-btn>
      <template v-else>
        <v-btn
          class="balance-btn"
          variant="text"
          min-width="auto"
          padding="4 12"
          @click="$router.push('/wallet')"
        >
          <span class="balance-text">${{ userStore.balance }}</span>
        </v-btn>
        <v-menu location="bottom" :close-on-content-click="false">
          <template #activator="{ props }">
            <v-btn v-bind="props" icon variant="text" class="avatar-btn">
              <v-avatar size="36" color="primary">
                <v-img v-if="userStore.avatarUrl" :src="userStore.avatarUrl" cover alt="avatar" />
                <v-icon v-else>mdi-account</v-icon>
              </v-avatar>
            </v-btn>
          </template>
          <v-list density="compact">
            <v-list-item
              :title="userStore.user?.nickName || userStore.user?.userName || 'User'"
              disabled
            />
            <v-list-item title="退出登录" @click="userStore.logout()" />
          </v-list>
        </v-menu>
      </template>
    </v-app-bar>
    <v-main>
      <router-view v-slot="{ Component }">
        <keep-alive :include="['Home']">
          <component :is="Component" />
        </keep-alive>
      </router-view>
    </v-main>
  </v-app>
</template>

<style scoped>
/* Global styles can be added here */
.active {
  font-weight: bold;
  text-decoration: underline;
}

.balance-btn {
  color: rgba(255, 255, 255, 0.9);
  text-transform: none;
}

.balance-text {
  font-weight: 500;
  font-size: 0.95rem;
}

.back-btn {
  color: rgba(255, 255, 255, 0.9);
}
</style>
