document.addEventListener('DOMContentLoaded', function() {
    const modalBg = document.getElementById('modalBg');
    const closeButtons = document.querySelectorAll('.closeModal');

    function openModal(modalId, videoIdOrSrc, videoType, title) {
        const modal = document.getElementById(modalId);
        const iframe = modal.querySelector('iframe');
        const video = modal.querySelector('video');
        // const videoTitle = modal.querySelector('h2');

        // videoTitle.textContent = title;

        if (videoType === 'youtube') {
            const videoUrl = `https://www.youtube.com/embed/${videoIdOrSrc}?autoplay=1`;
            iframe.src = videoUrl;
            iframe.style.display = 'block';
            if (video) video.style.display = 'none';
        } else if (videoType === 'mp4') {
            video.querySelector('source').src = videoIdOrSrc;
            video.load();
            video.play();
            video.style.display = 'block';
            if (iframe) iframe.style.display = 'none';
        }

        modal.classList.add('active');
        modalBg.style.display = 'block';
    }

    function closeModal() {
        document.querySelectorAll('.modal_video').forEach(modal => {
            const iframe = modal.querySelector('iframe');
            const video = modal.querySelector('video');

            if (iframe) {
                iframe.src = '';
                iframe.style.display = 'none';
            }

            if (video) {
                video.pause();
                video.currentTime = 0;
                video.querySelector('source').src = '';
                video.load();
                video.style.display = 'none';
            }

            modal.classList.remove('active');
        });
        modalBg.style.display = 'none';
    }

    document.querySelectorAll('.video-thumbnail').forEach(thumbnail => {
        thumbnail.addEventListener('click', function(e) {
            e.preventDefault();
            const videoId = this.getAttribute('data-video-id');
            const videoSrc = this.getAttribute('data-video-src');
            const modalId = this.getAttribute('data-modal');
            const title = this.getAttribute('data-video-title');

            if (videoId) {
                openModal(modalId, videoId, 'youtube', title);
            } else if (videoSrc) {
                openModal(modalId, videoSrc, 'mp4', title);
            }
        });
    });

    closeButtons.forEach(button => {
        button.addEventListener('click', closeModal);
    });

    modalBg.addEventListener('click', closeModal);
});