<template>
  <div>
      <div v-if="naechsteTermine.length > 0" class="space-y-2 mb-6">
        <div
          v-for="(termin, index) in naechsteTermine"
          :key="index"
          class="bg-gray-50 rounded-lg p-3 hover:bg-gray-100 transition-colors"
        >
          <div class="flex items-center justify-between">
            <div class="flex items-center space-x-3">
              <div class="w-10 h-10 bg-primary-600 rounded-lg flex flex-col items-center justify-center text-white text-xs font-bold">
                <span>{{ formatDay(termin.datum) }}</span>
                <span>{{ formatMonth(termin.datum) }}</span>
              </div>
              <div>
                <h3 class="font-semibold text-gray-900">{{ termin.titel }}</h3>
                <p class="text-sm text-gray-600">{{ termin.beschreibung }}</p>
              </div>
            </div>
            <span :class="[
              'px-2 py-1 text-xs font-medium rounded-full',
              termin.kategorie === 'Turnier' ? 'bg-yellow-100 text-yellow-800' : 'bg-blue-100 text-blue-800'
            ]">
              {{ termin.kategorie }}
            </span>
          </div>
        </div>
      </div>

      <div v-else class="text-center py-8 bg-gray-50 rounded-lg">
        <Calendar :size="32" class="text-gray-400 mx-auto mb-2" />
        <p class="text-gray-600 text-sm">Keine kommenden Termine</p>
      </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Calendar } from 'lucide-vue-next'

const termine = ref([])

const naechsteTermine = computed(() => {
  const heute = new Date()
  console.log('Heute ist:', heute.toISOString().split('T')[0])
  
  const kommende = termine.value
    .filter(t => {
      const terminDatum = new Date(t.datum)
      const istKommend = terminDatum >= heute
      console.log(`Termin ${t.titel} (${t.datum}): ${istKommend ? 'KOMMEND' : 'VERSTRICHEN'}`)
      return istKommend
    })
    .sort((a, b) => new Date(a.datum) - new Date(b.datum))
  
  console.log('Kommende Termine:', kommende)
  return kommende
})

const formatDay = (dateString) => {
  const date = new Date(dateString)
  return date.getDate()
}

const formatMonth = (dateString) => {
  const date = new Date(dateString)
  const monate = ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez']
  return monate[date.getMonth()]
}

const loadTermine = async () => {
  try {
    const response = await $fetch('/api/termine')
    termine.value = response.termine || []
  } catch (error) {
    console.error('Fehler beim Laden der Termine:', error)
    termine.value = []
  }
}

onMounted(() => {
  loadTermine()
})
</script>

