document.addEventListener("DOMContentLoaded", function () {
    let page = 1;
    let selectedCategory = ""; // Default to empty (all items)

    // Automatically load initial posts when the page loads
    aump_loadMorePosts();

    // Load more projects on button click
    document.getElementById("aump_load-more-btn")?.addEventListener("click", aump_loadMorePosts);
            
document.querySelectorAll(".aump-all-filter").forEach(el => el.classList.add("aump_active"));

    // Filter projects based on category click
    document.addEventListener("click", function (event) {
        if (event.target.classList.contains("aump_category-filter")) {
            document.querySelectorAll(".aump_category-filter").forEach(el => el.classList.remove("aump_active"));
            event.target.classList.add("aump_active");

            selectedCategory = event.target.dataset.category || ""; // If empty, show all

            document.getElementById("aump_projects-container").innerHTML = ""; // Clear existing projects
            page = 1; // Reset page number
            document.getElementById("aump_load-more-btn").style.display = "inline-block"; // Show button if hidden
            aump_loadMorePosts();
        }
    });

    // Function to load posts
    function aump_loadMorePosts() {
        const btn = document.getElementById("aump_load-more-btn");
        if (!btn) return;

        btn.disabled = true; // Disable button during request

        fetch(aump_loadmore.ajaxurl, {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: new URLSearchParams({
                action: "aump_load_more",
                page: page,
                nonce: aump_loadmore.nonce,
                category: selectedCategory, // Pass selected category ("" for all)
            }),
        })
            .then(response => response.text())
            .then(response => {
                if (response.trim()) {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(response, "text/html");
                    const newItems = doc.querySelectorAll(".aump_project");

                    const container = document.getElementById("aump_projects-container");
                    newItems.forEach(item => {
                        item.style.display = "none";
                        container.appendChild(item);
                        setTimeout(() => (item.style.display = "block"), 100);
                    });

                    page++;

                    // Hide the button if there are no more posts
                    if (doc.querySelector(".aump_no-more") || newItems.length < aump_loadmore.postsPerPage) {
                        btn.style.display = "none";
                    }
                } else {
                    btn.style.display = "none";
                }
            })
            .finally(() => (btn.disabled = false));
    }
});


// Above is done




document.addEventListener('DOMContentLoaded', function () {
	
	 let aump_open_in_popup = aumpSettings.aump_open_in_popup; // Store initial value
  //console.log("Auto Scroll Disabled:", autoScrollDisabled);
	if (!aump_open_in_popup) {
    return; // Exit if auto-scroll is disabled
  }
	
    const popup = document.getElementById('aump_project-popup');
    const popupContentArea = document.getElementById('aump_popup-content-area');
    const closePopup = document.querySelector('.aump_close-popup');
    const prevProject = document.querySelector('.aump_prev-project');
    const nextProject = document.querySelector('.aump_next-project');
    let currentIndex = null;

    // Open Popup Function
    function openPopup(url) {
        popup.style.display = 'flex';
        document.body.classList.add('no-scroll');
        popupContentArea.innerHTML = '<p class="loading-content-portfolio">Loading...</p>';
        fetch(url)
            .then(response => response.text())
            .then(data => {
                const content = new DOMParser().parseFromString(data, 'text/html');
                const projectContent = content.querySelector('.aump_single-portfolio'); // Assuming 'project-details' is the class in fetched content
                popupContentArea.innerHTML = projectContent ? projectContent.innerHTML : '<p>Content not found</p>';
            })
            .catch(error => {
                popupContentArea.innerHTML = '<p class="loading-content-portfolio">Error loading content</p>';
                console.error(error);
            });
    }

    // Close Popup Handler
    function closePopupHandler() {
        popup.style.display = 'none';
        document.body.classList.remove('no-scroll');
        popupContentArea.innerHTML = '';
    }

    // Event delegation for portfolio items
    document.body.addEventListener('click', function (e) {
        if (e.target.closest('.et_pb_portfolio_item')) {
            const item = e.target.closest('.et_pb_portfolio_item');
            e.preventDefault();
            const projectUrl = item.querySelector('a').getAttribute('href');
            currentIndex = Array.from(item.parentElement.children).indexOf(item);
            openPopup(projectUrl);
        }
        if (e.target === closePopup || e.target.closest('.aump_close-popup')) {
            closePopupHandler();
        }
        if (e.target === popup) {
            closePopupHandler();
        }
    });

    // Event listener for the previous and next buttons
    prevProject.addEventListener('click', function () {
        if (currentIndex > 0) {
            currentIndex -= 1;
            const prevUrl = document.querySelectorAll('.et_pb_portfolio_item')[currentIndex].querySelector('a').getAttribute('href');
            openPopup(prevUrl);
        }
    });

    nextProject.addEventListener('click', function () {
        const totalItems = document.querySelectorAll('.et_pb_portfolio_item').length;

        if (currentIndex < totalItems - 1) {
            currentIndex += 1;
            const nextUrl = document.querySelectorAll('.et_pb_portfolio_item')[currentIndex].querySelector('a').getAttribute('href');
            openPopup(nextUrl);
        } else {
            // When reaching the last item, trigger the "load more" button click
            const loadMoreBtn = document.querySelector('#aump_load-more-btn');
            if (loadMoreBtn) {
                loadMoreBtn.click();

                // Optionally, wait for the new items to load before continuing (you may need to adjust this part based on your site's behavior)
                setTimeout(function () {
                    // After loading, update the index and open the new item
                    const newTotalItems = document.querySelectorAll('.et_pb_portfolio_item').length;
                    if (newTotalItems > totalItems) {
                        currentIndex = totalItems; // Adjust index after new items load
                        const nextUrl = document.querySelectorAll('.et_pb_portfolio_item')[currentIndex].querySelector('a').getAttribute('href');
                        openPopup(nextUrl);
                    }
                }, 1000); // Adjust delay as necessary to allow time for items to load
            }
        }
    });
});


  // Initialize portfolio items for the first page load
  const portfolioItems = document.querySelectorAll('.et_pb_portfolio_item');
  portfolioItems.forEach((item, index) => {
    item.addEventListener('click', function (e) {
      e.preventDefault();
      const projectUrl = item.querySelector('a').getAttribute('href');
      currentIndex = index;
      openPopup(projectUrl);
    });

});


document.addEventListener('DOMContentLoaded', function () {
 let autoScrollDisabled = aumpSettings.autoScrollDisabled; // Store initial value
  //console.log("Auto Scroll Disabled:", autoScrollDisabled);
	if (autoScrollDisabled) {
    return; // Exit if auto-scroll is disabled
  }

  // Function to apply hover effects on portfolio images
  function applyHoverEffect(container) {
    const img = container.querySelector('img');
    container.addEventListener('mouseenter', function () {
      const imgHeight = img.offsetHeight;
      const containerHeight = container.offsetHeight;

      if (imgHeight > containerHeight) {
        img.style.transition = 'transform 3s linear'; // Adjust speed
        img.style.transform = `translateY(-${imgHeight - containerHeight}px)`;
      }
    });

    container.addEventListener('mouseleave', function () {
      img.style.transition = 'transform 1s linear'; // Reset speed
      img.style.transform = 'translateY(0)';
    });
  }

  // Event delegation for dynamically added .aump_portfolio_image elements
  document.body.addEventListener('mouseenter', function (e) {
    if (e.target.closest('.aump_portfolio_image')) {
      applyHoverEffect(e.target.closest('.aump_portfolio_image'));
    }
  }, true); // Use capture phase to ensure it works with dynamically added elements

  // Initial binding for already loaded elements
  document.querySelectorAll('.aump_portfolio_image').forEach(function (container) {
    applyHoverEffect(container);
  });
});