// src/components/TabNews.vue
<template>
  <div class="p-4">
    <!-- หัวข้อข่าว -->
    <div class="mb-6 px-2 md:px-4">
      <h4
          class="inline-block text-white text-2xl md:text-3xl font-semibold px-6 py-2 bg-[#1b3872] rounded shadow-md"
      >
        {{ appStore.checkLang.isTh ? 'ข่าวสารอัพเดต' : 'Latest Updates' }}
      </h4>
    </div>

    <!-- Tabs -->
    <div role="tablist" class="flex flex-wrap space-x-2 border-b border-gray-300">
      <button
          v-for="(tab, index) in tabs"
          :key="tab.category"
          class="px-4 py-2 text-sm font-medium transition-all duration-200 border-b-2 whitespace-nowrap"
          :class="{
          'border-blue-700 text-blue-700': activeTab === tab.category,
          'border-transparent text-gray-500 hover:text-blue-700 hover:border-blue-500': activeTab !== tab.category
        }"
          @click="changeTab(tab.category)"
      >
        {{ appStore.checkLang.isTh ? tab.title : tab.title_en }}
      </button>
    </div>

    <!-- Tab Content -->
    <div class="mt-4">
      <div
          v-for="tab in tabs"
          :key="tab.category"
          v-show="activeTab === tab.category"
      >
        <div v-if="newsByTab[tab.category]?.data?.length > 0">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div
                v-for="(item, index) in newsByTab[tab.category].data"
                :key="item.id"
                class="card card-compact bg-base-100 shadow-md rounded-md overflow-hidden
                     transition-transform duration-200 hover:shadow-lg hover:-translate-y-1
                     flex flex-col md:flex-row"
            >
              <div class="crop w-full md:w-36 h-36 md:h-auto flex-shrink-0">
                <img
                    :src="`${appStore.imageBaseUrl}${item.image?.url ?? ''}`"
                    alt="News Thumbnail"
                    class="w-full h-full object-cover"
                    @error="e => e.target.style.display = 'none'"
                />
              </div>

              <div class="card-body p-4 flex flex-col justify-between flex-1">
                <router-link
                    :to="`/content/${item.id}`"
                    class="card-title text-base text-gray-800 hover:underline line-clamp-2 mb-2"
                >
                  {{ appStore.checkLang.isTh ? item.title_th : item.title_en || 'No Title' }}
                </router-link>
                <p class="text-sm text-gray-600 line-clamp-2 flex-grow">
                  {{ truncateDetail(appStore.checkLang.isTh ? item.detail_th : item.detail_en || '', 80) }}
                </p>
                <div class="text-xs text-gray-400 mt-2">
                  <span v-if="item.release_date">{{ formatDate(item.release_date) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div v-else class="text-center text-gray-500 py-8">
          {{ appStore.checkLang.isTh ? 'ไม่พบข่าวสารในหมวดหมู่นี้' : 'No news found in this category' }}
        </div>

        <div class="flex justify-end mt-6">
          <router-link
              v-if="newsByTab[tab.category]?.total > 6"
              :to="`/news/${tab.category}`"
              class="btn bg-[#1b3872] text-white hover:bg-[#1b3872]/90 rounded-none border-none shadow-md"
          >
            {{ appStore.checkLang.isTh ? more : more_en }}
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>

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

const appStore = useAppStore();

const tabs = ref([
  { title: "ข่าวประชาสัมพันธ์หน่วยงาน", title_en: "RTAF News", category: "HumanTechNews" },
  { title: "ข่าวประชาสัมพันธ์ภายใน", title_en: "RTAF Organization News", category: "OrgNews" },
  { title: "ข่าวนวัตกรรม", title_en: "RTAF Service News", category: "InnovationNews" },
  { title: "Press Release", title_en: "RTAF Press Release", category: "GeneralPublic" },
  { title: "ข่าวบริการประชาชน", title_en: "Public Service News", category: "EventActivities" },
]);

const activeTab = ref(tabs.value[0].category);
const newsByTab = ref({});
const more = "อ่านข่าวต่อ";
const more_en = "Read More";

const truncateDetail = (text, maxLength) => {
  if (!text) return '';
  return text.length <= maxLength ? text : text.substring(0, maxLength) + '...';
};

const formatDate = (dateString) => {
  if (!dateString) return '';
  const parts = dateString.split('/');
  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 fetchNewsForTab = async (category) => {
  try {
    const { data, total } = await appStore.fetchTabNews(category, 6);
    newsByTab.value[category] = { data, total };
  } catch (error) {
    console.error(`Error fetching news for ${category}:`, error);
    newsByTab.value[category] = { data: [], total: 0 };
  }
};

const changeTab = async (category) => {
  activeTab.value = category;
  if (!newsByTab.value[category]) {
    await fetchNewsForTab(category);
  }
};

onMounted(async () => {
  for (const tab of tabs.value) {
    await fetchNewsForTab(tab.category);
  }
});
</script>

<style scoped>
.crop {
  overflow: hidden;
  background-color: #f0f0f0;
}
</style>
