<template>
  <div id="app-wrapper">
    <AppHeader class="header" />
    <main class="main-content">
      <router-view />
    </main>
    <AppFooter class="footer" v-if="false" />
    <!-- Payment Dialog -->
    <PaymentDialog ref="paymentDialog" @success="onPaymentSuccess" />
  </div>
</template>

<script setup>
import { ref, provide, onMounted } from 'vue'
import AppHeader from '@/components/common/AppHeader.vue'
import AppFooter from '@/components/common/AppFooter.vue'
import PaymentDialog from '@/components/PaymentDialog.vue'
import { useUserStore } from '@/stores/user'
import api from '@/api'
import { handleWxLoginCallback } from '@/utils/wxLogin'

const userStore = useUserStore()
const paymentDialog = ref(null)

onMounted(async () => {
  // 1. 尝试处理微信登录回调
  const isWxLoginSuccess = await handleWxLoginCallback()
  if (isWxLoginSuccess) {
    // 微信登录成功后拉取用户信息
    userStore.fetchProfile().catch(() => { })
    return
  }

  // 2. 正常 token 验证
  if (localStorage.getItem('token') && !userStore.tokenChecked) {
    userStore.fetchProfile().catch(() => { })
  }
})

provide('showPayment', () => {
  paymentDialog.value?.open()
})

function onPaymentSuccess() {
  userStore.fetchProfile()
}
</script>

<style lang="scss">
#app-wrapper {
  min-height: 100vh;
  max-width: 2000px;
  min-width: 1200px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;

  .main-content {
    flex: 1;
  }
}
</style>
