<!-- 常用功能收藏:星标收藏当前页,弹窗展示收藏列表快速跳转 -->
<template>
  <ElPopover
    :width="360"
    :show-arrow="false"
    trigger="click"
    placement="bottom-end"
    popper-class="favorites-popover"
  >
    <template #reference>
      <div class="c-p mx-1 flex-cc rounded p-2 text-lg hover:bg-g-200/70 dark:hover:bg-g-200/90" title="收藏">
        <ArtSvgIcon :icon="isCurrentFavorite ? 'ri:star-fill' : 'ri:star-line'" class="text-xl" :style="{ color: isCurrentFavorite ? '#f7ba1e' : '' }" />
      </div>
    </template>

    <div>
      <div class="mb-2 flex items-center justify-between">
        <h3 class="text-sm font-medium">我的收藏</h3>
        <ElButton link type="primary" size="small" :disabled="isCurrentFavorite" @click="addCurrent">收藏当前页</ElButton>
      </div>
      <ul v-if="favorites.length" class="max-h-72 space-y-1 overflow-y-auto">
        <li v-for="item in favorites" :key="item.path" class="c-p flex items-center justify-between rounded px-2 py-1.5 hover:bg-g-200/70 dark:hover:bg-g-200/90" @click="go(item)">
          <span class="text-sm">{{ item.title }}</span>
          <ElButton link type="danger" size="small" @click.stop="remove(item.path)">删除</ElButton>
        </li>
      </ul>
      <div v-else class="py-6 text-center text-sm text-g-400">暂无收藏,点击右上角星标收藏常用页面</div>
    </div>
  </ElPopover>
</template>

<script setup lang="ts">
  import { useRoute, useRouter } from 'vue-router'

  interface Favorite {
    title: string
    path: string
  }

  const STORAGE_KEY = 'gateway-favorites'
  const route = useRoute()
  const router = useRouter()
  const favorites = ref<Favorite[]>(load())

  const currentPath = computed(() => route.path)
  const currentTitle = computed(() => {
    const meta = (route.meta as Record<string, any>) || {}
    return typeof meta.title === 'string' ? meta.title : route.name?.toString() || route.path
  })
  const isCurrentFavorite = computed(() => favorites.value.some((item) => item.path === currentPath.value))

  function load(): Favorite[] {
    try {
      const raw = localStorage.getItem(STORAGE_KEY)
      const parsed = raw ? JSON.parse(raw) : []
      return Array.isArray(parsed) ? parsed.filter((item) => item && typeof item.path === 'string') : []
    } catch {
      return []
    }
  }

  function persist() {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(favorites.value.slice(0, 50)))
  }

  function addCurrent() {
    if (isCurrentFavorite.value) return
    favorites.value.unshift({ title: currentTitle.value, path: currentPath.value })
    persist()
  }

  function remove(path: string) {
    favorites.value = favorites.value.filter((item) => item.path !== path)
    persist()
  }

  function go(item: Favorite) {
    router.push(item.path)
  }
</script>
