<template>
  <div>
    <section>
      <div v-for="yearGroup in eventsByYear" :key="yearGroup.year" class="mb-8">
        <p class="text-sm text-gray-500 mb-4">{{ yearGroup.year }}</p>
        
        <div v-for="item in yearGroup.events" :key="item.start_date" class="mb-6">
          <div class="flex items-start gap-4">
            <div class="text-sm text-gray-400 min-w-[80px]">
              {{ item.formatted_date }}
            </div>
            <div class="flex-1">
              <div>
                {{ item.venue.city }}, {{ item.venue.state }}
              </div>
              <div class="text-sm text-gray-500 ml-4">
                {{ item.venue.name }}
              </div>
              
              <div class="ml-4 mt-2">
                <div v-for="performance in item.program" :key="performance.work" class="mb-2">
                  <div class="italic">{{ performance.work }}</div>
                  <div v-if="performance.ensemble" class="ml-4 text-sm text-gray-500">
                    {{ performance.ensemble }}
                  </div>
                  <div v-if="performance.performers?.length" class="ml-4 text-sm text-gray-500">
                    <span v-for="(performer, idx) in performance.performers" :key="performer.name">
                      <span v-if="idx > 0">, </span>
                      {{ performer.name }}<span v-if="performer.instrument_tags?.length"> - {{ performer.instrument_tags.join(', ') }}</span>
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
const { data: events } = await useFetch('/api/events', {
  transform: (events) => {
    for (const event of events) {
      let date = new Date(event.start_date)
      event.formatted_date = ("0" + date.getDate()).slice(-2) + "." + ("0" + (date.getMonth() + 1)).slice(-2) + "." + date.getFullYear()
    }
    return events.sort((a,b) => new Date(b.start_date) - new Date(a.start_date))
  }
})

const eventsByYear = computed(() => {
  if (!events.value) return []
  
  const byYear = {}
  for (const event of events.value) {
    const year = new Date(event.start_date).getFullYear()
    if (!byYear[year]) byYear[year] = []
    byYear[year].push(event)
  }
  
  return Object.keys(byYear)
    .sort((a, b) => b - a)
    .map(year => ({
      year,
      events: byYear[year].sort((a, b) => new Date(b.start_date) - new Date(a.start_date))
    }))
})

useHead({
  titleTemplate: 'Michael Winter - Performances'
})
</script>
