<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 { NAME, REPOSITORY, VERSION } from '@lib/meta'

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

async function loadPage(target: RouteLocation) {
  article.value = await loadArticle(
    dateFromParts(
      target.params.year as string,
      target.params.month as string,
      target.params.day as string,
    ),
  )
}

function scrollTop() {
  window.scrollTo(0, 0)
}

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

<template>
  <template v-if="!article">
    <NotFoundView />
  </template>
  <template v-else>
    <main class="article">
      <div class="header">
        <RouterLink class="link-home" to="/">↑</RouterLink>
        <h1>{{ article.metadata.title }}</h1>
        <span class="time">
          <span>{{ article.metadata.draft ? 'Drafted on' : 'Published on' }}</span>
          {{ simpleDateFormat(article.metadata.date) }}
        </span>
      </div>
      <img :src="article.metadata.thumbnail" alt="thumbnail" />
    </main>
    <div id="text" v-html="article.html"></div>
    <div id="signature">TODO signature</div>
    <br />
    <a @click.prevent="scrollTop" href="#">Go to top</a> -
    <RouterLink to="/">Back to home</RouterLink>
    <hr />
    <footer>
      <small>
        {{ new Date().getFullYear() }} - Made with <a :href="REPOSITORY">{{ NAME }}</a>
        {{ VERSION }}
      </small>
    </footer>
  </template>
</template>
