import videojs from 'video.js/dist/alt/video.novtt'
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'

export default (() => {
    window.addEventListener('load', () => {
        const videos = document.querySelectorAll('.wp-block-video')
    
        videos.forEach(function (el) {
            if(el.classList.contains('is-style-black') || el.classList.contains('is-style-light')) {
                const videoElement = el.querySelector('video')
                const source = videoElement.getAttribute('src')
                if(source) {
                    const createSource = document.createElement('source')
                    createSource.setAttribute('src', source)
                    videoElement.appendChild(createSource)
    
                    videoElement.classList.add('custom-video')
                    videoElement.classList.add('vjs-has-started')
                    videoElement.classList.add('video-js')
    
                    let player = videojs(videoElement, {
                        'preload': 'auto',
                        controlBar: {
                            volumePanel: {
                                inline: false,
                            },
                        },
                    })
                }
            }
        })

        const customPlayer = document.querySelectorAll('.video-player-embed .video-player video')
        customPlayer.forEach(video => {
            const autoplay = video.dataset.autoplay
            if(autoplay == 'scrolltrigger') {
                ScrollTrigger.create({
                    trigger: video,
                    start: 'top top',
                    end: 'bottom bottom',
                    onEnter: function() {
                        video.play()
                    },
                    onEnterBack: function() {
                        video.play()
                    },
                })

                ScrollTrigger.create({
                    trigger: video,
                    start: 'bottom bottom-=20%',
                    end: 'top top',
                    onLeaveBack: function () {
                        video.pause()
                    },
                    onLeave: function () {
                        video.pause()
                    },
                })
            }


            let player = videojs(video, {
                    'preload': 'auto',
                    controlBar: {
                    volumePanel: {
                        inline: false,
                    },
                },
            })
        })
    })

})()