﻿<template>
  <div>
    <v-infinite-scroll :items="contents" :onLoad="fetchContents">      
      <div class="grid gap-2 -mt-4"
           :class="{
             'grid-cols-1': isExtraSmallScreen,
             'grid-cols-2': isSmallScreen,
             'grid-cols-3': isMediumScreen,
             'grid-cols-4': isLargeScreen,
             'grid-cols-5': isExtraLargeScreen
           }">
        <template v-for="content in contents" :key="content.id">
          <component
              :is="isSmallScreen ? ContentCardSm : ContentCardNormal"
              :content="content"
              @content-deleted="onContentDeleted"
          ></component>
        </template>
      </div>
      


      <template v-slot:empty >
       <div class="py-2" :style="{color:branding.colors.onSurface}">Il n'y a pas plus de contenu</div>
      </template>

      <template v-slot:error>
        <v-alert type="error">{{ errorMessage }}</v-alert>
      </template>
    </v-infinite-scroll>
  </div>
</template>

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

const branding = useBrandingStore();
const props = defineProps({
  creatorId: {
    type: String,
    required: true
  }
});

const client = useClient();
const contents = ref([]);
const errorMessage = ref();
let last_id = null;


const isExtraSmallScreen = ref(false);
const isSmallScreen = ref(false);
const isMediumScreen = ref(false);
const isLargeScreen = ref(false);
const isExtraLargeScreen = ref(false);

const updateScreenSize = () => {
  isExtraSmallScreen.value = window.matchMedia('(max-width: 640px)').matches;
  isSmallScreen.value = window.matchMedia('(min-width: 641px) and (max-width: 768px)').matches;
  isMediumScreen.value = window.matchMedia('(min-width: 769px) and (max-width: 1024px)').matches;
  isLargeScreen.value = window.matchMedia('(min-width: 1025px) and (max-width: 1280px)').matches;
  isExtraLargeScreen.value = window.matchMedia('(min-width: 1281px)').matches;
};

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

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


async function onContentDeleted(contentId) {
  contents.value = contents.value.filter(c => c.id !== contentId);
}

const creatorIdWatcher = watch(
    () => props.creatorId,
    (newCreatorId) => {
      if (newCreatorId) {
        contents.value = [];
        last_id = null;
        fetchContents({ done: () => {} });
      }
    }
);

async function fetchContents({ done, page_size = 10 }) {
  if (props.creatorId == null) return;

  try {
    let uri = `/api/contents/creator/${props.creatorId}?page_size=${page_size}`;
    if (last_id !== null) uri = uri + `&last_id=${last_id}`;

    const response = await client.get(uri);

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

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

      if (contentCount < page_size)
        done('empty');
      else
        done('ok');
    }
  } catch (error) {
    console.error("Failed to fetch posts", error);
    errorMessage.value = error.message || "Failed to fetch contents";
    done('error');
  }
}

</script>
