<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 NotFoundView from './NotFoundView.vue'
import { simpleDateFormat } from '@lib/dates'
import { PUBLISHED_ON, SIGNATURE, TITLE } from '@lib/config'
import PageFooter from '@components/PageFooter.vue'
import { stripHTML } from '@lib/strings'
import NavBar from '@components/NavBar.vue'
import BackHomeButton from '@/components/BackHomeButton.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">
    <main></main>
  </template>
  <template v-else-if="!article">
    <NotFoundView />
  </template>
  <template v-else>
    <main class="article">
      <NavBar />
      <div class="article-header">
        <h1 class="article-title" v-html="article.metadata.title"></h1>
        <div class="article-published">
          <span v-html="PUBLISHED_ON"></span> {{ simpleDateFormat(article.metadata.date) }}
        </div>
        <img
          v-if="article.metadata.thumbnail"
          id="thumbnail"
          :src="article.metadata.thumbnail"
          alt="thumbnail"
        />
      </div>
      <div class="article-text" v-html="article.html"></div>
      <div class="article-signature" v-html="SIGNATURE"></div>
      <BackHomeButton />
      <PageFooter />
    </main>
  </template>
</template>
