/**********************************
 *  DOWNUP
 * This script enables a toggle feature for elements with the class "downup-label" and their parent containers ".downup".
 * It allows for expanding/collapsing content, handling clicks both to open/close items and to close them when clicking outside.
 **********************************/

// Select all elements that trigger the down-up action.
const clickName = document.querySelectorAll(".downup-label");
// Select all parent elements that should receive the "active" state.
const clickParent = document.querySelectorAll(".downup");

// Function to remove "active" class from all triggers and their parents.
function removeAllActiveClasses() {
  clickName.forEach((el) => el.classList.remove("active"));
  clickParent.forEach((el) => el.classList.remove("active"));
}

// Listen for clicks on the document to toggle the down-up feature.
document.addEventListener("click", function (e) {
  // Check if the clicked element is a down-up trigger.
  if (e.target && e.target.matches(".downup-label")) {
    const wasActive = e.target.classList.contains("active");
    // First, remove "active" from all elements to reset the state.
    removeAllActiveClasses();

    // If the clicked element was not already active, activate it and its parent.
    if (!wasActive) {
      e.target.classList.add("active");
      const parentDroplist = e.target.closest(".downup");
      if (parentDroplist) {
        parentDroplist.classList.add("active");
      }
    }
  }
});

// Listen for mouseup events to close active items when clicking outside.
document.addEventListener("mouseup", function (e) {
  // If the click is outside active down-up elements, remove "active" classes.
  if (!e.target.closest(".downup.active, .downup-label.active")) {
    removeAllActiveClasses();
  }
});

// Attach event listeners to elements meant to close the down-up components explicitly.
document.querySelectorAll(".downup-close").forEach((droplistList) => {
  droplistList.addEventListener("click", function () {
    removeAllActiveClasses();
  });
});
