<?php

$titre = get_field('titre');
$soustitre = get_field('sous-titre');
$items = get_field('videos_grid');
$grid_columns = count($items);
?>
<style>
    @media (min-width: 768px) {
        .video-grid {
            display: grid;
            grid-template-columns: repeat(<?php echo $grid_columns ?>, 1fr);
        }
    }
</style>

<section class="block-video-grid ">
    <div class="container-fluid relative">
        <?php if (!empty($titre)) : ?>
            <div class="scroll-appear flex flex-col gap-4 justify-center text-center absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-20 w-full max-w-5xl mx-auto text-white pointer-events-none overflow-hidden">

                <div class="tracking-widest text-center text-[1.75rem] lg:text-[2rem] xl:text-[2.8125rem] font-heading  uppercase scroll-appear leading-tight"><?php echo $titre; ?>
                </div>
                <small class="block scroll-appear text-xl lg:text-[1.75rem] xl:text-[2.1875rem] font-cursive italic leading-tight normal-case">
                    <?php echo $soustitre; ?>
                </small>
            </div>
        <?php
        endif; ?>
        <!-- Desktop version grid -->
        <div class="hidden md:block desktop-version">
            <?php if (!empty($items)) : ?>
                <div class="video-grid z-0" data-columns="<?php echo esc_attr($grid_columns); ?>">
                    <?php foreach ($items as $item) :

                        $video_url = $item['video'] != false    ? $item['video']['url'] : '';
                        $video_poster = $item['poster'];
                        $video_titre = $item['titre'] != ''    ? $item['titre'] : '';
                        $video_lien = $item['lien'] != ''    ? $item['lien'] : '';

                    ?>
                        <?php if ($video_lien != '') : ?>
                            <a href="<?php echo esc_url($video_lien['url']); ?>"
                                target="<?php echo esc_attr($video_lien['target']); ?>" class="video-item relative">
                            <?php else : ?>
                                <div class="video-item relative">
                                <?php endif; ?>
                                <div class="video-wrapper relative  aspect-video md:aspect-[12/16] cursor-pointer overflow-hidden group"
                                    data-video-url="<?php echo esc_url($video_url); ?>">
                                    <?php if ($video_poster != false) : ?>
                                        <?php echo wp_get_attachment_image($video_poster['ID'], 'large', false, array('class' => 'video-poster ')); ?>
                                    <?php endif; ?>
                                    <video class="video-element"
                                        src="<?php echo esc_url($video_url); ?>"
                                        muted
                                        loop
                                        playsinline>
                                    </video>
                                    <?php if ($video_titre) : ?>
                                        <div class="video-footer absolute bottom-8 left-0 z-10 text-white text-center w-full flex flex-col gap-1">
                                            <div class="video-titre"><?php echo ($video_titre); ?></div>
                                            <div>
                                                <?php if (!empty($video_lien) && is_array($video_lien)) : ?>
                                                    <button class="btn btn-underline dark">
                                                        <?php echo ($video_lien['title']); ?>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <?php if ($video_lien != '') : ?>
                            </a>
                        <?php else : ?>
                </div>
            <?php endif; ?>
        <?php endforeach; ?>
        </div>
    <?php endif; ?>
    </div>
    <!-- Mobile version slider -->
    <div class="md:hidden mobile-version">
        <?php if (!empty($items)): ?>
            <div class="slick-video-grid z-0">
                <?php foreach ($items as $item):
                    $video_url = $item['video'] != false ? $item['video']['url'] : '';
                    $video_poster = $item['poster'];
                    $video_titre = $item['titre'] != '' ? $item['titre'] : '';
                    $video_lien = $item['lien'] != '' ? $item['lien'] : '';
                ?>
                    <?php if ($video_lien != ''): ?>
                        <a href="<?php echo $video_lien['url']; ?>" target="<?php echo $video_lien['target']; ?>"
                            class="video-item relative">
                        <?php else: ?>
                            <div class="video-item relative">
                            <?php endif; ?>
                            <div class="video-wrapper relative cursor-pointer overflow-hidden group"
                                data-video-url="<?php echo esc_url($video_url); ?>">
                                <?php if ($video_poster != false): ?>
                                    <?php echo wp_get_attachment_image($video_poster['ID'], 'large', false, array('class' => 'video-poster !hidden')); ?>
                                <?php endif; ?>

                                <video class="video-element" src="<?php echo esc_url($video_url); ?>" poster="<?php echo esc_url($video_poster['sizes']['large']); ?>" muted playsinline>
                                </video>
                                <div class="video-overlay"></div>
                                <?php if ($video_titre): ?>
                                    <div
                                        class="video-footer absolute bottom-8 z-10 text-white text-center w-full flex flex-col gap-1">
                                        <h3 class="video-titre "><?php echo ($video_titre); ?></h3>
                                        <div>
                                            <?php if (!empty($video_lien) && is_array($video_lien)) : ?>
                                                <button class="btn btn-underline dark"><?php echo ($video_lien['title']); ?></button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <?php if ($video_lien != ''): ?>
                        </a>
                    <?php else: ?>
            </div>
        <?php endif; ?>
    <?php endforeach; ?>
    </div>
<?php endif; ?>
</div>
</div>
</section>

<script>
    let domContentLoaded = false;
    const playVideos = () => {
        const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
        const isMobile = window.innerWidth < 768;

        const desktopVersion = document.querySelector('.desktop-version');
        const mobileVersion = document.querySelector('.mobile-version');
        const videoWrappers = isMobile ? mobileVersion.querySelectorAll('.video-wrapper') : desktopVersion.querySelectorAll('.video-wrapper');

        let cpt = 0;

        if (videoWrappers.length > 0) {
            videoWrappers.forEach(wrapper => {
                const video = wrapper.querySelector('.video-element');
                const videoPoster = wrapper.querySelector('.video-poster');
                // reset
                if (isTouchDevice) {
                    video.removeAttribute('loop');
                } else {
                    video.setAttribute('loop', true);
                }

                video.removeEventListener('mouseenter', () => {});
                video.removeEventListener('mouseleave', () => {});
                video.removeEventListener('ended', () => {});

                // add events
                if (!isTouchDevice) {
                    wrapper.addEventListener('mouseenter', () => {
                        video.play();
                    });

                    wrapper.addEventListener('mouseleave', () => {
                        video.pause();
                        video.currentTime = 0;
                    });
                } else {
                    video.addEventListener('ended', () => {
                        videoWrappers[cpt].querySelector('.video-poster').classList.remove('hide');

                        cpt++;
                        if (cpt >= videoWrappers.length) {
                            cpt = 0;
                        }

                        videoWrappers[cpt].querySelector('.video-element').play();
                        videoWrappers[cpt].querySelector('.video-poster').classList.add('hide');
                    });



                    videoWrappers[cpt].querySelector('.video-element').play();
                    videoWrappers[cpt].querySelector('.video-poster').classList.add('hide');

                }
            });
        }
    }

    const resetVideos = () => {
        const videoWrappers = document.querySelectorAll('.video-wrapper');
        videoWrappers.forEach(wrapper => {
            const video = wrapper.querySelector('.video-element');
            const videoPoster = wrapper.querySelector('.video-poster');
            video.pause();
            video.currentTime = 0;
            videoPoster.classList.remove('hide');
            video.removeEventListener('mouseenter', () => {});
            video.removeEventListener('mouseleave', () => {});
            video.removeEventListener('ended', () => {});
        });
    }

    document.addEventListener('DOMContentLoaded', function() {
        domContentLoaded = true;
        playVideos();
    });

    window.addEventListener('resize', () => {
        if (domContentLoaded) {
            resetVideos();
            playVideos();
        }
    })
</script>