<template>
  <div class="bucket" :class="{ 'drag-over': isDragOver }" @dragenter.prevent="onDragEnter"
    @dragover.prevent="onDragOver" @dragleave="onDragLeave" @drop.prevent="onDrop">
    <div class="bucket-content">
      <div v-if="cards.length === 0" class="bucket-empty">
        Drop cards here
      </div>
      <div v-else class="bucket-cards">
        <Card v-for="(card, index) in cards" :key="index" :track="card" class="bucket-card" isFaceUp />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

const props = defineProps<{
  modelValue?: any[]
}>()

const emit = defineEmits(['update:modelValue', 'card-dropped'])

const isDragOver = ref(false)
const cards = ref<any[]>(props.modelValue || [])

// Mettre à jour les cartes quand la prop change
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    cards.value = [...newValue]
  }
})

const onDragEnter = (e: DragEvent) => {
  e.preventDefault()
  isDragOver.value = true
}

const onDragOver = (e: DragEvent) => {
  e.preventDefault()
  isDragOver.value = true
}

const onDragLeave = () => {
  isDragOver.value = false
}

const onDrop = (e: DragEvent) => {
  isDragOver.value = false

  // Récupérer les données de la carte depuis l'événement de glisser
  const cardData = e.dataTransfer?.getData('application/json')
  if (cardData) {
    try {
      const card = JSON.parse(cardData)
      cards.value = [...cards.value, card]
      emit('update:modelValue', cards.value)
      emit('card-dropped', card)
    } catch (e) {
      console.error('Invalid card data', e)
    }
  }
}
</script>

<style scoped>
.bucket {
  width: 120px;
  min-height: 160px;
  border: 2px dashed #ccc;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
  transition: all 0.2s ease;
  padding: 1rem;
  position: relative;
  overflow: hidden;
}

.bucket.drag-over {
  border-color: #4f46e5;
  background-color: #eef2ff;
  transform: scale(1.02);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.bucket-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.bucket-empty {
  color: #9ca3af;
  text-align: center;
  padding: 1rem;
}

.bucket-cards {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  width: 100%;
}

.bucket-card {
  background: white;
  border-radius: 4px;
  padding: 0.5rem;
  font-size: 0.8rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
