<template>
  <h1 class="mb-4 font-semibold text-xl">Favorites</h1>


  <div v-if="messages.length == 0">Empty...</div>
  <template v-else>
    <ListItem v-for="message in messages" :key="message.ID" :item="message" />

    <div class="flex items-center justify-center">
      <button class="px-4 py-2 hover:bg-slate-100 rounded border text-xl font-semibold w-full"
        @click="loadMore">LoadMore</button>
    </div>
  </template>
</template>

<script setup>
import ListItem from "@/components/ListItem.vue";
import { getFavoriteMessages } from "@/services/messages";
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";

const route = useRoute();

const messages = ref([]);

const loadMore = async () => {
  // router goto next page
  // offset is last message ID
  const offset = messages.value[messages.value.length - 1].ID
  router.push({
    name: "favorite-messages",
    params: {
      channel: route.params.channel,
      offset: offset,
    },
  });

  messages.value = await getFavoriteMessages({ offset: offset });
  console.log("messages", messages.value);
  // page scroll to top with animation
  window.scrollTo({ top: 0, behavior: "smooth" });
}

onMounted(async () => {
  messages.value = await getFavoriteMessages({ offset: route.params.offset });
});
</script>
