<script setup lang="ts">
import { ref, onBeforeMount, onUpdated, onMounted } from 'vue'
import { listArticles, updateDynamicContent } from '@lib/articles'
import type { ArticleMetadata } from '@interfaces'
import { simpleDateFormat } from '@lib/dates'
import { HOME_COUNT, PROD, PUBLISHED_ON, TITLE } from '@lib/config'
import { stripHTML } from '@lib/strings'

const articles = ref<ArticleMetadata[]>([])
const loading = ref<boolean>(true)

onBeforeMount(async () => {
  const newArticles = (await listArticles())
    .filter((metadata) => (!metadata.draft || !PROD) && metadata.path)
    .slice(0, HOME_COUNT)
  articles.value.splice(0, articles.value.length, ...newArticles)
  window.document.title = stripHTML(TITLE) + ' — Home'
  loading.value = false
  await updateDynamicContent()
})
onMounted(updateDynamicContent)
onUpdated(updateDynamicContent)
</script>

<template>
  <div v-if="!loading" class="home">
    <template v-for="(metadata, index) in articles" :key="index">
      <div v-if="(!metadata.draft || !PROD) && metadata.path" class="article-item">
        <RouterLink :to="metadata.path" class="h-entry">
          <h2 class="p-name" v-html="metadata.title"></h2>
          <span class="article-info"
            ><span v-html="PUBLISHED_ON"></span> <time class="dt-published" :datetime="simpleDateFormat(metadata.date)">{{ simpleDateFormat(metadata.date) }}</time></span
          >
          <img
            v-if="metadata.thumbnail"
            alt="thumbnail"
            :src="metadata.path + metadata.thumbnail"
          />
        </RouterLink>
      </div>
    </template>
  </div>
</template>
