<script setup lang="ts">
import type { Article } from '@interfaces'
import { ref, onBeforeMount } from 'vue'
import { loadArticle } from '@lib/articles'
import { useRoute, onBeforeRouteUpdate, type RouteLocation } from 'vue-router'
import NotFoundView from './NotFoundView.vue'
import { dateFromParts, simpleDateFormat } from '@lib/dates'
import { SIGNATURE, TITLE } from '@lib/meta'
import PageFooter from '@components/PageFooter.vue'
import { stripHTML } from '@/lib/strings'

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(
    dateFromParts(
      target.params.year as string,
      target.params.month as string,
      target.params.day as string,
    ),
  )
  window.document.title =
    stripHTML(TITLE) + ' — ' + stripHTML(article.value?.metadata.title ?? 'Not Found')
  loading.value = false
}

onBeforeMount(() => loadPage(route))
onBeforeRouteUpdate(loadPage)
</script>

<template>
  <template v-if="loading">
    <main></main>
  </template>
  <template v-else-if="!article">
    <NotFoundView />
  </template>
  <template v-else>
    <main class="article">
      <div class="article-header">
        <RouterLink class="link-home" to="/"><i icon="undo-2">↑</i></RouterLink>
        <h1 class="article-title" v-html="article.metadata.title"></h1>
        <div class="article-published">
          {{ article.metadata.draft ? 'Drafted on' : 'Published on' }}
          {{ 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>
      <br />
      <PageFooter />
    </main>
  </template>
</template>
