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

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

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

            if (this.filterType == "more") {
               this.list.insertAdjacentHTML("beforeend", html);
            } else {
               this.list.innerHTML = html;
            }

            if (hide_more_btn) {
               this.showMoreBtn.classList.add("hide");
            } else {
               this.showMoreBtn.classList.remove("hide");
            }
         });
   }

   setPage(page, moreBtnPage = 1) {
      this.filter.page = page;
      this.showMoreBtn.setAttribute("data-page", moreBtnPage);
   }

   initBlogFilter() {
      this.filter = { action: "filter_posts" };
      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.filterType = "tab";
            this.setPage(this.starterPage, +this.starterPage + 1);

            this.filter.cat = tab.dataset.id;
            this.filterPosts();
         });
      });

      const showMore = this.field.querySelector(".recent-articles__link");
      this.showMoreBtn = showMore;

      showMore.addEventListener("click", () => {
         const nextPage = showMore.dataset.page;

         this.filterType = "more";

         this.setPage(nextPage, +nextPage + 1);

         this.filterPosts();
      });
   }

   init() {
      this.list = this.field.querySelector(".recent-articles__list");
      this.initBlogFilter();
   }
}

function initBlogPage() {
   const page = document.querySelector(".blog-page");
   new BlogPage(page);
}

export { initBlogPage };
