function getUTMSource() {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get('utm_source');
}

$(document).ready(function () {
    setInterval(() => {
        if (document.querySelector("#discount-popup").parentElement.style.margin !== "0px !important") {
            document.querySelector("#discount-popup").parentElement.style.margin = "0px !important";
            document.querySelector("#discount-popup").parentElement.style.padding = "0px !important";
            document.querySelector("#discount-popup").parentElement.setAttribute("style", "margin: 0px !important; padding: 0px !important;");
        }
    }, 500);

    setTimeout(() => {
        clearInterval(interval);
    }, 10000);

});

window.addEventListener('message', function (event) {
    if (event.origin === "https://arp.avon.com") {
        var iframe = document.querySelector('#iframe-form');
        var iframeWrapper = document.querySelector('.iframe-wrapper');

        if (!iframe || !iframeWrapper) {
            console.error("Iframe or wrapper not found");
            return;
        }

        try {
            var data = JSON.parse(event.data);


            if (event.data === "formSent") {
                const utmSource = getUTMSource();
                // Send event to Google Analytics
                gtag('event', 'form_completion', {
                    'event_category': 'Registration',
                    'event_label': utmSource || 'No UTM Source'
                });
            }

            if (data.event === "PageLoad") {
                var baseHeight, heightAdjustment;

                if (window.innerWidth < 455) {
                    heightAdjustment = 350;
                } else if (window.innerWidth < 960) {
                    heightAdjustment = 250;
                } else {
                    heightAdjustment = 0;
                }

                switch (data.eventAction) {
                    case "/contactDetails":
                        baseHeight = 680;
                        break;
                    case "/homeAddress":
                        baseHeight = 650;
                        break;
                    case "/summary":
                        baseHeight = 980;
                        break;
                    default:
                        baseHeight = 680; // Default height
                }

                var newHeight = baseHeight + heightAdjustment;
                iframe.style.setProperty('height', newHeight + 'px', 'important');
                iframeWrapper.style.setProperty('height', newHeight + 'px', 'important');
            }
        } catch (e) {
            if (event.data === "formSubmit") {
                var formSubmitHeight = 980 + (window.innerWidth < 768 ? 300 : (window.innerWidth < 960 ? 200 : 0));
                iframe.style.setProperty('height', formSubmitHeight + 'px', 'important');
                iframeWrapper.style.setProperty('height', formSubmitHeight + 'px', 'important');


            } else {
                console.error("Failed to parse message data:", e);
            }
        }
    } else {
        console.log("Message from unexpected origin:", event.origin);
    }
});

document.addEventListener('DOMContentLoaded', function () {
    const faqItems = document.querySelectorAll('.faq-item');
    const popup = document.getElementById('discount-popup');
    const closeBtn = document.getElementById('close-popup');
    const discountBtn = popup.querySelector('.btn');
    const formSection = document.querySelector('#form');
    let popupShown = false;

    // FAQ functionality
    faqItems.forEach(item => {
        const question = item.querySelector('.faq-question');
        question.addEventListener('click', () => {
            faqItems.forEach(otherItem => {
                if (otherItem !== item) {
                    otherItem.classList.remove('active');
                }
            });
            item.classList.toggle('active');
        });
    });

    // AOS initialization
    AOS.init({
        duration: 1000,
        once: true,
        disable: "mobile"
    });

    // Popup functionality
    function isElementInViewport(el, threshold = 0.3) {
        const rect = el.getBoundingClientRect();
        const windowHeight = window.innerHeight || document.documentElement.clientHeight;

        // Calculate how much of the element is visible
        const visibleHeight = Math.min(rect.bottom, windowHeight) - Math.max(rect.top, 0);
        const percentVisible = visibleHeight / rect.height;

        // Consider the element in view if the visible portion exceeds the threshold
        return percentVisible > threshold;
    }

    function showPopup() {
        if (!popupShown && !isElementInViewport(formSection)) {
            popup.classList.add('show');
            popupShown = true;
            startConfetti();
        }
    }

    function hidePopup() {
        popup.classList.remove('show');
        stopConfetti();
    }

    // Show popup after 10 seconds, but only if the form is not in view
    setTimeout(() => {
        if (!isElementInViewport(formSection)) {
            showPopup();
        }
    }, 10000);

    // Check form visibility on scroll
    window.addEventListener('scroll', () => {
        if (isElementInViewport(formSection) && popup.classList.contains('show')) {
            hidePopup();
        }
    });

    closeBtn.addEventListener('click', hidePopup);

    window.addEventListener('click', function (event) {
        if (event.target == popup) {
            hidePopup();
        }
    });

    // Confetti effect
    const canvas = document.getElementById('confetti-canvas');
    let ctx = canvas.getContext('2d');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    let confetti = [];

    function startConfetti() {
        for (let i = 0; i < 100; i++) {
            confetti.push({
                x: Math.random() * canvas.width,
                y: Math.random() * canvas.height,
                size: Math.random() * 5 + 5,
                color: `hsl(${Math.random() * 360}, 100%, 50%)`,
                speed: Math.random() * 3 + 1
            });
        }
        animateConfetti();
    }

    function animateConfetti() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        confetti.forEach((c, index) => {
            ctx.beginPath();
            ctx.arc(c.x, c.y, c.size, 0, 2 * Math.PI);
            ctx.fillStyle = c.color;
            ctx.fill();
            c.y += c.speed;
            if (c.y > canvas.height) {
                confetti.splice(index, 1);
            }
        });
        if (confetti.length > 0) {
            requestAnimationFrame(animateConfetti);
        }
    }

    function stopConfetti() {
        confetti = [];
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    }

    // Smooth scrolling function
    function smoothScroll(e) {
        e.preventDefault();
        const targetId = this.getAttribute('href');
        const targetElement = document.querySelector(targetId);
        if (targetElement) {
            targetElement.scrollIntoView({ behavior: 'smooth' });

            // Add shake effect if it's the form section
            if (targetId === '#form') {
                targetElement.classList.add('shake');
                setTimeout(() => {
                    targetElement.classList.remove('shake');
                }, 820);
            }
        }
    }

    // Apply smooth scrolling to all internal links
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', smoothScroll);
    });

    // Update the popup button click handler
    if (discountBtn) {
        discountBtn.addEventListener('click', function (e) {
            e.preventDefault();
            hidePopup();
            smoothScroll.call(this, e);
        });
    }
    console.log("Form in viewport on load:", isElementInViewport(formSection));

    setTimeout(() => {
        console.log("Form in viewport after 10s:", isElementInViewport(formSection));
        if (!isElementInViewport(formSection)) {
            showPopup();
        }
    }, 10000);

    window.addEventListener('scroll', () => {
        console.log("Form in viewport on scroll:", isElementInViewport(formSection));
    });


    // Find and remove the <base> element
    const baseElement = document.querySelector('base');
    if (baseElement) {
        baseElement.remove();
    }

    // Reset the base URL to the default (current page URL)
    document.baseURI = window.location.href;



});
