<script setup>
  const { post } = defineProps(['post'])

  const { getItems } = useDirectusItems();

  let comments = []
  try {
    const filter = { public: true, post: post }
    comments = await getItems({
      collection: "comments",
      params: { filter: filter },
      sort: { "date_created": 1 }
    })
  } catch {}

  import { format, parseISO } from "date-fns";

  for (let i = 0; i < comments.length; i++) {
    let date = parseISO(comments[i].date_created)
    comments[i].date = format(date, 'MMM do, yyy')

    if (comments[i].website && !comments[i].website.startsWith("http")) {
      comments[i].website = "https://" + comments[i].website
    }
  }

</script>

<template>
  <div class="comments">
    <h2>Comments</h2>
    <div class="comment" v-for="comment in comments" :key="comment.id">
      <NuxtLink v-if="comment.website" class="name" :to="comment.website" target="_BLANK">
        <h5>{{ comment.name }}</h5>
      </NuxtLink>
      <h5 v-if="!comment.website" class="name">{{ comment.name }}</h5>

      <p class="date"><span>•</span> {{ comment.date }}</p>

      <p class="text" v-html="comment.comment"></p>
    </div>
    <p v-if="comments.length === 0">No comments found... make the first comment. 👇</p>
  </div>
</template>