<template>
  <div>
    <section>
      <div v-for="item in pubs" :key="item.citationKey" class="mb-6">
        <div class="flex items-start gap-2">
          <div>
            <a 
              v-if="item.entryTags.howpublished"
              :href="item.entryTags.howpublished"
              target="_blank"
              class="hover:underline"
            >
              <span v-html="item.entryTags.title"></span>
            </a>
            <span v-else v-html="item.entryTags.title"></span>
            <div class="text-sm text-gray-500 ml-4">
              {{ item.entryTags.author }}
              <span v-if="item.entryTags.booktitle">{{ item.entryTags.booktitle }}.</span>
              <span v-if="item.entryTags.journal">{{ item.entryTags.journal }}.</span>
              <span v-if="item.entryTags.editor">editors {{ item.entryTags.editor }}</span>
              <span v-if="item.entryTags.volume">volume {{ item.entryTags.volume }}.</span>
              <span v-if="item.entryTags.publisher">{{ item.entryTags.publisher }}.</span>
              {{ item.entryTags.year }}.
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
const isValidUrl = urlString => {
  var pattern = /^((http|https|ftp):\/\/)/;
  return pattern.test(urlString)
}

const { data: pubs } = await useFetch('/api/publications', {
  key: 'publications-page',
  transform: (pubs) => {
    const cloned = JSON.parse(JSON.stringify(pubs))
    for (const pub of cloned) {
      if(pub.entryTags && pub.entryTags.howpublished && !(isValidUrl(pub.entryTags.howpublished))){
        pub.entryTags.howpublished = "/pubs/" + pub.entryTags.howpublished
      }
    }
    return cloned.sort((a, b) => {
      const getYear = (key) => parseInt(key.replace(/\D/g, '')) || 0
      const getSuffix = (key) => key.replace(/^Winter\d+/, '') || ''
      
      const yearA = getYear(a.citationKey)
      const yearB = getYear(b.citationKey)
      
      if (yearA !== yearB) return yearB - yearA
      
      return getSuffix(b.citationKey).localeCompare(getSuffix(a.citationKey))
    })
  }
})

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