<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { NBadge, NButton, NPopover, NList, NListItem, NEmpty } from 'naive-ui'
import { RouterLink } from 'vue-router'
import { api } from '../../api/client'
import type { NotificationItem } from '../../types'
import { useToast } from '../../composables/useToast'
import { toBeijingDateTime } from '../../utils/date'

const toast = useToast()
const unread = ref(0)
const items = ref<NotificationItem[]>([])
const showPopover = ref(false)
let intervalId: ReturnType<typeof setInterval> | null = null

onMounted(() => {
  loadNotifications()
  intervalId = setInterval(loadNotifications, 60000)
})
onUnmounted(() => { if (intervalId) clearInterval(intervalId) })

async function loadNotifications() {
  try {
    const { data } = await api.get('/notifications')
    items.value = (data.items || []).slice(0, 10)
    unread.value = data.unread || items.value.filter((i: NotificationItem) => !i.is_read).length
  } catch (e) { toast.apiError(e, "加载通知失败") }
}

async function markRead(nid: string) {
  try { await api.post(`/notifications/${nid}/read`); unread.value = Math.max(0, unread.value - 1) } catch (e) { toast.apiError(e, "标记已读失败") }
}

function handlePopoverShow(show: boolean) { if (show) loadNotifications() }
</script>

<template>
  <NPopover v-model:show="showPopover" trigger="click" placement="bottom-end" @update:show="handlePopoverShow" style="max-width:360px">
    <template #trigger>
      <NButton text size="small" style="color:inherit" title="通知">
        <NBadge :value="unread" :max="99" :show="unread > 0" :offset="[-2, 4]">
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 01-3.46 0"/></svg>
        </NBadge>
      </NButton>
    </template>

    <div style="width:320px">
      <NList size="small" v-if="items.length">
        <NListItem v-for="n in items.slice(0,8)" :key="n.id"
                   :style="n.is_read ? {} : { background: 'var(--kw-pill-bg)' }"
                   @click="markRead(n.id)">
          <div style="font-size:13px;font-weight:500">{{ n.title }}</div>
          <div style="font-size:12px;color:var(--text-muted);margin-top:2px">{{ n.content?.slice(0,40) || '' }}</div>
          <div style="font-size:10px;color:var(--text-muted);margin-top:2px">{{ toBeijingDateTime(n.created_at) }}</div>
        </NListItem>
      </NList>
      <NEmpty v-else description="暂无通知" style="padding:16px" />
      <div style="text-align:center;border-top:1px solid var(--border-color);padding:6px 0">
        <router-link to="/app/notifications" @click="showPopover = false" style="font-size:12px;color:var(--kw-pill-color);text-decoration:none">查看全部 →</router-link>
      </div>
    </div>
  </NPopover>
</template>
