<template>
  <div class="upload-area">
    <div 
      class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-400 transition-colors"
      :class="{ 'border-blue-400 bg-blue-50': isDragOver }"
      @dragover.prevent="isDragOver = true"
      @dragleave.prevent="isDragOver = false"
      @drop.prevent="handleDrop"
    >
      <div class="space-y-4">
        <div class="text-4xl text-gray-400">📁</div>
        <div class="space-y-3">
          <p class="text-lg text-gray-600">Drop org files or folders here</p>
          <p class="text-sm text-gray-400">or</p>
          <div class="flex gap-3 justify-center items-center">
            <label>
              <input 
                type="file" 
                multiple 
                accept=".org"
                @change="handleFileSelect"
                class="hidden"
              />
              <span class="inline-block bg-blue-600 text-white px-4 py-2 rounded cursor-pointer hover:bg-blue-700 transition-colors">
                Browse Files
              </span>
            </label>
            <button
              @click="loadExampleFiles"
              class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700 transition-colors"
            >
              Use Example Files
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { parseOrgFile } from '@/utils/orgParser'
import { exampleFiles } from '@/data/exampleFiles'
import type { OrgFile } from '@/types/org'

const emit = defineEmits<{
  'files-selected': [files: OrgFile[]]
}>()

const isDragOver = ref(false)

async function handleDrop(event: DragEvent) {
  isDragOver.value = false
  const files = Array.from(event.dataTransfer?.files || [])
  await processFiles(files)
}

async function handleFileSelect(event: Event) {
  const target = event.target as HTMLInputElement
  const files = Array.from(target.files || [])
  await processFiles(files)
}

async function processFiles(files: File[]) {
  const orgFiles: OrgFile[] = []
  
  for (const file of files) {
    if (file.name.endsWith('.org')) {
      const content = await file.text()
      const parsed = parseOrgFile(file.name, content)
      orgFiles.push(parsed)
    }
  }
  
  if (orgFiles.length > 0) {
    emit('files-selected', orgFiles)
  }
}

function loadExampleFiles() {
  const orgFiles: OrgFile[] = []
  
  for (const [filename, content] of Object.entries(exampleFiles)) {
    const parsed = parseOrgFile(filename, content)
    orgFiles.push(parsed)
  }
  
  emit('files-selected', orgFiles)
}
</script>