(function ($, Drupal, drupalSettings, once) {

  'use strict';

  Drupal.behaviors.nodehiveActivityBlock = {
    attach: function (context, settings) {
      const activityContent = document.querySelector(".nodehive-activity-block .activity-content");
      const activityBlock = document.querySelector(".nodehive-activity-block");
      const defaultButton = document.querySelector(".activity-tabs .button[data-action='team']");
      const number_of_action = drupalSettings.nodehiveActivityBlock.numberOfItems;
      const workflow = drupalSettings.nodehiveActivityBlock.workflow;

      function fetchContent(action, number_of_action, workflow) {
        fetch(`/nodehive/activity-block/${action}/${number_of_action}/${workflow}`, {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
          },
        })
          .then((response) => response.text())
          .then((html) => {
            activityContent.innerHTML = html;
          })
          .catch((error) => console.error("Error:", error));
      }

      if (defaultButton) {
        defaultButton.classList.add("active");
        fetchContent("team", number_of_action, workflow);
      }

      activityBlock.addEventListener("click", function (event) {
        const button = event.target;

        if (button.classList.contains("button")) {
          event.preventDefault();

          const action = button.getAttribute("data-action");

          document.querySelectorAll(".activity-tabs .button").forEach((btn) => {
            btn.classList.remove("active");
          });

          button.classList.add("active");

          fetchContent(action, number_of_action, workflow);
        }
      });
    }
  };

})(jQuery, Drupal, drupalSettings, once);
