<template>
  <div>
    <section>
      <div v-for="yearGroup in lecturesByYear" :key="yearGroup.year" class="mb-8">
        <p class="text-sm text-gray-500 mb-4">{{ yearGroup.year }}</p>
        
        <div v-for="item in yearGroup.talks" :key="item.date + item.title" class="mb-4">
          <div class="text-sm">{{ item.location }}</div>
          <div v-for="talk in item.talks" :key="talk.title" class="ml-4 text-sm text-gray-500">
            {{ talk.title }}
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
const { data: talksData } = await useFetch('/api/talks', {
  transform: (events) => {
    for (const event of events) {
      let date = new Date(event.date)
      event.date = date
      event.formatted_date = ("0" + (date.getMonth() + 1)).slice(-2) + "." + date.getFullYear()
      if(typeof event.title === 'string' || event.title instanceof String) {
        event.talks = [{'title': event.title}]
      } else {
        let talks = []
        for(const talk of event.title){
          talks.push({"title": talk})
        }
        event.talks = talks
      }
    }
    return events.sort((a,b) => new Date(b.date) - new Date(a.date))
  }
})

const lecturesByYear = computed(() => {
  if (!talksData.value) return []

  const byYear = {}
  for (const talk of talksData.value) {
    const year = talk.date ? talk.date.getFullYear() : 'Unknown'
    if (!byYear[year]) byYear[year] = []
    byYear[year].push(talk)
  }

  return Object.keys(byYear)
    .sort((a, b) => b - a)
    .map(year => {
      const talks = byYear[year].sort((a, b) => new Date(b.date) - new Date(a.date))
      return { year, talks }
    })
})

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