
const videosSelector = '.video-play';

const initVideo = () => {
    const videoBtns = document.querySelectorAll('.video-play');
    for (const button of videoBtns) {
        const btnToggleClass = 'video__play-btn--hidden';
        const posterToggleClass = 'video__img--hidden';
        const poster = document.querySelector(button.getAttribute('data-poster'));

        const type = button.dataset.type;
        if (type === 'youtube') {
            const iframe = document.querySelector(button.getAttribute('data-video'));

            if (!iframe) return;

            const src = iframe.getAttribute('data-iframe-src');
            const url = new URL(src);

            const onYoutubeClick = (e) => {
                e.preventDefault();
                // const isPlaying = url.searchParams.get('autoplay') === 1;

                url.searchParams.set('autoplay', 1);
                button.classList.add(btnToggleClass);
                iframe.setAttribute('src', url.href);

                if (poster) {
                    poster.classList.add(posterToggleClass);
                }

                button.removeEventListener('click', onYoutubeClick);
            }
            button.addEventListener('click', onYoutubeClick);
        } else if (type === 'video' || type === 'asset') {
            const video = document.querySelector(button.getAttribute('data-video'));

            if (!video) return;

            button.addEventListener('click', (e) => {
                e.preventDefault();
                if (video.paused) {
                    video.play();
                    button.classList.add(btnToggleClass);
                    if (poster) {
                        poster.classList.add(posterToggleClass);
                    }
                } else {
                    video.pause();
                    button.classList.remove(btnToggleClass);
                    if (poster) {
                        poster.classList.remove(posterToggleClass);
                    }
                }

                video.addEventListener('pause', (event) => {
                    button.classList.remove(btnToggleClass);

                    if (poster) {
                        poster.classList.remove(posterToggleClass);
                    }
                });
            });
        }
    };
}

export { videosSelector, initVideo };
