<template>
  <div class="my-wishes-page with-bottom-nav">
    <van-nav-bar title="我的愿望" />

    <div v-if="!userStore.isLoggedIn" class="no-login">
      <van-empty description="请先登录查看你的愿望">
        <van-button type="primary" round to="/login">去登录</van-button>
      </van-empty>
    </div>

    <template v-else>
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="loadWishes"
        >
          <wish-card
            v-for="wish in wishes"
            :key="wish.id"
            :wish="wish"
            @click="goWish(wish.id)"
          />
        </van-list>
      </van-pull-refresh>

      <van-empty v-if="!loading && wishes.length === 0" description="你还没有许过愿望哦">
        <van-button type="primary" round to="/">去许愿</van-button>
      </van-empty>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { fetchMyWishes } from '@/api/wish'
import WishCard from '@/components/WishCard.vue'
import type { Wish } from '@/mock/data'

const router = useRouter()
const userStore = useUserStore()

const wishes = ref<Wish[]>([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
let page = 1

async function loadWishes() {
  loading.value = true
  try {
    const result = await fetchMyWishes(page, 20)
    if (refreshing.value) {
      wishes.value = result.list
    } else {
      wishes.value = [...wishes.value, ...result.list]
    }
    finished.value = result.list.length < 20
    page++
  } catch {
    finished.value = true
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

async function onRefresh() {
  refreshing.value = true
  page = 1
  finished.value = false
  await loadWishes()
}

function goWish(id: number) {
  router.push(`/wish/${id}`)
}
</script>

<style scoped>
.my-wishes-page {
  min-height: 100vh;
  background: #f7f8fa;
}
.no-login {
  padding-top: 60px;
}
</style>
