import { hideLoader, showLoader } from "../utils/utils.js";

class CasesPage {
   /**
    *
    * @param {HTMLElement} field
    */
   constructor(field) {
      this.field = field;

      if (field) {
         this.starterPage = this.field.dataset.currentPage;
         this.init();
      }
   }

   filterCases() {
      showLoader(this.casesContent);
      fetch("/wp-admin/admin-ajax.php", {
         method: "POST",
         body: new URLSearchParams(this.filter),
      })
         .then((res) => res.json())
         .then((data) => {
            const { html, pagination } = data;

            this.list.innerHTML = html;
            this.pagination.innerHTML = pagination;
         })
         .finally(() => {
            hideLoader(this.casesContent);
         });
   }

   initCasesFilter() {
      this.filter = { action: "filter_cases" };
      const tabs = this.field.querySelectorAll(".tabs-nav__item");
      tabs.forEach((tab) => {
         tab.addEventListener("click", () => {
            tabs.forEach((t) => t.classList.remove("active"));
            tab.classList.add("active");

            this.filter.page = 1;
            this.filter.cat = tab.dataset.id;
            this.filterCases();
         });
      });

      this.pagination.addEventListener("click", (e) => {
         const target = e.target;
         console.log(target);

         let page = target.dataset.page;

         if (!page) {
            const pageBtn = target.closest("[data-page]");

            page = pageBtn ? pageBtn.dataset.page : null;
         }

         console.log(page);

         if (page) {
            this.filter.page = page;
            this.filterCases();
         }
      });
   }

   init() {
      this.list = this.field.querySelector(".cases__list");
      this.casesContent = this.field.querySelector(".cases__content");
      this.pagination = this.field.querySelector("#pagination");
      this.initCasesFilter();
   }
}

function initCasesPage() {
   const page = document.querySelector(".cases-page");
   new CasesPage(page);
}

export { initCasesPage };
