<script setup lang="ts">
import type { Article } from '@interfaces'
import { ref, onBeforeMount, onUpdated, onMounted } from 'vue'
import { loadArticle, updateDynamicContent } from '@lib/articles'
import { useRoute, onBeforeRouteUpdate, type RouteLocation } from 'vue-router'
import { simpleDateFormat } from '@lib/dates'
import { AUTHORED, PUBLISHED_ON, SIGNATURE, TITLE, UPDATED_ON } from '@lib/config'
import { stripHTML } from '@lib/strings'
import BackHomeButton from '@components/BackHomeButton.vue'
import NotFoundView from '@views/NotFoundView.vue'
import ArticleTagList from '@components/ArticleTagList.vue'

const article = ref<Article | null>(null)
const loading = ref<boolean>(true)
const route = useRoute()

async function loadPage(target: RouteLocation) {
  loading.value = true
  article.value = await loadArticle(target.params.pathMatch as string)
  window.document.title =
    stripHTML(TITLE) + ' — ' + stripHTML(article.value?.metadata.title ?? 'Not Found')
  loading.value = false
  await updateDynamicContent()
}

onBeforeMount(() => loadPage(route))
onBeforeRouteUpdate(loadPage)
onMounted(updateDynamicContent)
onUpdated(updateDynamicContent)
</script>

<template>
  <template v-if="!loading && !article">
    <NotFoundView />
  </template>
  <article v-if="!loading" class="article h-entry">
    <template v-if="!loading && article">
      <div class="article-header">
        <h1 class="article-title p-name" v-html="article.metadata.title"></h1>
        <div class="article-info">
          <template v-if="article.metadata.author">
            <span v-html="AUTHORED"></span>
            &hairsp;
            <span class="p-author h-card" v-html="article.metadata.author"></span>
            &hairsp;—
          </template>
          <span v-html="PUBLISHED_ON"></span>
          &hairsp;
          <time class="dt-published" :datetime="simpleDateFormat(article.metadata.date)">
            {{ simpleDateFormat(article.metadata.date) }}
          </time>
          <template v-if="article.metadata.updated">
            &hairsp;—
            <span v-html="UPDATED_ON"></span>
            {{ simpleDateFormat(article.metadata.updated) }}
          </template>
          <template v-if="article.metadata.tags.length > 0">
            —
            <article-tag-list :tags="article.metadata.tags" />
          </template>
        </div>
        <img
          v-if="article.metadata.thumbnail"
          id="thumbnail"
          :src="article.metadata.thumbnail"
          alt="thumbnail"
        />
      </div>
      <div class="article-text e-content" v-html="article.html"></div>
      <div class="article-signature" v-html="SIGNATURE"></div>
      <BackHomeButton />
    </template>
  </article>
</template>
