import Lottie from 'lottie-web/build/player/lottie_light.min.js'
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import lottie from 'lottie-web/build/player/lottie_light.min.js'

gsap.registerPlugin(ScrollTrigger)

export default (() => {
    const animations = document.querySelectorAll('.lottie-animation .wrapper')
    animations && animations.forEach(animation => {
        if (animation.dataset.animation) {
            const activateOnScroll = animation.dataset.activate
            const loop = Boolean(animation.dataset.loop)
            const speed = animation.dataset.speed
            let autoplay = Boolean(activateOnScroll ? false : true)

            let anim = lottie.loadAnimation({
                container: animation,
                renderer: 'svg',
                loop: loop,
                autoplay: autoplay,
                path: animation.dataset.animation,
            });

            if(anim && speed) {
                anim.setSpeed(speed)
            } 

            if(activateOnScroll) {
                ScrollTrigger.create({
                    trigger: animations,
                    end: 'bottom start',
                    start: 'start bottom',
                    onEnter: () => {
                        anim.play()
                    },

                    onLeave: () => {
                        anim.stop()
                    },

                    onEnterBack: () => {
                        anim.play()
                    },

                    onLeaveBack: () => {
                        anim.stop()
                    },
                })
            }
        }
    })
})()