<template>
  <view>
    <AppNavbar title="我的" />

    <view class="page profile-page">
    <view class="profile-head">
      <AtAvatar class="profile-avatar" circle :text="avatarText" />
      <view>
        <view class="section-title">{{ profile.username || '未命名用户' }}</view>
        <text class="profile-role muted">{{ roleName || '普通用户' }}</text>
      </view>
    </view>

    <AtList class="profile-cells">
      <AtListItem title="用户信息" arrow="right" @click="handleProfileInfoTap" />
      <AtListItem title="修改密码" arrow="right" @click="handlePasswordTap" />
    </AtList>

    <view class="logout-bar">
      <AtButton class="btn btn-primary" @click="logout">退出登录</AtButton>
    </view>

      <AppTabBar />
    </view>
  </view>
</template>

<script setup lang="ts">
import Taro, { useDidShow } from '@tarojs/taro'
import { computed, reactive, ref } from 'vue'
import { logoutApi } from '@/api/auth'
import { getProfileApi } from '@/api/profile'
import { isLoggedIn, redirectToLogin } from '@/utils/auth'
import { useUserStore } from '@/stores/user'
import AppNavbar from '@/components/AppNavbar.vue'
import AppTabBar from '@/custom-tab-bar/index.vue'

const userStore = useUserStore()
const roleName = ref('')
const profile = reactive({ username: '', nickname: '', phoneNumber: '', email: '' })
const avatarText = computed(() => (profile.nickname || profile.username || '我').slice(0, 1))

useDidShow(() => {
  if (!isLoggedIn()) {
    redirectToLogin()
    return
  }
  loadProfile()
})

async function loadProfile() {
  const { data } = await getProfileApi()
  Object.assign(profile, data.user || {})
  roleName.value = data.roleName || data.user?.roleName || ''
  userStore.setUser(data.user || {})
}

async function handleProfileInfoTap() {
  await navigateToPage('/pages/profile/info/index')
}

async function handlePasswordTap() {
  await navigateToPage('/pages/profile/password/index')
}

async function navigateToPage(url: string) {
  try {
    await Taro.navigateTo({ url })
  } catch (error) {
    console.error(error)
    Taro.showToast({ title: '页面跳转失败', icon: 'none' })
  }
}

async function logout() {
  await logoutApi().catch(() => undefined)
  userStore.clearSession()
  Taro.reLaunch({ url: '/pages/login/index' })
}
</script>

<style lang="scss">
.profile-head {
  display: flex;
  gap: $space-lg;
  align-items: center;
  padding: 0 0 28px;
}

.profile-avatar.at-avatar {
  width: 112px;
  height: 112px;
  font-size: $font-profile-title;
  font-weight: 700;
  line-height: 112px;
  background: $color-primary;
  border-radius: $radius-md;
}

.profile-head .section-title {
  margin-bottom: 6px;
}

.profile-role {
  font-size: $font-md;
  line-height: 34px;
}

.profile-cells {
  margin-bottom: $space-lg;
}

.profile-cells.at-list::before,
.profile-cells.at-list::after {
  content: initial;
  border: 0;
}

.logout-bar {
  position: fixed;
  right: $space-xl;
  bottom: calc(128px + env(safe-area-inset-bottom));
  left: $space-xl;
  z-index: 900;
}
</style>
