// src/views/AllNewsView.vue
<template>
  <div class="mt-6">
    <div
        class="p-4 bg-cover bg-center"
        :style="`background-image: url('${appStore.imageBaseUrl}${appStore.headers.header_background.url}')`"
    >
      <div class="container mx-auto">
        <h4
            class="text-2xl md:text-3xl font-bold text-gray-900 mb-6 border-b pb-4"
            style="background-color: transparent !important;"
        >
          {{ appStore.checkLang.isTh ? 'เรื่องราวดี ๆ ที่เราอยากบอกต่อ' : 'Our Inspiring Stories' }}
        </h4>
      </div>
    </div>

    <div class="p-6" :style="`background-color:${appStore.headers.bgColor || '#ffffff'}`">
      <div class="container mx-auto"> <div v-if="displayedNews.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div v-for="item in displayedNews" :key="item.id" class="flex flex-col">
          <NewsItem :item="item" />
        </div>
      </div>
        <div v-else class="text-center text-gray-500 py-10">
          {{ appStore.checkLang.isTh ? 'ไม่พบข่าวสาร' : 'No news found' }}
        </div>

        <div v-if="hasMoreNews" class="flex justify-center mt-8">
          <button
              @click="loadMoreNews"
              class="btn bg-[#1b3872] text-white hover:bg-[#1b3872]/90 rounded-none border-none shadow-md"
          >
            {{ appStore.checkLang.isTh ? 'โหลดข่าวเพิ่ม' : 'Load More News' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import NewsItem from '@/components/NewsItem.vue';
import { useAppStore } from '@/stores/app';

const appStore = useAppStore();

const displayedNews = ref([]);
const currentPage = ref(1);
const newsPerLoad = 6; // จำนวนข่าวต่อหน้าที่คาดหวังจาก appStore.find

const fetchNews = async () => {
  const fetchedData = await appStore.find(
      'news',
      `_limit=${newsPerLoad}&_page=${currentPage.value}&feature=false`
  );

  const currentFetchedNews = Array.isArray(fetchedData) ? fetchedData : [];

  if (currentPage.value === 1) {
    displayedNews.value = currentFetchedNews; // ใช้ currentFetchedNews โดยตรง
  } else {
    displayedNews.value = [...displayedNews.value, ...currentFetchedNews]; // ใช้ currentFetchedNews โดยตรง
  }
  // console.log(`[AllNewsView] - displayedNews updated. Length: ${displayedNews.value.length}`); // Commented out to clean up console
};

const loadMoreNews = () => {
  currentPage.value++;
  fetchNews();
};

const hasMoreNews = computed(() => {
  const currentDisplayedLength = displayedNews.value.length;
  const totalFromStore = appStore.totalNewsCount;
  const result = currentDisplayedLength < totalFromStore;

  // console.log(`[AllNewsView - computed hasMoreNews] - displayedNews.length: ${currentDisplayedLength}, appStore.totalNewsCount (direct): ${totalFromStore}, Result: ${result}`); // Commented out to clean up console

  return result;
});

onMounted(() => {
  fetchNews();
});

// Watch (คุณสามารถเก็บไว้สำหรับ debugging ในอนาคต หรือลบออกถ้าไม่ต้องการแล้ว)
// watch(() => appStore.totalNewsCount, (newValue, oldValue) => {
//   console.log(`[AllNewsView - Watch appStore.totalNewsCount] - totalNewsCount changed from ${oldValue} to ${newValue}`);
// }, { immediate: true });

watch(() => appStore.checkLang.isTh, () => {
  currentPage.value = 1;
  displayedNews.value = []; // เคลียร์ข้อมูลเก่าเมื่อเปลี่ยนภาษา
  fetchNews();
});
</script>

<style scoped>
/* คุณสามารถเพิ่ม CSS เฉพาะส่วนนี้ได้ถ้าจำเป็น */
</style>