<template>
  <div :class="containerClass">
    <!-- 收藏按钮 -->
    <button 
      class="action-btn like-btn" 
      :class="{ liked: isLiked }"
      @click.stop="handleToggleLike" 
      :title="isLiked ? t('Unlike') : t('Like')"
      :disabled="likeLoading"
    >
      <i :class="isLiked ? 'fas fa-heart' : 'far fa-heart'"></i>
    </button>
    <!-- 操作按钮 -->
    <button 
      class="action-btn" 
      @click.stop="handleView" 
      :title="t('View')"
      :disabled="!canRead"
      :class="{ disabled: !canRead }"
    >
      <i class="fa fa-eye"></i>
    </button>
    <button 
      class="action-btn" 
      @click.stop="handleEdit" 
      :title="t('Edit')"
      :disabled="!canWrite"
      :class="{ disabled: !canWrite }"
    >
      <i class="fa fa-edit"></i>
    </button>
    <button 
      class="action-btn delete-btn" 
      @click.stop="handleDelete" 
      :title="t('Delete')"
      :disabled="!canDelete"
      :class="{ disabled: !canDelete }"
    >
      <i class="fa fa-trash"></i>
    </button>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { t } from '@/shared/i18n'
import { toggleLike as toggleLikeApi } from '@/shared/api/timeline'
import { useAuthStore } from '@/shared/stores/auth'

interface Props {
  row: any
  entity: string
  viewMode?: 'card' | 'list'
}

interface Emits {
  (e: 'view', row: any): void
  (e: 'edit', row: any): void
  (e: 'delete', row: any): void
  (e: 'like-toggled'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const authStore = useAuthStore()
const likeLoading = ref(false)

// 权限检查（后端 _can_delete 已根据 if_owner 等约束计算）
const canRead = computed(() => props.row._can_read === 1 || props.row._can_read === undefined)
const canWrite = computed(() => props.row._can_write === 1 || props.row._can_write === undefined)
const canDelete = computed(() => props.row._can_delete === 1 || props.row._can_delete === undefined)

// Like state
const currentUser = computed(() => authStore.user?.username || authStore.user?.name || '')
const likedBy = computed<string[]>(() => {
  const raw = props.row?._liked_by
  if (!raw) return []
  if (typeof raw === 'string') { try { return JSON.parse(raw) } catch { return [] } }
  return Array.isArray(raw) ? raw : []
})
const isLiked = computed(() => likedBy.value.includes(currentUser.value))

async function handleToggleLike() {
  if (likeLoading.value) return
  likeLoading.value = true
  try {
    await toggleLikeApi(props.entity, props.row.name, isLiked.value ? 'No' : 'Yes')
    // Optimistic update: toggle _liked_by locally
    const list = [...likedBy.value]
    if (isLiked.value) {
      const idx = list.indexOf(currentUser.value)
      if (idx >= 0) list.splice(idx, 1)
    } else {
      if (!list.includes(currentUser.value)) list.push(currentUser.value)
    }
    props.row._liked_by = JSON.stringify(list)
    emit('like-toggled')
  } catch {
    // Silently fail for list view like toggle
  } finally {
    likeLoading.value = false
  }
}

// 根据视图模式决定容器类名，组件自包含所有样式
const containerClass = computed(() => {
  return props.viewMode === 'card' ? 'actions-container card-actions' : 'actions-container col-actions'
})

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

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

function handleDelete() {
  emit('delete', props.row)
}
</script>

<style scoped>
/* 操作按钮容器基础样式 */
.actions-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

/* 卡片视图样式：包含 footer 外观（padding, border-top, background） */
.card-actions {
  padding: 8px 16px;
  border-top: 1px solid #f3f4f6;
  background: #fafbfc;
  margin-top: auto;
}

/* 列表视图样式：只提供按钮排列，无背景（通过 actions-container 基础样式实现） */

/* 操作按钮通用样式 - 统一使用节点列表页的大小 */
.action-btn { 
  width: 28px; 
  height: 28px; 
  border: none; 
  background: #f3f4f6; 
  color: #6b7280; 
  border-radius: 6px; 
  cursor: pointer; 
  display: flex; 
  align-items: center; 
  justify-content: center; 
  font-size: 12px; 
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); 
}

.action-btn:hover { 
  background: #3b82f6; 
  color: white; 
}

.action-btn.delete-btn:hover {
  background: #ef4444;
  color: white; 
}

/* Like 按钮已收藏状态 */
.action-btn.like-btn.liked {
  color: #ef4444;
  background: #fef2f2;
}

.action-btn.like-btn.liked:hover {
  background: #fecaca;
  color: #ef4444;
}

/* 禁用状态 */
.action-btn:disabled,
.action-btn.disabled {
  opacity: 0.4;
  cursor: not-allowed;
  pointer-events: none;
}
</style>
