﻿<script setup>
import {ref, onMounted, onBeforeUnmount} from "vue";
import { useClient } from "@/plugins/api.js";
import ContentCardSm from "@/views/contents/contentcards/SmContentCard.vue";
import ContentCardNormal from "@/views/contents/contentcards/NContentCard.vue";

const client = useClient();

const contentCount = ref(0);
const pageSize = ref(10);
const contents = ref([]);
const isSmallScreen = ref(false);
const errorMessage = ref()

let last_id = null


const updateScreenSize = () => {
  isSmallScreen.value = window.matchMedia('(max-width: 600px)').matches;
};

const fetchContents = async ({done}) => {
  try {
    let uri = `/api/contents/followed/?page_size=${pageSize.value}`;
    if (last_id !== null) uri = uri + `&last_id=${last_id}`

    const response = await client.get(uri);

    if (response.status >= 200 && response.status < 300) {
      contentCount.value = response.data.length;

      if (contentCount.value > 0) {
        contents.value.push(...response.data)
        const [last_content] = response.data.slice(-1)
        last_id = last_content.id
      }

      if (contentCount < pageSize.value)
        done('empty')
      else
        done('ok')
    }
    
  } catch (error) {
    console.error("Failed to fetch posts", error);
  }
};

onMounted(() => {
  updateScreenSize();
  window.addEventListener('resize', updateScreenSize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', updateScreenSize);
});

</script>

<template>
  <div class="max-w-[800px] mx-auto">
    <div class="w-full h-full mx-1">
      <div class="d-sm-block d-md-block mb-1">
        <v-infinite-scroll :items="contents"
                           :onLoad="fetchContents"
                           class="md:gap-2">
      
          <template v-for="content in contents" :key="content.id">
            <component
                :is="isSmallScreen ? ContentCardSm : ContentCardNormal"
                :content="content"
                @content-deleted="onContentDeleted"
            ></component>
          </template>
      
          <template v-slot:empty>
            Il n'y a pas plus de contenus
          </template>
      
          <template v-slot:error>
            <v-alert type="error">{{ errorMessage }}</v-alert>
          </template>
      
        </v-infinite-scroll>
      </div>
    </div>
  </div>
</template>
<style scoped>
/* Add your styles here */
</style>
