<template>
  <scroll-view scroll-y class="messages-scroll" @scrolltolower="loadMore">
    <view :class="['messages-page', elderClass]">
      <GuestGuard>
        <text class="page-title">消息</text>

        <!-- 消息列表 -->
        <Loading v-if="loading && messages.length === 0" text="加载中..." />
        <EmptyState v-else-if="messages.length === 0" icon="📭" title="暂无消息" />
        <template v-else>
          <view v-for="msg in messages" :key="msg.id" class="msg-card" @tap="goDetail(msg)">
            <text class="msg-title">{{ msg.title }}</text>
            <text class="msg-content">{{ msg.content }}</text>
            <text class="msg-time">{{ getRelativeTime(msg.created_at) }}</text>
          </view>
        </template>
      </GuestGuard>
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useAuthStore } from '@/stores/auth'
import { useElderClass } from '@/composables/useElderClass'
import { notificationService } from '@/services/notification'
import { getRelativeTime } from '@/utils/date'
import Loading from '@/components/Loading.vue'
import EmptyState from '@/components/EmptyState.vue'
import GuestGuard from '@/components/GuestGuard.vue'

const authStore = useAuthStore()
const { elderClass } = useElderClass()

const loading = ref(false)
const messages = ref<any[]>([])
const page = ref(1)

async function fetchMessages() {
  loading.value = true
  try {
    const res = await notificationService.list({ page: page.value, page_size: 20 })
    messages.value = res || []
  } catch {
    messages.value = []
  }
  loading.value = false
}

function loadMore() {
  page.value++
  fetchMessages()
}

function goDetail(msg: any) {
  if (msg.type === 'consultation') {
    uni.navigateTo({ url: `/pages-sub/consultation/detail/index?id=${msg.ref_id}` })
  }
}

onMounted(fetchMessages)
onShow(() => { authStore.restore() })
</script>

<style lang="scss" scoped>
.messages-scroll {
  height: 100vh;
  background: $bg;
}

.messages-page {
  padding: 28px 24px 120px;
}

.page-title {
  @include section-title;
}

.msg-card {
  background: $card;
  border-radius: $r;
  padding: 20px 24px;
  margin-bottom: 16px;
  box-shadow: $shadow-sm;
}

.msg-title {
  display: block;
  font-size: var(--tk-font-body);
  font-weight: 600;
  color: $tx;
  margin-bottom: 8px;
}

.msg-content {
  display: block;
  font-size: var(--tk-font-body-sm);
  color: $tx2;
  margin-bottom: 8px;
}

.msg-time {
  display: block;
  font-size: var(--tk-font-cap);
  color: $tx3;
}
</style>
