import { animateCardsOnScroll } from "../handlers/handlerScrollAnimations.js";
import fetchData from "../http/http.js";
import { hideLoader, showLoader } from "../utils/utils.js";

class Case {
   activeClassName = "active";

   constructor() {
      this.wrapper = document.querySelector(".cases") || null;
      this.casesContent = document.querySelector(".cases__content") || null;
      this.initFields();
      this.initHandlers();
   }

   initFields() {
      this.initCaseArchiveFields();
   }

   wrapperIsExist() {
      return Boolean(this.wrapper);
   }

   initCaseArchiveFields() {
      if (this.wrapperIsExist()) {
         this.casesTabs = this.wrapper.querySelectorAll(".cases__tab");
         this.casesList = this.wrapper.querySelector(".cases__list");
         this.casesIds = JSON.parse(this.casesList.dataset.cases || "[]");
      }
   }

   initHandlers() {
      if (this.wrapperIsExist()) {
         this.initTabsFilter();
      }
   }

   initTabsFilter() {
      this.casesTabs.forEach((tab) => {
         tab.addEventListener("click", async () => {
            const termSlug = tab.dataset.slug || "all";
            this.setActiveTab(tab);
            await this.caseFilter(termSlug);
         });
      });
   }

   setActiveTab(tab) {
      this.casesTabs.forEach((item) => item.classList.remove(this.activeClassName));
      tab.classList.add(this.activeClassName);
   }

   showCases(res) {
      if (res && res.success) {
         this.casesList.innerHTML = res.data.posts;
         const newCards = this.casesList.querySelectorAll(".cases__item");
         if (newCards.length) {
            animateCardsOnScroll(newCards);
         }
      } else {
         this.casesList.innerHTML = `<div class="cases__empty">${res?.data?.message || "Ошибка загрузки кейсов"}</div>`;
      }
   }

   async caseFilter(termSlug) {
      showLoader(this.casesContent);

      try {
         const formData = new FormData();

         formData.append("action", "filter_case");
         formData.append("term", termSlug);

         this.casesIds.forEach((id) => {
            formData.append("cases_ids[]", id);
         });

         const res = await fetchData(formData);

         this.showCases(res);
      } finally {
         hideLoader(this.casesContent);
      }
   }
}

export { Case };
