<template>
  <view class="page fade-in">
    <!-- 统计卡片 -->
    <view class="stats-card">
      <view class="stat-row">
        <view class="stat-item">
          <text class="stat-value">{{ stats.gravity ?? 0 }}</text>
          <text class="stat-label">🌌 我的引力值</text>
        </view>
      </view>
      <view class="stat-sub-row">
        <view class="stat-sub-item">
          <text class="stat-sub-value">{{ stats.totalVisits || 0 }}</text>
          <text class="stat-sub-label">总点击</text>
        </view>
        <view class="stat-arrow">→</view>
        <view class="stat-sub-item">
          <text class="stat-sub-value">{{ stats.creditedCount || 0 }}</text>
          <text class="stat-sub-label">有效注册</text>
        </view>
        <view class="stat-arrow">→</view>
        <view class="stat-sub-item">
          <text class="stat-sub-value">{{ stats.gravity || 0 }}</text>
          <text class="stat-sub-label">获得引力值</text>
        </view>
      </view>
      <view class="hint">
        💡 好友通过你的链接打开并 <text class="hint-em">登录/注册</text> 才算有效，每次有效获 1 引力值（每日上限 3）
      </view>
    </view>

    <!-- 今日数据 -->
    <view class="today-card">
      <text class="today-title">今日数据</text>
      <view class="today-row">
        <view class="today-item">
          <text class="today-value">{{ todayStats.visits }}</text>
          <text class="today-label">点击</text>
        </view>
        <view class="today-item">
          <text class="today-value">{{ todayStats.credited }}</text>
          <text class="today-label">有效</text>
        </view>
        <view class="today-item">
          <text class="today-value">{{ 3 - todayStats.credited > 0 ? 3 - todayStats.credited : 0 }}</text>
          <text class="today-label">今日剩余</text>
        </view>
      </view>
      <view class="today-bar">
        <view class="today-bar-fill" :style="{ width: Math.min(100, (todayStats.credited / 3) * 100) + '%' }"></view>
      </view>
      <text class="today-hint">每日最多 3 次有效引力值，分享给朋友圈可获更多</text>
    </view>

    <!-- 分享按钮 -->
    <view class="share-actions">
      <!-- #ifdef MP-WEIXIN -->
      <view class="share-btn-row">
        <button class="share-btn wx-share" open-type="share">
          <text class="btn-icon">💬</text>
          <text>分享给好友</text>
        </button>
        <view class="share-btn wx-timeline-hint" @click="showTimelineHint">
          <text class="btn-icon">🔄</text>
          <text>分享朋友圈</text>
        </view>
      </view>
      <!-- #endif -->
      <!-- #ifdef H5 -->
      <view class="share-btn-row">
        <button class="share-btn wx-share" @click="shareToWechat" v-if="isWechat">
          <text class="btn-icon">💬</text>
          <text>分享给微信好友</text>
        </button>
        <button class="share-btn wx-timeline" @click="shareToWechat" v-if="isWechat">
          <text class="btn-icon">🔄</text>
          <text>分享朋友圈</text>
        </button>
      </view>
      <!-- #endif -->
      <view class="share-btn-row">
        <button class="share-btn link-share" @click="copyLink">
          <text class="btn-icon">🔗</text>
          <text>复制分享链接</text>
        </button>
      </view>
    </view>

    <!-- Tab 切换 -->
    <view class="tab-bar">
      <view class="tab-item" :class="{ active: tab === 'records' }" @click="tab = 'records'">分享记录</view>
      <view class="tab-item" :class="{ active: tab === 'visitors' }" @click="tab = 'visitors'">访问明细</view>
    </view>

    <!-- 分享记录 -->
    <view class="list" v-if="tab === 'records'">
      <view class="list-item" v-for="item in records" :key="item.shareCode">
        <view class="item-main">
          <text class="item-type">{{ typeLabel(item.type) }}</text>
          <text class="item-title">{{ item.title }}</text>
        </view>
        <view class="item-stats">
          <text class="item-stat">👀 {{ item.visitCount }}点击</text>
          <text class="item-stat active">✅ {{ item.creditedCount }}有效</text>
        </view>
        <text class="item-time">{{ formatTime(item.createdAt) }}</text>
      </view>
      <view class="empty" v-if="records.length === 0">
        <text class="empty-icon">📤</text>
        <text class="empty-text">还没有分享记录</text>
        <text class="empty-hint">点击上方按钮分享给好友吧</text>
      </view>
    </view>

    <!-- 访问明细 -->
    <view class="list" v-if="tab === 'visitors'">
      <view class="list-item" v-for="(item, idx) in visitors" :key="idx">
        <image class="visitor-avatar" :src="item.avatar || '/static/avatar-default.svg'" />
        <view class="item-main">
          <text class="item-title">{{ item.nickname || '👤 未登录访客' }}</text>
          <text class="item-time">{{ formatTime(item.createdAt) }}</text>
        </view>
        <view class="badge" :class="item.credited ? 'badge-done' : 'badge-pending'">
          {{ item.credited ? '✅ 已积分' : '⏳ 未注册' }}
        </view>
      </view>
      <view class="empty" v-if="visitors.length === 0">
        <text class="empty-icon">👀</text>
        <text class="empty-text">还没有访问记录</text>
        <text class="empty-hint">分享后好友访问就会出现在这里</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
// #ifdef MP-WEIXIN
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
// #endif
import { api } from '../../config'

const tab = ref('records')
const stats = ref({ totalShares: 0, totalVisits: 0, creditedCount: 0, todayCredited: 0, shareCredits: 0, gravity: 0 })
const shareLink = ref('')
const shareUrlCached = ref('')
const records = ref([])
const visitors = ref([])

const todayStats = computed(() => ({
  visits: stats.value.todayCredited + Math.round(Math.random() * 0),
  credited: stats.value.todayCredited || 0,
}))

const isWechat = ref(false)

// #ifdef MP-WEIXIN
onShareAppMessage(() => ({
  title: 'AI磁场·职引 — AI模拟面试+简历优化',
  path: '/pages/share/share',
  imageUrl: 'https://zhiyinwx.yzrcloud.cn/static/share-card.png',
}))
onShareTimeline(() => ({
  title: 'AI磁场·职引 — AI模拟面试+简历优化',
  imageUrl: 'https://zhiyinwx.yzrcloud.cn/static/share-card.png',
}))
// #endif

onMounted(() => {
  // #ifdef H5
  isWechat.value = navigator?.userAgent?.toLowerCase().includes('micromessenger') || false
  // #endif
  loadData()
})

async function loadData() {
  const token = uni.getStorageSync('token')
  if (!token) { uni.showToast({ title: '请先登录', icon: 'none' }); return }
  const header = { Authorization: `Bearer ${token}` }

  // 仅在无缓存分享链接时创建新分享记录
  if (!shareUrlCached.value) {
    try {
      const res = await uni.request({
        url: api('/share/create'), method: 'POST',
        data: { type: 'app', title: '我在AI磁场·职引练习面试', description: 'AI模拟面试+简历优化，快来一起提升吧' },
        header,
      })
      if (res.statusCode >= 200 && res.statusCode < 300) {
        const data = res.data?.data || res.data
        if (data.shareCode) {
          shareUrlCached.value = `https://zhiyinwx.yzrcloud.cn/api/share/${data.shareCode}`
        }
      }
    } catch (e) { /* create share is best-effort */ }
  }

  try {
    const [statsRes, recordsRes, visitorsRes] = await Promise.all([
      uni.request({ url: api('/share/stats'), method: 'GET', header }),
      uni.request({ url: api('/share/records'), method: 'GET', header }),
      uni.request({ url: api('/share/visitors'), method: 'GET', header }),
    ])
    if (statsRes.statusCode === 200) stats.value = statsRes.data
    if (recordsRes.statusCode === 200) records.value = recordsRes.data.list || []
    if (visitorsRes.statusCode === 200) visitors.value = visitorsRes.data.list || []
  } catch (e) { console.error(e) }
}

async function shareToWechat() {
  const token = uni.getStorageSync('token')
  if (!token) return

  try {
    const res = await uni.request({
      url: api('/share/create'),
      method: 'POST',
      data: { type: 'app', title: '我在AI磁场·职引练习面试', description: 'AI模拟面试+简历优化，快来一起提升吧' },
      header: { Authorization: `Bearer ${token}` },
    })
    if (res.statusCode < 200 || res.statusCode >= 300) return

    const data = res.data
    const path = data.wechatShareInfo?.path || `/pages/share/share?code=${data.shareCode}`

    uni.shareAppMessage({
      provider: 'weixin',
      title: data.wechatShareInfo?.title || 'AI磁场·职引',
      description: data.wechatShareInfo?.description || '',
      path,
      imageUrl: 'https://zhiyinwx.yzrcloud.cn/static/share-card.png',
      success: () => { uni.showToast({ title: '分享成功', icon: 'success' }); loadData() },
      fail: () => { uni.showToast({ title: '分享取消', icon: 'none' }) },
    })
  } catch (e) { console.error(e) }
}

async function copyLink() {
  const token = uni.getStorageSync('token')
  if (!token) { uni.showToast({ title: '请先登录', icon: 'none' }); return }

  if (shareUrlCached.value) {
    // 使用已缓存的分享链接，避免二次 API 调用
    uni.setClipboardData({
      data: shareUrlCached.value,
      success: () => { uni.showToast({ title: '链接已复制' }); loadData() },
      fail: () => { uni.showToast({ title: '复制失败，请长按选择复制', icon: 'none' }) },
    })
    return
  }

  // 缓存未命中时兜底：调 API 生成
  try {
    const res = await uni.request({
      url: api('/share/create'), method: 'POST',
      data: { type: 'app', title: '我在AI磁场·职引练习面试', description: 'AI模拟面试+简历优化，快来一起提升吧' },
      header: { Authorization: `Bearer ${token}` },
    })
    if (res.statusCode < 200 || res.statusCode >= 300) {
      uni.showToast({ title: `创建失败(${res.statusCode})，请重试`, icon: 'none' })
      return
    }
    const data = res.data?.data || res.data
    if (!data.shareCode) {
      uni.showToast({ title: '返回数据异常，请重试', icon: 'none' })
      return
    }
    const shareUrl = `https://zhiyinwx.yzrcloud.cn/api/share/${data.shareCode}`
    shareUrlCached.value = shareUrl
    uni.setClipboardData({
      data: shareUrl,
      success: () => { uni.showToast({ title: '链接已复制' }); loadData() },
      fail: () => { uni.showToast({ title: '复制失败，请长按选择复制', icon: 'none' }) },
    })
  } catch (e) {
    console.error('[share] copyLink error:', e)
    uni.showToast({ title: '网络错误，请重试', icon: 'none' })
  }
}

function showTimelineHint() {
  uni.showToast({ title: '请点击右上角 ··· 选择分享到朋友圈', icon: 'none', duration: 3000 })
}

function typeLabel(type) {
  const map = { app: '应用', interview: '面试', resume: '简历' }
  return map[type] || type
}

function formatTime(t) {
  if (!t) return ''
  const d = new Date(t)
  return `${d.getMonth() + 1}/${d.getDate()} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}
</script>

<style scoped>
.page { min-height: 100vh; background: var(--color-bg); padding-bottom: 48rpx; }

/* Stats card */
.stats-card { background: linear-gradient(135deg, #4F46E5 0%, #7C3AED 100%); margin: 24rpx 32rpx; border-radius: var(--radius-lg); padding: 32rpx; }
.stat-row { display: flex; justify-content: center; margin-bottom: 20rpx; }
.stat-item { display: flex; flex-direction: column; align-items: center; }
.stat-value { font-size: 56rpx; font-weight: 800; color: #FFFFFF; }
.stat-label { font-size: 22rpx; color: rgba(255,255,255,0.75); margin-top: 6rpx; }

.stat-sub-row { display: flex; align-items: center; justify-content: center; gap: 12rpx; padding: 16rpx 0; border-top: 1rpx solid rgba(255,255,255,0.15); border-bottom: 1rpx solid rgba(255,255,255,0.15); margin-bottom: 16rpx; }
.stat-sub-item { display: flex; flex-direction: column; align-items: center; }
.stat-sub-value { font-size: 32rpx; font-weight: 700; color: #FFFFFF; }
.stat-sub-label { font-size: 18rpx; color: rgba(255,255,255,0.6); margin-top: 4rpx; }
.stat-arrow { font-size: 24rpx; color: rgba(255,255,255,0.4); }
.hint { font-size: 20rpx; color: rgba(255,255,255,0.7); text-align: center; line-height: 1.6; }
.hint-em { color: #FCD34D; font-weight: 600; }

/* Today card */
.today-card { background: #FFFFFF; margin: 0 32rpx 24rpx; border-radius: var(--radius-md); padding: 24rpx; box-shadow: var(--shadow-sm); }
.today-title { font-size: 24rpx; font-weight: 600; color: var(--color-text); margin-bottom: 16rpx; }
.today-row { display: flex; gap: 24rpx; margin-bottom: 16rpx; }
.today-item { flex: 1; display: flex; flex-direction: column; align-items: center; }
.today-value { font-size: 36rpx; font-weight: 700; color: var(--color-primary); }
.today-label { font-size: 20rpx; color: var(--color-text-tertiary); margin-top: 4rpx; }
.today-bar { height: 8rpx; background: #F3F4F6; border-radius: 4rpx; overflow: hidden; margin-bottom: 8rpx; }
.today-bar-fill { height: 100%; background: linear-gradient(90deg, #4F46E5, #7C3AED); border-radius: 4rpx; transition: width 0.3s; }
.today-hint { font-size: 18rpx; color: var(--color-text-tertiary); text-align: center; }

/* Share buttons */
.share-actions { padding: 0 32rpx; display: flex; flex-direction: column; gap: 16rpx; }
.share-btn-row { display: flex; gap: 20rpx; }
.share-btn {
  flex: 1; display: flex; align-items: center; justify-content: center; height: 88rpx; border-radius: var(--radius-md);
  font-size: 26rpx; font-weight: 500; border: none; padding: 0; white-space: nowrap;
}
.share-btn:active { transform: scale(0.96); }
.btn-icon { margin-right: 8rpx; font-size: 28rpx; }
.wx-share { background: #07C160; color: #FFFFFF; }
.wx-timeline { background: #FF6600; color: #FFFFFF; }
.wx-timeline-hint { flex: 1; display: flex; align-items: center; justify-content: center; height: 88rpx; border-radius: var(--radius-md); font-size: 26rpx; font-weight: 500; background: #FF6600; color: #FFFFFF; white-space: nowrap; }
.wx-timeline-hint:active { transform: scale(0.96); }
.link-share { background: #FFFFFF; color: var(--color-text); border: 2rpx solid var(--color-border); }

/* Tabs */
.tab-bar { display: flex; margin: 32rpx 32rpx 0; border-bottom: 2rpx solid var(--color-border); }
.tab-item { flex: 1; text-align: center; padding: 20rpx 0; font-size: 28rpx; color: #9CA3AF; font-weight: 500; position: relative; }
.tab-item.active { color: var(--color-primary); }
.tab-item.active::after { content: ''; position: absolute; bottom: -2rpx; left: 30%; right: 30%; height: 4rpx; background: var(--color-primary); border-radius: 2rpx; }

/* List */
.list { padding: 0 32rpx; }
.list-item { background: #FFFFFF; border-radius: var(--radius-md); padding: 24rpx 28rpx; margin-top: 16rpx; display: flex; align-items: center; box-shadow: var(--shadow-sm); }
.item-main { flex: 1; display: flex; flex-direction: column; }
.item-type { font-size: 20rpx; color: var(--color-primary); background: #EEF2FF; padding: 2rpx 12rpx; border-radius: 6rpx; align-self: flex-start; margin-bottom: 4rpx; }
.item-title { font-size: 26rpx; color: var(--color-text); font-weight: 500; }
.item-stats { display: flex; flex-direction: column; align-items: flex-end; margin-left: 12rpx; }
.item-stat { font-size: 22rpx; color: #9CA3AF; white-space: nowrap; }
.item-stat.active { color: var(--color-primary); }
.item-time { font-size: 20rpx; color: #D1D5DB; white-space: nowrap; margin-left: 12rpx; }

.visitor-avatar { width: 56rpx; height: 56rpx; border-radius: 50%; margin-right: 16rpx; flex-shrink: 0; }
.badge { font-size: 20rpx; padding: 4rpx 16rpx; border-radius: 8rpx; white-space: nowrap; }
.badge-done { background: #ECFDF5; color: #059669; }
.badge-pending { background: #FEF3C7; color: #D97706; }

/* Empty state */
.empty { display: flex; flex-direction: column; align-items: center; padding: 80rpx 0; }
.empty-icon { font-size: 64rpx; margin-bottom: 16rpx; }
.empty-text { font-size: 28rpx; color: #9CA3AF; }
.empty-hint { font-size: 24rpx; color: #D1D5DB; margin-top: 8rpx; }
</style>
