<template>
  <div
    class="border-2 border-dashed rounded-xl p-8 text-center transition-all duration-200"
    :class="{
      'border-blue-300 bg-blue-50': isDragging,
      'border-gray-200 hover:border-blue-300 hover:bg-gray-50': !isDragging,
    }"
    @dragenter.prevent="isDragging = true"
    @dragleave.prevent="isDragging = false"
    @dragover.prevent
    @drop.prevent="handleDrop"
    @click="openFileDialog"
  >
    <input ref="fileInput" type="file" multiple accept="image/*,.json" class="hidden" @change="handleFileChange" />

    <div class="mb-6">
      <img src="@/assets/images/file.svg" alt="File upload" class="w-20 h-20 mx-auto mb-4 opacity-75" />
    </div>

    <p class="text-xl font-medium text-gray-700 mb-2">Drag and drop your sprite images or JSON file here</p>
    <p class="text-sm text-gray-500 mb-6">or</p>

    <button class="px-6 py-2.5 bg-blue-500 hover:bg-blue-600 text-white font-medium rounded-lg transition-colors inline-flex items-center space-x-2 cursor-pointer">
      <i class="fas fa-folder-open"></i>
      <span>Select files</span>
    </button>
  </div>
</template>

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

  const emit = defineEmits<{
    (e: 'uploadSprites', files: File[]): void;
  }>();

  const fileInput = ref<HTMLInputElement | null>(null);
  const isDragging = ref(false);

  const openFileDialog = () => {
    fileInput.value?.click();
  };

  const handleFileChange = (event: Event) => {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files.length > 0) {
      const files = Array.from(input.files);
      emit('uploadSprites', files);
      // Reset input value so uploading the same file again will trigger the event
      if (fileInput.value) fileInput.value.value = '';
    }
  };

  const handleDrop = (event: DragEvent) => {
    isDragging.value = false;

    if (event.dataTransfer?.files && event.dataTransfer.files.length > 0) {
      const files = Array.from(event.dataTransfer.files).filter(file => {
        return file.type.startsWith('image/') || file.type === 'application/json' || file.name.endsWith('.json');
      });

      if (files.length > 0) {
        emit('uploadSprites', files);
      }
    }
  };
</script>
