<script setup>
import { computed, onMounted, nextTick, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Link, View, Edit, DocumentCopy, Delete } from '@element-plus/icons-vue'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'

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

const props = defineProps({
  link: {
    type: Object,
    required: true,
  }
})

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

import defaultIcon from '@/assets/images/default.png'

const faviconUrl = computed(() => {
  if (props.link.icon) return props.link.icon
  if (!props.link.url) return defaultIcon
  try {
    const { origin } = new URL(props.link.url)
    // 使用本地占位图标，避免外部favicon加载失败
    return origin;
  } catch {
    return defaultIcon
  }
})

const fallbackInitial = computed(() => {
  if (props.link.title) {
    const first = props.link.title.trim()[0]
    return first ? first.toUpperCase() : 'B'
  }
  return 'B'
})

const visitSummary = computed(() => {
  const count = props.link.visitCount ?? 0
  const lastVisit = props.link.lastVisitTime ? new Date(props.link.lastVisitTime) : null
  const visitLabel = '次访问'
  if (!lastVisit) return `共 ${count} ${visitLabel}`
  return `共 ${count} ${visitLabel} · ${formatDistanceToNow(lastVisit, { addSuffix: true, locale: zhCN })}`
})

const createdLabel = computed(() => {
  if (!props.link.createdAt) return ''
  try {
    return `添加于 ${formatDistanceToNow(new Date(props.link.createdAt), { addSuffix: true, locale: zhCN })}`
  } catch {
    return ''
  }
})

function handleOpen() {
  emit('open', props.link)
}

function handleEdit() {
  emit('edit', props.link)
}

function handleRemove() {
  emit('remove', props.link)
}

function handleView() {
  emit('view', props.link)
}

async function handleCopy() {
  const url = props.link.url
  if (!url) {
    ElMessage.warning('当前链接没有可复制的地址')
    return
  }

  try {
    if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
      await navigator.clipboard.writeText(url)
    } else if (typeof document !== 'undefined') {
      const textarea = document.createElement('textarea')
      textarea.value = url
      textarea.setAttribute('readonly', '')
      textarea.style.position = 'absolute'
      textarea.style.left = '-9999px'
      document.body.appendChild(textarea)
      const selection = document.getSelection()
      const selectedRange = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null
      textarea.select()
      const successful = document.execCommand('copy')
      document.body.removeChild(textarea)
      if (selectedRange && selection) {
        selection.removeAllRanges()
        selection.addRange(selectedRange)
      }
      if (!successful) throw new Error('execCommand copy failed')
    } else {
      throw new Error('Clipboard API 不可用')
    }
    ElMessage.success('链接地址已复制')
  } catch (error) {
    console.error(error)
    ElMessage.error('复制失败，请稍后再试')
  }
}

function handleCommand(command) {
  switch (command) {
    case 'open':
      handleOpen()
      break
    case 'view':
      handleView()
      break
    case 'edit':
      handleEdit()
      break
    case 'copy':
      handleCopy()
      break
    case 'remove':
      handleRemove()
      break
  }
}

// #region agent log
const cardRef = ref(null)
onMounted(() => {
  nextTick(() => {
    const cardEl = cardRef.value
    if (!cardEl) return
    
    const rect = cardEl.getBoundingClientRect()
    const computedStyle = window.getComputedStyle(cardEl)
    const titleEl = cardEl.querySelector('h3')
    const descEl = cardEl.querySelector('p')
    
    fetch('http://127.0.0.1:7242/ingest/f96150ac-89c4-4b8b-bead-0078442f7ecb', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        location: 'LinkCard.vue:onMounted',
        message: 'Card content measurement',
        data: {
          linkId: props.link.id,
          title: props.link.title,
          titleLength: props.link.title?.length || 0,
          hasDescription: !!props.link.description,
          descriptionLength: props.link.description?.length || 0,
          cardWidth: rect.width,
          cardHeight: rect.height,
          cardPadding: computedStyle.padding,
          cardBorder: computedStyle.borderWidth,
          cardBoxSizing: computedStyle.boxSizing,
          titleWidth: titleEl?.getBoundingClientRect().width || null,
          titleText: titleEl?.textContent || null,
          descWidth: descEl?.getBoundingClientRect().width || null
        },
        timestamp: Date.now(),
        sessionId: 'debug-session',
        runId: 'run1',
        hypothesisId: 'A,C,D'
      })
    }).catch(() => {})
  })
})
// #endregion
</script>

<template>
  <el-dropdown
    trigger="contextmenu"
    :teleported="true"
    @command="handleCommand"
  >
    <article 
      ref="cardRef"
      :class="styles.card"
      :data-link-id="link.id"
      @dblclick="handleView"
    >
      <div :class="styles.cardHeader">
        <div :class="styles.icon" aria-hidden="true">
          <img 
            v-if="faviconUrl" 
            :src="faviconUrl" 
            alt="" 
            @error="$event.target.src = defaultIcon"
          />
          <span v-else>{{ fallbackInitial }}</span>
        </div>
        <h3 :class="styles.title">{{ link.title }}</h3>
      </div>

      <p v-if="link.description" :class="styles.description">{{ link.description }}</p>
    </article>

    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="open">
          <el-icon><Link /></el-icon>
          <span>打开链接</span>
        </el-dropdown-item>
        <el-dropdown-item command="view">
          <el-icon><View /></el-icon>
          <span>查看</span>
        </el-dropdown-item>
        <el-dropdown-item command="edit">
          <el-icon><Edit /></el-icon>
          <span>编辑</span>
        </el-dropdown-item>
        <el-dropdown-item command="copy">
          <el-icon><DocumentCopy /></el-icon>
          <span>复制地址</span>
        </el-dropdown-item>
        <el-dropdown-item divided command="remove" class="danger-item">
          <el-icon><Delete /></el-icon>
          <span>删除</span>
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

