<template>
  <div class="page mine">
    <!-- 用户信息头 -->
    <header class="mine-hd">
      <div class="mine-hd__top">
        <div class="avatar" @click="openAvatarSheet">
          <img v-if="avatarUrl" :src="avatarUrl" alt="头像" @error="onAvatarError" />
          <span v-else class="avatar__fallback">{{ avatarInitial }}</span>
        </div>
        <div class="uinfo">
          <div class="uinfo__name">{{ displayName }}</div>
          <div class="uinfo__phone">{{ displayPhone }}</div>
        </div>
        <div class="uinfo__edit" @click="toast('编辑资料')">编辑 ›</div>
      </div>

      <!-- 数据统计 -->
      <div class="stats">
        <div class="stats__item" v-for="s in stats" :key="s.key" @click="toast(s.label)">
          <b>{{ s.value }}</b>
          <span>{{ s.label }}</span>
        </div>
      </div>
    </header>

    <div class="page__inner mine-bd">
      <!-- 成为骑手 -->
      <section class="card rider" @click="toast('申请成为骑手')">
        <div class="rider__left">
          <div class="rider__title">成为校园骑手</div>
          <div class="rider__sub muted">课余接单，赚取零花钱，时间自由</div>
        </div>
        <span class="rider__btn">去认证</span>
      </section>

      <!-- 我的钱包卡片 -->
      <section class="card wallet">
        <div class="wallet__item" @click="toast('我的钱包')">
          <span class="wallet__icon"><AppIcon name="wallet" :size="26" /></span><span>我的钱包</span>
        </div>
        <div class="wallet__item" @click="toast('优惠券')">
          <span class="wallet__icon"><AppIcon name="coupon" :size="26" /></span><span>优惠券</span>
        </div>
        <div class="wallet__item" @click="toast('积分商城')">
          <span class="wallet__icon"><AppIcon name="points" :size="26" /></span><span>积分商城</span>
        </div>
        <div class="wallet__item" @click="toast('会员中心')">
          <span class="wallet__icon"><AppIcon name="member" :size="26" /></span><span>会员中心</span>
        </div>
      </section>

      <!-- 常用功能 -->
      <section class="section">
        <div class="section__head"><div class="section__title">常用功能</div></div>
        <div class="card tools">
          <div
            v-for="t in mineTools"
            :key="t.key"
            class="tools__item"
            @click="toast(t.name)"
          >
            <span class="tools__icon">
              <AppIcon v-if="t.svg" :name="t.svg" :size="24" />
              <template v-else>{{ t.icon }}</template>
            </span>
            <span class="tools__name">{{ t.name }}</span>
          </div>
        </div>
      </section>

      <!-- 服务与协议 -->
      <van-cell-group inset class="agreements">
        <van-cell title="服务协议" is-link @click="toast('服务协议')" />
        <van-cell title="隐私政策" is-link @click="toast('隐私政策')" />
        <van-cell title="关于校跑侠" value="v1.0.0" is-link @click="toast('关于我们')" />
      </van-cell-group>

      <div class="logout" @click="onLogout">退出登录</div>
    </div>

    <van-action-sheet
      v-model:show="avatarSheetShow"
      :actions="avatarActions"
      cancel-text="取消"
      close-on-click-action
      @select="onAvatarSelect"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showLoadingToast, closeToast } from 'vant'
import { mineTools } from '../data/mock.js'
import { session, ensureLogin, logout } from '../store/session.js'
import { resolveDailyAvatar, refreshDailyAvatar, setCustomAvatar } from '../store/avatar.js'

const router = useRouter()
const toast = (m) => showToast(m)

function onLogout() {
  logout()
  showToast('已退出登录')
  router.replace('/login')
}

const displayName = computed(() => session.profile?.name || '同学你好')
const displayPhone = computed(() => {
  const p = session.profile?.phone
  return p ? p.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '未登录'
})
const avatarInitial = computed(() => (session.profile?.name || '游')[0])
const stats = computed(() => [
  {
    key: 'wallet',
    label: '钱包(元)',
    value: session.profile ? Number(session.profile.balance).toFixed(2) : '0.00'
  },
  { key: 'coupon', label: '优惠券', value: session.profile ? String(session.profile.coupons) : '0' },
  { key: 'point', label: '积分', value: session.profile ? String(session.profile.points) : '0' }
])

// 头像：每人每天随机一次，可自定义
const avatarUrl = ref('')
const avatarSheetShow = ref(false)
const avatarActions = [{ name: '换一张随机头像' }, { name: '自定义头像链接' }]

async function loadAvatar() {
  const profile = await ensureLogin()
  try {
    avatarUrl.value = await resolveDailyAvatar(profile.id)
  } catch (e) {
    avatarUrl.value = ''
  }
}
onMounted(loadAvatar)
onActivated(loadAvatar)

function openAvatarSheet() {
  avatarSheetShow.value = true
}
function onAvatarError() {
  avatarUrl.value = ''
}
async function onAvatarSelect(action) {
  const profile = session.profile
  if (!profile) return
  if (action.name === '换一张随机头像') {
    setCustomAvatar(profile.id, '')
    showLoadingToast({ message: '换一张…', forbidClick: true, duration: 0 })
    try {
      avatarUrl.value = await refreshDailyAvatar(profile.id)
      closeToast()
    } catch (e) {
      closeToast()
      showToast('获取失败，请重试')
    }
  } else if (action.name === '自定义头像链接') {
    const url = window.prompt('请输入头像图片链接（http/https）', avatarUrl.value || 'https://')
    if (url && /^https?:\/\//.test(url)) {
      setCustomAvatar(profile.id, url)
      avatarUrl.value = url
      showToast('已更新头像')
    } else if (url) {
      showToast('链接格式不正确')
    }
  }
}
</script>

<style scoped>
.mine {
  background: var(--brand-bg);
}
.mine-hd {
  background: linear-gradient(160deg, #2f7bff 0%, #1677ff 50%, #0958d9 100%);
  padding: calc(env(safe-area-inset-top) + 18px) 16px 44px;
  color: #fff;
  border-radius: 0 0 22px 22px;
}
.mine-hd__top {
  display: flex;
  align-items: center;
  gap: 12px;
}
.avatar {
  width: 58px;
  height: 58px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.22);
  border: 2px solid rgba(255, 255, 255, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  cursor: pointer;
}
.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.avatar__fallback {
  font-size: 24px;
  font-weight: 800;
  color: #fff;
}
.uinfo {
  flex: 1;
}
.uinfo__name {
  font-size: 19px;
  font-weight: 800;
}
.uinfo__phone {
  margin-top: 4px;
  font-size: 13px;
  opacity: 0.9;
}
.uinfo__edit {
  font-size: 13px;
  background: rgba(255, 255, 255, 0.2);
  padding: 5px 12px;
  border-radius: 16px;
}
.stats {
  display: flex;
  margin-top: 20px;
}
.stats__item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 3px;
}
.stats__item b {
  font-size: 20px;
  font-weight: 800;
}
.stats__item span {
  font-size: 12px;
  opacity: 0.9;
}
.mine-bd {
  margin-top: -30px;
  position: relative;
}

/* 骑手 */
.rider {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: linear-gradient(120deg, #fff7e8, #ffffff);
  border: 1px solid #ffe7ba;
}
.rider__title {
  font-size: 16px;
  font-weight: 800;
  color: #d46b08;
}
.rider__sub {
  margin-top: 4px;
  font-size: 12px;
}
.rider__btn {
  background: linear-gradient(135deg, #ff9a2e, #fa8c16);
  color: #fff;
  font-weight: 700;
  font-size: 13px;
  padding: 8px 16px;
  border-radius: 18px;
}

/* 钱包 */
.wallet {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  padding: 16px 0;
  margin-top: 12px;
}
.wallet__item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: var(--brand-text-secondary);
}
.wallet__icon {
  font-size: 24px;
}

/* 工具 */
.tools {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px 0;
  padding: 18px 0;
}
.tools__item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 7px;
  font-size: 12px;
  color: var(--brand-text-secondary);
}
.tools__icon {
  font-size: 24px;
}

.agreements {
  margin-top: 14px;
}
.logout {
  margin: 20px auto 10px;
  text-align: center;
  color: var(--brand-text-tertiary);
  font-size: 14px;
}
</style>
