<template>
  <div class="mt-8 block border p-6" data-cy="circle-document-section">
    <h3 class="text-blue-dark">
      {{ $t("circlePage.documents.title") }}
    </h3>
    <div>
      <div class="mt-4 leading-relaxed">
        {{ $t("circlePage.documents.userDescription") }}
      </div>
    </div>
    <ul v-if="circleDocuments.length" class="mt-8 border-t border-t-gray-500">
      <DocumentListItem
        v-for="doc of circleDocuments"
        :key="doc.url"
        :subtitle="doc.learning_sequence.title"
        :doc="doc"
      />
    </ul>
  </div>
</template>

<script setup lang="ts">
import DocumentListItem from "@/components/circle/DocumentListItem.vue";
import { useCurrentCourseSession } from "@/composables";
import { computed, onMounted, ref } from "vue";
import type { CircleDocument, CircleType } from "@/types";
import { fetchCourseSessionDocuments } from "@/services/files";

const props = defineProps<{
  circle: CircleType;
}>();

const courseSession = useCurrentCourseSession();

const circleDocumentsResultData = ref<CircleDocument[]>([]);

async function fetchDocuments() {
  const result = await fetchCourseSessionDocuments(courseSession.value?.id);
  if (result.length > 0) {
    circleDocumentsResultData.value = result;
  } else {
    circleDocumentsResultData.value = [];
  }
}

const circleDocuments = computed(() => {
  return circleDocumentsResultData.value.filter(
    (d) => d.learning_sequence.circle.slug === props.circle?.slug
  );
});

onMounted(async () => {
  await fetchDocuments();
});
</script>
