<template>
  <div
    class="card"
    :draggable="!isMobile && canMove"
    @dragstart="handleDragStart"
    @dragend="handleDragEnd"
    @touchstart="handleTouchStart"
    @touchend="handleTouchEnd"
    @touchmove="handleTouchMove"
    @mousedown="handleMouseDown"
    @mouseup="handleMouseUp"
    @mouseleave="handleMouseLeave"
    @contextmenu="handleContextMenu"
    :class="{ dragging: isDragging, 'has-label-color': cardLabelColor, 'long-pressing': isLongPressing, 'no-move': !canMove }"
    :style="cardLabelColor ? { '--label-bg': cardLabelColor } : {}"
  >
    <div class="card-header">
      <div class="tag-group">
        <span v-if="cardLabel" class="label-icon">{{ cardLabel.icon }}</span>
        <span 
          v-if="cardDepartment" 
          class="tag"
          :style="{ color: cardDepartment.color }"
        >
          {{ cardDepartment.name_departments }}
        </span>
        <!-- Индикаторы ограничений прав -->
        <div v-if="!canEdit || !canMove" class="permissions-indicators">
          <span 
            v-if="!canEdit" 
            class="perm-icon no-edit" 
            title="Нет прав на редактирование"
          >
            <i data-lucide="pencil-off"></i>
          </span>
          <span 
            v-if="!canMove" 
            class="perm-icon no-move-icon" 
            title="Нет прав на перемещение"
          >
            <i data-lucide="lock"></i>
          </span>
        </div>
      </div>
      <div class="header-right">
        <button 
          v-if="canArchive" 
          class="btn-archive-card" 
          :class="{ 'always-visible': isMobile }"
          @click.stop="handleArchive"
          title="В архив"
        >
          <i data-lucide="archive"></i>
        </button>
        <span v-if="card.comments_count" class="comments-indicator" :title="card.comments_count + ' комментариев'">
          <i data-lucide="message-circle"></i>
          <span class="indicator-count">{{ card.comments_count }}</span>
        </span>
        <span v-if="card.files && card.files.length" class="files-indicator" :title="card.files.length + ' изображений'">
          <i data-lucide="image-plus"></i>
        </span>
        <div v-if="card.assignee" class="assignee">
          <img 
            v-if="isAvatarUrl(card.assignee)" 
            :src="getFullUrl(card.assignee)" 
            alt="avatar"
            class="assignee-img"
          />
          <span v-else>{{ card.assignee }}</span>
        </div>
      </div>
    </div>

    <h3 class="card-title">{{ card.title }}</h3>
    
    <p v-if="card.description" class="card-description">
      {{ card.description }}
    </p>

    <div class="card-footer">
      <span v-if="card.dateCreate" class="date-create">
        Создано: {{ formatShort(card.dateCreate) }}
      </span>
      <span v-if="card.dueDate && Number(columnId) !== store.doneColumnId" class="due-date" :class="dueDateStatus">
        {{ daysLeftText }}
      </span>
      <span v-if="store.doneColumnId && Number(columnId) === store.doneColumnId && card.dateClosed" class="date-closed">
        Закрыто: {{ closedDateText }}
      </span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { getFullUrl } from '../api'
import { useMobile } from '../composables/useMobile'
import { useLucideIcons } from '../composables/useLucideIcons'
import { useDateFormat } from '../composables/useDateFormat'
import { useProjectsStore } from '../stores/projects'

const { isMobile } = useMobile()
const { formatShort, formatRelative, getDaysLeftText, getDueDateStatus } = useDateFormat()
const store = useProjectsStore()

useLucideIcons()

const props = defineProps({
  card: Object,
  columnId: [String, Number],
  index: Number,
  canMove: {
    type: Boolean,
    default: true
  },
  canEdit: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['archive', 'move-request'])

// Long-press для мобильной версии
const isLongPressing = ref(false)
let longPressTimer = null
let touchStartPos = { x: 0, y: 0 }

const handleTouchStart = (e) => {
  if (!isMobile.value || !props.canMove) return
  
  const touch = e.touches[0]
  touchStartPos = { x: touch.clientX, y: touch.clientY }
  
  longPressTimer = setTimeout(() => {
    isLongPressing.value = true
    // Вибрация если поддерживается
    if (navigator.vibrate) {
      navigator.vibrate(30)
    }
    // Эмитим запрос на перемещение
    emit('move-request', {
      cardId: props.card.id,
      cardTitle: props.card.title,
      columnId: props.columnId
    })
    isLongPressing.value = false
  }, 500) // 500ms для long-press
}

const handleTouchMove = (e) => {
  if (!longPressTimer) return
  
  const touch = e.touches[0]
  const moveX = Math.abs(touch.clientX - touchStartPos.x)
  const moveY = Math.abs(touch.clientY - touchStartPos.y)
  
  // Если сдвинулись больше 10px - отменяем long-press
  if (moveX > 10 || moveY > 10) {
    clearTimeout(longPressTimer)
    longPressTimer = null
  }
}

const handleTouchEnd = () => {
  if (longPressTimer) {
    clearTimeout(longPressTimer)
    longPressTimer = null
  }
  isLongPressing.value = false
}

// Блокируем контекстное меню на мобильных
const handleContextMenu = (e) => {
  if (isMobile.value) {
    e.preventDefault()
  }
}

// Mouse long-press для ПК в мобильном режиме (когда touch события недоступны)
const handleMouseDown = (e) => {
  if (!isMobile.value || !props.canMove) return
  // Только левая кнопка мыши
  if (e.button !== 0) return
  
  longPressTimer = setTimeout(() => {
    isLongPressing.value = true
    // Эмитим запрос на перемещение
    emit('move-request', {
      cardId: props.card.id,
      cardTitle: props.card.title,
      columnId: props.columnId
    })
    isLongPressing.value = false
  }, 500)
}

const handleMouseUp = () => {
  if (longPressTimer) {
    clearTimeout(longPressTimer)
    longPressTimer = null
  }
  isLongPressing.value = false
}

const handleMouseLeave = () => {
  if (longPressTimer) {
    clearTimeout(longPressTimer)
    longPressTimer = null
  }
  isLongPressing.value = false
}

const isDragging = ref(false)

const handleDragStart = (e) => {
  if (!props.canMove) {
    e.preventDefault()
    return
  }
  isDragging.value = true
  e.dataTransfer.effectAllowed = 'move'
  e.dataTransfer.setData('cardId', props.card.id.toString())
  e.dataTransfer.setData('columnId', props.columnId)
}

const handleDragEnd = () => {
  isDragging.value = false
}

// Получаем отдел по id
const cardDepartment = computed(() => {
  if (!props.card.departmentId) return null
  return store.departments.find(d => d.id === props.card.departmentId) || null
})

// Получаем лейбл по id
const cardLabel = computed(() => {
  if (!props.card.labelId) return null
  return store.labels.find(l => l.id === props.card.labelId) || null
})

// Цвет лейбла для фона карточки
const cardLabelColor = computed(() => {
  return cardLabel.value?.color || null
})

// Даты через composable
const dueDateStatus = computed(() => getDueDateStatus(props.card.dueDate))
const daysLeftText = computed(() => getDaysLeftText(props.card.dueDate))
const closedDateText = computed(() => formatRelative(props.card.dateClosed))

const isAvatarUrl = (value) => {
  return value && (value.startsWith('http://') || value.startsWith('https://') || value.startsWith('/'))
}

// Можно ли архивировать (только если колонка "Готово")
const canArchive = computed(() => {
  return store.doneColumnId && Number(props.columnId) === store.doneColumnId
})

const handleArchive = () => {
  emit('archive', props.card.id)
}
</script>

<style scoped>
.card {
  background: var(--bg-card);
  border-radius: 12px;
  padding: 14px 16px;
  cursor: grab;
  transition: all 0.2s;
  /* Отключаем выделение текста на мобильных при long-press */
  -webkit-user-select: none;
  user-select: none;
  -webkit-touch-callout: none;
}

.card.no-move {
  cursor: pointer;
}

.card:hover {
  background: var(--bg-card-hover);
}

.card.has-label-color {
  background: color-mix(in srgb, var(--label-bg) 15%, var(--bg-card));
  border-left: 3px solid var(--label-bg);
}

.card.has-label-color:hover {
  background: color-mix(in srgb, var(--label-bg) 20%, var(--bg-card-hover));
}

.card.dragging {
  opacity: 0.4;
  cursor: grabbing;
}

.card.long-pressing {
  transform: scale(0.98);
  box-shadow: 0 0 0 2px var(--accent);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 10px;
}

.tag-group {
  display: flex;
  align-items: center;
  gap: 6px;
}

.label-icon {
  font-size: 14px;
}

.tag {
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.4px;
}

.assignee {
  width: 24px;
  height: 24px;
  background: var(--blue);
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 8px;
  font-weight: 600;
  color: white;
  overflow: hidden;
}

.assignee-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}


.card-title {
  font-size: 14px;
  font-weight: 500;
  line-height: 1.5;
  color: var(--text-primary);
}

.card-description {
  font-size: 13px;
  color: var(--text-secondary);
  line-height: 1.5;
  margin-top: 8px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  padding-top: 10px;
  border-top: 1px solid rgba(255, 255, 255, 0.06);
}

.date-create {
  font-size: 11px;
  color: var(--text-muted);
  opacity: 0.7;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.comments-indicator,
.files-indicator {
  display: flex;
  align-items: center;
  gap: 3px;
  color: var(--text-muted);
}

.comments-indicator i,
.comments-indicator svg,
.files-indicator i,
.files-indicator svg {
  width: 14px;
  height: 14px;
}

.indicator-count {
  font-size: 11px;
  font-weight: 500;
}

.due-date {
  font-size: 11px;
  color: var(--text-muted);
}

.due-date.soon {
  color: var(--orange);
}

.due-date.overdue {
  color: var(--red);
}

.date-closed {
  font-size: 11px;
  color: var(--green, #00d4aa);
}

.btn-archive-card {
  display: none;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background: rgba(255, 255, 255, 0.1);
  border: none;
  border-radius: 6px;
  color: var(--text-muted);
  cursor: pointer;
  transition: all 0.15s;
}

.btn-archive-card i,
.btn-archive-card svg {
  width: 18px;
  height: 18px;
}

.card:hover .btn-archive-card {
  display: flex;
}

.btn-archive-card:hover {
  background: var(--orange);
  color: #000;
}

/* Mobile: всегда показываем кнопку архивирования */
.btn-archive-card.always-visible {
  display: flex;
}

/* ========== ИНДИКАТОРЫ ПРАВ ========== */
.permissions-indicators {
  display: flex;
  align-items: center;
  gap: 4px;
}

.perm-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 18px;
  height: 18px;
  opacity: 0.5;
}

.perm-icon i,
.perm-icon svg {
  width: 12px;
  height: 12px;
}

.perm-icon.no-edit {
  color: var(--orange);
}

.perm-icon.no-move-icon {
  color: var(--red);
}
</style>
