<script setup>
import { computed } from 'vue'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'

import styles from './RecentLinks.module.scss'

const props = defineProps({
  links: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['open', 'edit'])

const items = computed(() => props.links.slice(0, 10))

function faviconUrl(url, icon) {
  if (icon) return icon
  try {
    const { origin } = new URL(url)
    return `https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${encodeURIComponent(
      origin
    )}&size=24`
  } catch {
    return ''
  }
}

function fallbackInitial(title) {
  return title ? title[0]?.toUpperCase() ?? 'B' : 'B'
}

function visitLabel(link) {
  if (!link.lastVisitTime) return '尚未访问'
  try {
    return formatDistanceToNow(new Date(link.lastVisitTime), { addSuffix: true, locale: zhCN })
  } catch {
    return '最近'
  }
}
</script>

<template>
  <div>
    <div v-if="items.length" :class="styles.list">
      <div
        v-for="item in items"
        :key="item.id"
        :class="styles.item"
        role="button"
        tabindex="0"
        @click="emit('open', item)"
        @keyup.enter="emit('open', item)"
      >
        <div :class="styles.icon">
          <img v-if="faviconUrl(item.url, item.icon)" :src="faviconUrl(item.url, item.icon)" alt="" />
          <span v-else>{{ fallbackInitial(item.title) }}</span>
        </div>
        <div :class="styles.info">
          <h4 :class="styles.title">{{ item.title }}</h4>
          <div :class="styles.meta">
            <span>{{ visitLabel(item) }}</span>
            <el-button type="text" size="small" @click.stop="emit('edit', item)">编辑</el-button>
          </div>
          <div v-if="item.tags?.length" :class="styles.tags">
            <span v-for="tag in item.tags.slice(0, 4)" :key="`${item.id}-${tag}`" :class="styles.tag">{{ tag }}</span>
          </div>
        </div>
      </div>
    </div>
    <el-empty v-else description="暂无访问记录。" />
  </div>
</template>

