// src/views/NewsCategoryView.vue
<template>
  <div class="container mx-auto p-4 md:p-8">
    <h2 class="text-2xl md:text-3xl font-bold text-gray-900 mb-6 border-b pb-4">
      {{ appStore.checkLang.isTh ? `ข่าวสารหมวดหมู่: ${categoryTitleTh}` : `News Category: ${categoryTitleEn}` }}
    </h2>

    <div v-if="newsList.length > 0" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
      <div
          v-for="item in newsList"
          :key="item.id"
          class="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-xl transition-shadow duration-300"
      >
        <router-link :to="`/tab-news-content/${item.id}`" class="block">
          <div class="w-full h-48 overflow-hidden">
            <img
                v-if="item.image && item.image.url"
                class="w-full h-full object-cover transition-transform duration-300 hover:scale-105"
                :src="`${appStore.imageBaseUrl}${item.image.url}`"
                :alt="appStore.checkLang.isTh ? item.title_th : item.title_en"
            />
            <div v-else class="w-full h-full bg-gray-200 flex items-center justify-center text-gray-500">
              {{ appStore.checkLang.isTh ? 'ไม่มีรูปภาพ' : 'No Image' }}
            </div>
          </div>
          <div class="p-4">
            <h3 class="font-semibold text-lg text-gray-800 hover:text-primary-focus leading-tight mb-2 line-clamp-2">
              {{ appStore.checkLang.isTh ? item.title_th : item.title_en }}
            </h3>
            <p class="text-sm text-gray-600 leading-snug mb-3 line-clamp-3">
              {{ stripHtmlAndTruncate(appStore.checkLang.isTh ? item.detail_th : item.detail_en || '', 120) }}
            </p>
            <div class="text-xs text-gray-500">
              <span v-if="item.release_date">{{ formatDate(item.release_date) }}</span>
            </div>
          </div>
        </router-link>
      </div>
    </div>

    <div v-if="newsList.length > 0 && newsList.length < totalNews" 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' }}
      </button>
    </div>

    <div v-else-if="newsList.length === 0 && !isLoading" class="text-center text-gray-600 py-16">
      <p class="text-2xl font-semibold mb-4">
        {{ appStore.checkLang.isTh ? 'ไม่พบข่าวสารในหมวดหมู่นี้ หรือข่าวสารนี้ไม่พร้อมใช้งานในภาษาปัจจุบัน' : 'No news found in this category or not available in the current language.' }}
      </p>
      <router-link to="/home" class="btn bg-[#1b3872] text-white hover:bg-[#1b3872]/90 rounded-none border-none shadow-md">
        {{ appStore.checkLang.isTh ? 'กลับหน้าหลัก' : 'Back to Home' }}
      </router-link>
    </div>
    <div v-else-if="isLoading" class="text-center text-gray-500 py-16">
      <p class="text-xl flex items-center justify-center">
        <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-gray-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        {{ appStore.checkLang.isTh ? 'กำลังโหลดข่าวสาร...' : 'Loading news...' }}
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import { useRoute } from 'vue-router';
import { useAppStore } from '@/stores/app.js';
import { RouterLink } from 'vue-router';

const appStore = useAppStore();
const route = useRoute();
const newsList = ref([]);
const totalNews = ref(0);
const currentPage = ref(1);
const newsPerPage = 6;
const isLoading = ref(false);

// Computed property เพื่อแสดงชื่อหมวดหมู่ตามภาษา
const categoryTitleTh = computed(() => {
  if (appStore.tabs && Array.isArray(appStore.tabs) && appStore.tabs.length > 0) {
    const tab = appStore.tabs.find(t => t.category === route.params.category);
    return tab ? tab.title : 'ไม่ระบุหมวดหมู่';
  }
  return appStore.checkLang.isTh ? 'กำลังโหลด...' : 'Loading...';
});

const categoryTitleEn = computed(() => {
  if (appStore.tabs && Array.isArray(appStore.tabs) && appStore.tabs.length > 0) {
    const tab = appStore.tabs.find(t => t.category === route.params.category);
    return tab ? tab.title_en : 'Unspecified Category';
  }
  return appStore.checkLang.isTh ? 'Loading...' : 'Loading...';
});

// ** ฟังก์ชันสำหรับลบ HTML tags ออกจาก String ก่อนทำการ truncate **
const stripHtmlAndTruncate = (htmlText, maxLength) => {
  if (!htmlText) return '';
  // 1. สร้าง DOMParser เพื่อ parse HTML string
  const doc = new DOMParser().parseFromString(htmlText, 'text/html');
  // 2. ดึง textContent ออกมา ซึ่งจะลบ HTML tags ทั้งหมด
  const plainText = doc.body.textContent || "";
  // 3. ทำการ truncate text
  return plainText.length <= maxLength ? plainText : plainText.substring(0, maxLength) + '...';
};

const formatDate = (dateString) => {
  if (!dateString) return '';
  const parts = dateString.split('/'); // Assumes MM/DD/YYYY
  if (parts.length === 3) {
    const [month, day, year] = parts;
    const dateObj = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
    const formattedDay = String(dateObj.getDate()).padStart(2, '0');
    const formattedMonth = String(dateObj.getMonth() + 1).padStart(2, '0');
    const formattedYear = dateObj.getFullYear();
    return `${formattedDay}/${formattedMonth}/${formattedYear}`;
  }
  return dateString;
};

const fetchNewsForCategory = async (category, pageToLoad = 1) => {
  isLoading.value = true;
  try {
    const result = await appStore.fetchNewsFromMockData({
      category: category,
      limit: newsPerPage,
      page: pageToLoad,
      // ใส่ภาษาเข้าไปใน parameter ถ้า fetchNewsFromMockData รองรับ
      // lang: appStore.isTh ? 'th' : 'en'
    });

    if (pageToLoad === 1) {
      newsList.value = result.data;
    } else {
      newsList.value = [...newsList.value, ...result.data];
    }
    totalNews.value = result.total;
    currentPage.value = pageToLoad;

  } catch (error) {
    console.error(`Error fetching news for category ${category}:`, error);
    newsList.value = [];
    totalNews.value = 0;
  } finally {
    isLoading.value = false;
  }
};

const loadMoreNews = () => {
  if (newsList.value.length < totalNews.value && !isLoading.value) {
    fetchNewsForCategory(route.params.category, currentPage.value + 1);
  }
};

onMounted(() => {
  fetchNewsForCategory(route.params.category, 1);
});

// Watch route params changes to refetch news for new category
watch(() => route.params.category, (newCategory) => {
  newsList.value = []; // Clear current news
  currentPage.value = 1; // Reset to first page
  totalNews.value = 0; // Reset total
  fetchNewsForCategory(newCategory, 1);
});

// Watch language changes to refetch news list
watch(() => appStore.isTh, () => {
  newsList.value = []; // Clear current news
  currentPage.value = 1; // Reset to first page
  totalNews.value = 0; // Reset total
  fetchNewsForCategory(route.params.category, 1);
});
</script>

<style scoped>
/* เพิ่ม line-clamp สำหรับ p และ h3 ใน card */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}
</style>