<template>
  <div id="kbuzz-section" class="flex items-center justify-between px-6 py-4 mt-12 relative z-10">
    <div data-aos="fade-right" class="lg:flex space-x-4 py-5 hidden">
      <!-- Categories Section -->
      <div v-for="category in categories" :key="category" @click="getCategory(category)" class="outer cursor-pointer">
        <div
          :class="{
            'button-cat': currentCategory !== category,
            'relative border border-[#EC2029] px-6 rounded-full': true,
            'bg-[#EC2029] text-white': currentCategory === category,
            'bg-white text-black': currentCategory !== category,
          }"
        >
          <div class="text-cat">{{ translate(category) }}</div>
        </div>
      </div>
    </div>

    <!-- category mobile -->
    <div data-aos="fade-right" class="relative lg:hidden block">
      <div class="relative group">
        <div class="flex items-center space-x-1 cursor-pointer">
          <div class="text-gray-600 text-sm flex items-center mr-1">
            <span class="ml-2 font-bold">{{ translate(currentCategory) }}</span>
          </div>
          <span class="transition-transform transform group-hover:rotate-180">
            <img :src="'/icon/icon_dropdown_sort.svg'" class="w-3" />
          </span>
        </div>
        <div class="absolute z-20 hidden group-hover:block w-max font-bold text-base bg-white text-black py-5 rounded-[20px] shadow-lg -left-2">
          <div v-for="category in categories" :key="category" @click="getCategory(category)" class="block px-10 py-1 hover:text-[#16256E]">
            {{ translate(category) }}
          </div>
        </div>
      </div>
    </div>
    <!--  -->

    <!-- Sort By Dropdown -->
    <div data-aos="fade-left" class="relative">
      <div class="relative group">
        <div class="flex items-center space-x-1 cursor-pointer">
          <div class="text-gray-600 lg:text-base text-sm flex items-center mr-1">
            SORT BY :
            <span class="ml-2 font-bold">{{ translate(sortCriteria) }}</span>
          </div>
          <span class="transition-transform transform group-hover:rotate-180">
            <img :src="'/icon/icon_dropdown_sort.svg'" class="w-3" />
          </span>
        </div>
        <div class="absolute z-20 hidden group-hover:block font-bold text-base bg-white text-black py-5 rounded-[20px] shadow-lg -left-2">
          <div class="block px-10 py-1 hover:text-[#16256E]" @click="setSortCriteria('Latest')">{{ translate("Latest") }}</div>
          <div class="block px-10 py-1 hover:text-[#16256E]" @click="setSortCriteria('Earliest')">{{ translate("Earliest") }}</div>
          <div class="block px-10 py-1 hover:text-[#16256E]" @click="setSortCriteria('A - Z')">A - Z</div>
          <div class="block px-10 py-1 hover:text-[#16256E]" @click="setSortCriteria('Z - A')">Z - A</div>
        </div>
      </div>
    </div>
  </div>

  <div class="px-5 items-center justify-center">
    <div v-if="sliced.length > 0">
      <div data-aos="fade-up" class="grid lg:grid-cols-3 grid-cols-1 md:grid-cols-2 gap-8 mb-6">
        <div v-for="item in sliced" :key="item.slug">
          <NuxtLink :to="'/article/' + item.slug">
            <div class="group">
              <div class="img-wrapper relative w-full h-0 rounded-[30px]" style="padding-top: 66.67%">
                <img class="inner-img absolute top-0 left-0 w-full h-full object-cover rounded-[30px]" :src="item.thumbnail" :alt="item.title" />
              </div>
              <div class="mt-5">
                <div class="flex items-center space-x-2">
                  <p class="text-[#EC2029] uppercase text-sm font-bold">
                    {{ item.category }}
                  </p>
                  <div class="border-l border-gray-300 h-4"></div>
                  <span class="text-gray-400 text-sm">
                    {{ formatDate(item.published_at) }}
                  </span>
                </div>
                <p class="text-xl font-bold text-blue-800 mt-3 transition-colors duration-300 ease-in-out group-hover:text-red-600">
                  {{ item.title }}
                </p>
                <p class="mt-3 text-gray-600 line-clamp-3" v-html="item.preview"></p>
                <div class="flex items-center justify-between mt-6"></div>
              </div>
            </div>
          </NuxtLink>
        </div>
      </div>

      <!-- Pagination -->
      <div data-aos="fade-in" class="flex items-center justify-center space-x-2 py-10">
        <div @click="changePage(currentPage - 1)" :disabled="currentPage === 1" class="button-highlight relative bg-[#EC2029] text-white rounded-full py-[8px] px-[4px]">
          <div class="text-highlight items-center">
            <img src="/icon/icon_slide_right.svg" class="rotate-180 h-5 w-5" />
          </div>
        </div>

        <span v-for="page in totalPages" :key="page" @click="changePage(page)" class="cursor-pointer px-3 py-1 rounded-full" :class="page === currentPage ? 'text-black font-bold' : 'text-gray-700 hover:bg-gray-200'">
          {{ page }}
        </span>

        <div @click="changePage(currentPage + 1)" :disabled="currentPage === totalPages" class="button-highlight relative bg-[#EC2029] text-white rounded-full py-[8px] px-[4px]">
          <div class="text-highlight items-center py-2">
            <img src="/icon/icon_slide_right.svg" class="h-5 w-5" />
          </div>
        </div>
      </div>
    </div>
    <div v-else>Data Not Found</div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue"; // Import onMounted
import { useLanguageStore } from "~/stores/lang";

const languageStore = useLanguageStore;
const appConfig = useAppConfig();

const currentCategory = ref("All Categories");
const categories = ref(["All Categories", "K-Food", "K-Drama", "K-Beauty", "K-Fashion", "News & Event"]);

const items = ref([]);
const itemsPerPage = 12;
const currentPage = ref(1);
const sortCriteria = ref("Latest");

const totalPages = computed(() => Math.ceil(items.value.length / itemsPerPage));

const sliced = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage;
  const end = start + itemsPerPage;
  return sortItems(items.value).slice(start, end);
});

const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "long",
    year: "numeric",
  });
};

const translate = (key) => languageStore().translateWords(key);

// Call fetchData function when component is mounted
onMounted(() => {
  fetchData(currentCategory.value); // Fetch data for the default category
});

async function fetchData(category) {
  const url = category === "All Categories" ? `${import.meta.env.VITE_API_URL}/api/articles` : `${import.meta.env.VITE_API_URL}/api/articles?category=${category}`;

  try {
    const response = await fetch(url);
    const data = await response.json();
    items.value = data.data;
  } catch (error) {
    console.error("Error fetching articles:", error);
  }
}

async function getCategory(category) {
  currentCategory.value = category;
  fetchData(category);
}

function setSortCriteria(criteria) {
  sortCriteria.value = criteria;
  currentPage.value = 1;
}

function sortItems(items) {
  return items.sort((a, b) => {
    const dateA = new Date(a.published_at);
    const dateB = new Date(b.published_at);

    switch (sortCriteria.value) {
      case "Latest":
        return dateB - dateA; // Sort descending by date
      case "Earliest":
        return dateA - dateB; // Sort ascending by date
      case "A - Z":
        return a.title.localeCompare(b.title); // Sort alphabetically A-Z
      case "Z - A":
        return b.title.localeCompare(a.title); // Sort alphabetically Z-A
      default:
        return 0; // No sorting
    }
  });
}

function changePage(page) {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page;
    document.getElementById("kbuzz-section").scrollIntoView({ behavior: "smooth", block: "start" });
  }
}
</script>

<style>
.button-cat {
  border: 1px solid #ec1f29;
  border-radius: 50px;
  width: 100%;
  display: block;

  background: linear-gradient(to right, #ec1f29 50%, #ec1f2900 50%);
  background-size: 200% 100%;
  background-position: right bottom;
  transition: all 0.5s ease-out;
}

.button-cat:hover {
  background-position: left bottom;
}

.text-cat {
  text-align: center;
  font-size: 16px;
  transition: all 0.6s ease-out;
  display: block;
}

.text-cat:hover {
  color: white;
}

.img-wrapper {
  overflow: hidden;
}

.inner-img {
  transition: 0.3s;
}

.inner-img:hover {
  transform: scale(1.1);
}

.button-highlight {
  border-radius: 50px;
  display: block;
  background: linear-gradient(to right, #273a97 50%, #ec1f29 50%);
  background-size: 200% 100%;
  background-position: right bottom;
  transition: all 0.5s ease-out;
}

.button-highlight:hover {
  background-position: left bottom;
}

.text-highlight {
  text-align: center;
  font-size: 16px;
  color: white;
  transition: all 0.6s ease-out;
  display: block;
}

.text-highlight:hover {
  color: white;
}
</style>
