document.addEventListener('DOMContentLoaded', () => {
    // Initialize Lenis with specific settings for a "weighty", buttery GSAP feel
    const lenis = new Lenis({
        lerp: 0.07,
        smoothWheel: true,
    });

    // Basic requestAnimationFrame loop
    function raf(time) {
        lenis.raf(time);
        requestAnimationFrame(raf);
    }

    requestAnimationFrame(raf);

    // Stacking Cards CSS Transition Trigger
    const cards = document.querySelectorAll('.service-item');
    if (cards.length > 0) {
        lenis.on('scroll', () => {
            const windowHeight = window.innerHeight;

            cards.forEach((card, index) => {
                const rect = card.getBoundingClientRect();

                // 1. Entry state: When the card enters the viewport
                if (rect.top < windowHeight * 0.9) {
                    card.classList.add('is-visible');
                } else {
                    card.classList.remove('is-visible');
                }

                // 2. Covered state: When the NEXT card starts sliding up over this one
                if (index < cards.length - 1) {
                    const nextCard = cards[index + 1];
                    const nextRect = nextCard.getBoundingClientRect();

                    // When the next card reaches the top 25% of the viewport 
                    // (i.e. has covered 75% of the screen/card),
                    // trigger the CSS transition to push the current card back
                    if (nextRect.top < windowHeight * 0.25) {
                        card.classList.add('is-covered');
                    } else {
                        card.classList.remove('is-covered');
                    }
                }
            });
        });

        // Trigger once to set initial states
        lenis.emit();
    }

    // Parallax logic for Chart Section
    const parallaxImg = document.querySelector('.kaz-chart-leak-bg');
    const chartSection = document.querySelector('.kaz-chart-section');

    if (parallaxImg && chartSection) {
        function updateParallax() {
            const rect = chartSection.getBoundingClientRect();
            const windowHeight = window.innerHeight;

            // Proveravamo da li je sekcija uopšte vidljiva na ekranu
            if (rect.top < windowHeight && rect.bottom > 0) {
                // Progres ide od 0 (sekcija ulazi odozdo) do 1 (sekcija izlazi odozgo)
                const progress = (windowHeight - rect.top) / (windowHeight + rect.height);

                // Slika se kreće od -15% do +15% po Y osi
                const yPos = (progress * 30) - 15;

                parallaxImg.style.transform = `translateY(${yPos}%)`;
            }
        }

        // Okidamo funkciju na Lenis skrol događaj
        lenis.on('scroll', updateParallax);

        // Okinemo jednom odmah da namestimo sliku na početnu poziciju
        updateParallax();
    }
});
