import {gsap, Power4} from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger)

export default (() => {
    const animatedValues = document.querySelectorAll('.animated-values');

    animatedValues.forEach((el) => {
        const single = el.querySelector('.animated-content .value')
        const duration = Number(single.dataset.duration) / 1000
        const trigger = single.dataset.trigger

        const timeline = gsap.timeline()

        timeline.from(single, {
            textContent: 0,
            duration: duration,
            ease: Power4.easeOut,
            snap: {
                textContent: 1,
            },
            stagger: {
                each: 1,
                ease: Power4.easeOut,
            },
        })

        timeline.pause()

        if (trigger == 'scrolltrigger') {
            ScrollTrigger.create({
                start: 'top center+=30%',
                end: 'bottom center+=30%',
                trigger: single,
                onEnter: () => {
                    timeline.restart()
                },
                onLeaveBack: () => {
                    timeline.reverse()
                },
            })
        } else {
            checkWhenBecomesVisible()

            function checkWhenBecomesVisible() {
                setInterval(() => {
                    if (isCurrentlyVisible() == true) {
                        timeline.play()
                    } else {
                        timeline.time(0).pause()
                    }
                }, 400);
            }

            function isCurrentlyVisible() {
                let visible = true
                let element = single
                while (element.parentNode && element.parentNode.nodeName.toLowerCase() != 'body') {
                    element = element.parentNode;
                    if (window.getComputedStyle(element).opacity == 0 || 
                        window.getComputedStyle(element).visibility == 'hidden' || 
                        window.getComputedStyle(element).display == 'none') {
                        visible = false
                    }
                }
                return visible
            }
        }
    })
})()