document.addEventListener("DOMContentLoaded", function () {

    // countdown ----------
    let timeRemaining = 72509; // 20h 08m 29s in seconds

    const hoursEl = document.getElementById('hours');
    const minutesEl = document.getElementById('minutes');
    const secondsEl = document.getElementById('seconds');
    const messageEl = document.getElementById('timer-message');

    function updateCountdown() {
        if (timeRemaining >= 0) {
            const hours = Math.floor(timeRemaining / 3600);
            const minutes = Math.floor((timeRemaining % 3600) / 60);
            const seconds = timeRemaining % 60;

            hoursEl.textContent = hours < 10 ? '0' + hours : hours;
            minutesEl.textContent = minutes < 10 ? '0' + minutes : minutes;
            secondsEl.textContent = seconds < 10 ? '0' + seconds : seconds;

            timeRemaining--;
        } else {
            messageEl.textContent = 'Time expired!';
            clearInterval(timerInterval);
        }
    }

    const timerInterval = setInterval(updateCountdown, 1000);
    updateCountdown(); // initial render


    // swipper js --------------
    var swiper = new Swiper(".thumb_slider", {
        loop: true,
        spaceBetween: 15,
        slidesPerView: 4,
        freeMode: true,
        watchSlidesProgress: true,
    });
    var swiper2 = new Swiper(".product_slider", {
        loop: true,
        spaceBetween: 10,
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
        thumbs: {
            swiper: swiper,
        },
    });


    // faq ---------------
    const faqItems = document.querySelectorAll(".save56-faq-itemTitle");

    faqItems.forEach(item => {
        item.addEventListener("click", () => {
            item.classList.toggle("activesave56-faq");
            const panel = item.nextElementSibling;

            if (panel.style.maxHeight) {
                panel.style.maxHeight = null;
            } else {
                panel.style.maxHeight = panel.scrollHeight + "px";
            }
        });
    });


    // review part duplicate -------------
    const moreBtn = document.querySelector('.more_btn a');
    const reviewPart = document.querySelector('.review_part');
    const reviewSection = reviewPart.parentNode; 

    if (moreBtn && reviewPart) {
        moreBtn.addEventListener('click', function(event) {
            event.preventDefault(); 

            // Clone the review_part element
            const clonedReview = reviewPart.cloneNode(true);

            // You might want to modify content in the cloned review, e.g., the time, if needed.
            // For now, it's an exact duplicate.

            // Insert the cloned review before the "Show More" button
            reviewSection.insertBefore(clonedReview, moreBtn.parentNode);
        });
    }


    // bottomStickyATC
    const bottomATC = document.getElementById('bottomStickyATC');

    // Add event listener for scroll event for the bottom sticky ATC
    window.addEventListener('scroll', function () {
        if (window.scrollY >= 1200) {
            bottomATC.classList.add('is-active');
        } else {
            bottomATC.classList.remove('is-active');
        }
    });

    // Scrolls to first CTA if top bar is clicked
    function save56scrollToCTA() {
        if (window.innerWidth < 1000) {
            const target = document.getElementById('save56-scrollId');
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth'
                });
            }
        }
    }


});


document.addEventListener("DOMContentLoaded", function () {

    //  Facebook ViewContent Tracking
    function safeTrackFBViewContent() {
        if (typeof fbq === 'function') {
            fbq('track', 'ViewContent');
        } else {
            setTimeout(safeTrackFBViewContent, 100);
        }
    }
    safeTrackFBViewContent();

    //  Quantity Selector Logic
    const outOfStockQuant = 'OUT_OF_STOCK'; // Replace with your actual out-of-stock quantity value
    const quantitySelectors = document.querySelectorAll('.save56-quantity-selector-card');

    quantitySelectors.forEach(selector => {
        selector.addEventListener('click', function (event) {
            let targetElement = event.target;

            // Find the correct selector element in case inner child was clicked
            while (targetElement && !targetElement.classList.contains('save56-quantity-selector-card')) {
                targetElement = targetElement.parentElement;
            }

            if (!targetElement) return;

            const currentSelector = targetElement;
            const currentSelectorQty = currentSelector.dataset.qty;

            if (currentSelectorQty == outOfStockQuant) return;

            const previousSelector = document.querySelector('.current-qty');
            if (previousSelector && previousSelector.dataset.qty == currentSelectorQty) return;

            // Toggle active class
            if (previousSelector) previousSelector.classList.remove('current-qty');
            currentSelector.classList.add('current-qty');

            // Update gift highlights
            const overlays = document.querySelectorAll('.save56-gift-overlay');
            const cards = document.querySelectorAll('.save56-gift-card');
            const titles = document.querySelectorAll('.save56-gift-title');

            for (let i = 0; i < overlays.length; i++) {
                if (i < currentSelectorQty) {
                    overlays[i]?.classList.add('is-active');
                    cards[i]?.classList.add('is-active');
                    titles[i]?.classList.add('is-active');
                } else {
                    overlays[i]?.classList.remove('is-active');
                    cards[i]?.classList.remove('is-active');
                    titles[i]?.classList.remove('is-active');
                }
            }

            // Update Save %
            const saveEl = document.getElementById('subandsavediscount');
            if (saveEl) {
                if (currentSelectorQty == 1) {
                    saveEl.innerHTML = "20";
                } else if (currentSelectorQty == 2) {
                    saveEl.innerHTML = "37";
                } else if (currentSelectorQty == 3) {
                    saveEl.innerHTML = "52";
                } else if (currentSelectorQty == 4) {
                    saveEl.innerHTML = "56";
                }
            }

            // Update ATC URL
            const atcBtn = document.querySelector('.save56-product-atc');
            if (atcBtn) {
                atcBtn.href = `/pages/save-56-build-your-bundle-2?sticks=${currentSelectorQty}`;
            }
        });
    });

    //  Format Date Function
    function formatDate(date) {
        const suffixes = ["th", "st", "nd", "rd"];
        const day = date.getDate();
        const month = date.toLocaleString('default', {
            month: 'short'
        });

        let suffix = "th";
        if (day % 10 >= 1 && day % 10 <= 3 && ![11, 12, 13].includes(day)) {
            suffix = suffixes[day % 10];
        }

        return `${month}. ${day}${suffix}`;
    }

    //  Set Today's Date for [data-order-by]
    document.querySelectorAll('[data-order-by]').forEach(el => {
        el.textContent = formatDate(new Date());
    });


    
});