// source --> https://sex-matters.org/wp-content/plugins/ninja-forms-uploads/assets/js/nfpluginsettings.js?ver=3.3.29 

jQuery(function ($) {
    /* 
    localized variables passed through params object:
    params.clearLogRestUrl
    params.clearLogButtonId  
    params.downloadLogRestUrl
    params.downloadLogButtonId
    
    */

 $("#"+params.clearLogButtonId).on("click", () => {

   $.post(
      params.clearLogRestUrl,
     { },
     function (json) {
       console.log(json);
     }
   );
 });

 $("#"+params.downloadLogButtonId).on("click", () => {
   $.post(
     params.downloadLogRestUrl,
     {},
     function (json) {
       let download = json.data;

       var blob = new Blob([download], { type: "json" });

       var a = document.createElement("a");
       a.download = "nf-file-uploads-debug-log.json";
       a.href = URL.createObjectURL(blob);
       a.dataset.downloadurl = ["json", a.download, a.href].join(":");
       a.style.display = "none";
       document.body.appendChild(a);
       a.click();
       document.body.removeChild(a);
       setTimeout(function () {
         URL.revokeObjectURL(a.href);
       }, 15000);
     }
   );
 });

return;

});
// source --> https://sex-matters.org/wp-content/themes/sex-matters-live/app/blocks/accordion/frontend.js?ver=1781682005 
document.addEventListener("DOMContentLoaded", function () {
  // First, fix duplicate IDs by assigning unique IDs dynamically
  fixAccordionIDs();

  // Then initialize the accordions
  initializeAccordions();

  // Add expand/collapse all buttons where needed
  addExpandCollapseAllButtons();
});

/**
 * Fixes duplicate accordion IDs by assigning unique IDs at runtime
 */
function fixAccordionIDs() {
  // Find all accordion containers
  const accordionContainers = document.querySelectorAll(".accordion-container");

  // Process each container separately to avoid conflicts between multiple accordions
  accordionContainers.forEach((container, containerIndex) => {
    const accordion = container.querySelector(".accordion");
    if (!accordion) return;

    // Get all accordion items in this container
    const items = accordion.querySelectorAll(".accordion__item");

    // Process each item
    items.forEach((item, itemIndex) => {
      const trigger = item.querySelector(".accordion__trigger");
      const content = item.querySelector(".accordion__content");

      if (trigger && content) {
        // Generate a unique ID based on container and item index
        const uniqueID = `accordion-${containerIndex}-item-${itemIndex}`;

        // Update the content ID
        content.id = uniqueID;

        // Update the trigger attributes to reference the new ID
        trigger.setAttribute("aria-controls", uniqueID);
        trigger.setAttribute("href", "#" + uniqueID);
      }
    });
  });
}

/**
 * Initialize all accordions on the page
 */
function initializeAccordions() {
  // Target all accordion containers
  const accordionContainers = document.querySelectorAll(".accordion-container");

  accordionContainers.forEach((container) => {
    const accordion = container.querySelector(".accordion");
    if (!accordion) return;

    const triggers = accordion.querySelectorAll(".accordion__trigger");

    triggers.forEach((trigger) => {
      const item = trigger.closest(".accordion__item");
      const content = item.querySelector(".accordion__content");

      if (trigger && content) {
        // Only add event listener if not already initialized
        if (!trigger.hasAttribute("data-initialized")) {
          // Function to handle accordion toggle
          const toggleAccordion = function (event) {
            // Prevent default link behavior
            event.preventDefault();

            // Stop event from reaching parent accordions
            event.stopPropagation();

            const isExpanded = trigger.getAttribute("aria-expanded") === "true";

            // Toggle current item
            trigger.setAttribute("aria-expanded", !isExpanded);

            // Use classList for toggling to avoid reflow
            content.classList.toggle("is-hidden", isExpanded);
            content.hidden = isExpanded; // Keep for accessibility

            item.classList.toggle("accordion__item--is-open");

            // Update icon
            const icon = trigger.querySelector(".accordion__icon");
            if (icon) {
              icon.classList.toggle("accordion__icon--is-open");
            }

            // If opening, initialize any nested accordions
            if (!isExpanded) {
              // Initialize nested accordions immediately
              initializeAccordions();
            }

            // Update the URL hash if the accordion is opened
            if (!isExpanded && content.id) {
              // Update the URL hash without causing a scroll jump
              const scrollPosition = window.pageYOffset;
              window.location.hash = content.id;
              window.scrollTo(0, scrollPosition);
            }

            // Update expand/collapse all button state
            updateExpandCollapseButtonState(container);
          };

          // Use click event for better stability and to prevent page jumping
          trigger.addEventListener("click", toggleAccordion);

          // Mark as initialized to avoid duplicate handlers
          trigger.setAttribute("data-initialized", "true");
        }
      }
    });
  });
}

/**
 * Add expand/collapse all buttons to accordion containers with more than one item
 */
function addExpandCollapseAllButtons() {
  const accordionContainers = document.querySelectorAll(".accordion-container");

  accordionContainers.forEach((container) => {
    // Skip if this container already has buttons
    const existingButton = container.querySelector(
      ":scope > .accordion__expand-collapse-all"
    );
    if (existingButton) return;

    // Find direct accordion child (not nested ones)
    const accordion = container.querySelector(":scope > .accordion");
    if (!accordion) return;

    // Count direct accordion items (top-level only for the check)
    const directItems = accordion.querySelectorAll(
      ":scope > .accordion__item, :scope > .wp-block-sex-matters-accordion-item"
    );

    // Only add buttons if there's more than one accordion item
    if (directItems.length <= 1) return;

    // Create click handler shared by both buttons
    function handleExpandCollapseClick(event) {
      event.preventDefault();
      const buttons = container.querySelectorAll(
        ":scope > .accordion__expand-collapse-all"
      );
      const currentState = buttons[0].getAttribute("data-state");
      const shouldExpand = currentState === "collapsed";

      // Get ALL accordion items within this container (including nested)
      const allItems = accordion.querySelectorAll(
        ".accordion__item, .wp-block-sex-matters-accordion-item"
      );

      allItems.forEach((item) => {
        const trigger = item.querySelector(".accordion__trigger");
        const content = item.querySelector(".accordion__content");
        const icon = trigger ? trigger.querySelector(".accordion__icon") : null;

        if (trigger && content) {
          if (shouldExpand) {
            // Expand
            trigger.setAttribute("aria-expanded", "true");
            content.classList.remove("is-hidden");
            content.hidden = false;
            item.classList.add("accordion__item--is-open");
            if (icon) icon.classList.add("accordion__icon--is-open");
          } else {
            // Collapse
            trigger.setAttribute("aria-expanded", "false");
            content.classList.add("is-hidden");
            content.hidden = true;
            item.classList.remove("accordion__item--is-open");
            if (icon) icon.classList.remove("accordion__icon--is-open");
          }
        }
      });

      // Update both buttons' state and text
      const newState = shouldExpand ? "expanded" : "collapsed";
      const newText = shouldExpand ? "Collapse all" : "Expand all";
      buttons.forEach((btn) => {
        btn.setAttribute("data-state", newState);
        btn.textContent = newText;
      });

      // Initialize nested accordions if expanding
      if (shouldExpand) {
        initializeAccordions();
      }
    }

    // Create top button
    const topButton = document.createElement("button");
    topButton.type = "button";
    topButton.className = "accordion__expand-collapse-all";
    topButton.setAttribute("data-state", "collapsed");
    topButton.textContent = "Expand all";
    topButton.addEventListener("click", handleExpandCollapseClick);

    // Create bottom button
    const bottomButton = document.createElement("button");
    bottomButton.type = "button";
    bottomButton.className =
      "accordion__expand-collapse-all accordion__expand-collapse-all--bottom";
    bottomButton.setAttribute("data-state", "collapsed");
    bottomButton.textContent = "Expand all";
    bottomButton.addEventListener("click", handleExpandCollapseClick);

    // Insert top button at the start of the container
    container.insertBefore(topButton, container.firstChild);

    // Append bottom button at the end of the container
    container.appendChild(bottomButton);
  });
}

/**
 * Update the expand/collapse all button state based on current accordion states
 */
function updateExpandCollapseButtonState(container) {
  // Find all direct child buttons for this container
  const buttons = container.querySelectorAll(
    ":scope > .accordion__expand-collapse-all"
  );
  if (buttons.length === 0) return;

  const accordion = container.querySelector(":scope > .accordion");
  if (!accordion) return;

  const allItems = accordion.querySelectorAll(
    ".accordion__item, .wp-block-sex-matters-accordion-item"
  );
  let expandedCount = 0;

  allItems.forEach((item) => {
    const trigger = item.querySelector(".accordion__trigger");
    if (trigger && trigger.getAttribute("aria-expanded") === "true") {
      expandedCount++;
    }
  });

  // Update both buttons based on whether all items are expanded
  const allExpanded = expandedCount === allItems.length;
  const newState = allExpanded ? "expanded" : "collapsed";
  const newText = allExpanded ? "Collapse all" : "Expand all";
  buttons.forEach((btn) => {
    btn.setAttribute("data-state", newState);
    btn.textContent = newText;
  });
};