

<?php
    // FIX #3: Regex diperbaiki agar tidak menangkap parameter ?si= dsb.
    preg_match('/(youtu\.be\/|[?&]v=)([^&?#\s]+)/', $lesson->content_url ?? '', $m);
    $videoId = $m[2] ?? null;

    $lessonLocked = $lesson->available_at && now()->lt($lesson->available_at);
?>


<?php if($lessonLocked): ?>

    <div class="flex flex-col items-center justify-center
                min-h-[50vh] bg-white text-center p-6">

        <i class="fas fa-lock text-6xl text-gray-400 mb-4"></i>

        <h3 class="text-lg font-semibold text-gray-800 mb-2">
            Materi belum dapat diakses
        </h3>

        <p class="text-gray-500 text-sm">
            Akses materi akan dibuka pada:
        </p>

        <p class="font-semibold text-gray-700 mt-1">
            <?php echo e($lesson->available_at->translatedFormat('d F Y H:i')); ?>

        </p>

        <a href="<?php echo e(route('siswa.dashboard')); ?>"
           class="mt-6 px-6 py-3 bg-gray-900 text-white rounded-lg hover:bg-gray-700">
            Kembali ke Dashboard
        </a>

    </div>


<?php else: ?>

    
    <?php if($lesson->content_type === 'text'): ?>
        <div class="text-gray-700 leading-relaxed text-base bg-white p-6">
            <?php echo nl2br(e($lesson->content)); ?>

        </div>

    
    <?php elseif($lesson->content_type === 'pdf'): ?>
    
    <div id="pdf-container-<?php echo e($lesson->id); ?>"
         style="width:100%; height:75vh; background:white; overflow-y:auto;">
    
        <iframe
            src="<?php echo e(str_replace('/view', '/preview', $lesson->content_url)); ?>"
            style="width:100%; height:1200px; border:0;"
            loading="lazy">
        </iframe>
    
    </div>
    
    <script>
    (function(){
    
        const lessonId = <?php echo e($lesson->id); ?>;
        const container = document.getElementById('pdf-container-<?php echo e($lesson->id); ?>');
    
        if(!container) return;
    
        let started = false;
        let timer   = null;
    
        container.addEventListener('scroll', function(){
            
            window.dispatchEvent(new Event('lesson-interact'));
    
            if(!started){
                started = true;
                startDuration();
            }
    
        });
    
function startDuration(){

<?php if(empty($lesson->duration)): ?>

    if(timer) return;

    timer = setInterval(function(){

        if(document.hidden) return;

        fetch('/siswa/lesson/'+lessonId+'/duration',{
            method:'POST',
            headers:{
                'X-CSRF-TOKEN':'<?php echo e(csrf_token()); ?>',
                'Content-Type':'application/json'
            },
            body:JSON.stringify({seconds:5})
        }).catch(()=>{});

    },5000);

<?php endif; ?>

}
    
        // 🔥 stop timer kalau user pindah halaman
        window.addEventListener('beforeunload', function(){
            if(timer){
                clearInterval(timer);
            }
        });
    
    })();
    </script>

    
    <?php elseif($lesson->content_type === 'video'): ?>

        <?php if($videoId): ?>

            <div class="relative w-full max-w-5xl mx-auto">
                <div id="yt-player" class="w-full aspect-video bg-black"></div>
                
                <div class="absolute bottom-0 left-0 w-full h-[70px] z-20 pointer-events-none"></div>
            </div>

            <div id="forward-warning"
                 class="hidden fixed bottom-6 left-1/2 -translate-x-1/2
                        bg-black text-white px-4 py-2 rounded-lg text-sm z-50 shadow-lg">
                тЪая╕П Anda tidak bisa mempercepat video
            </div>

            <script src="https://www.youtube.com/iframe_api"></script>

            <script>
            (function () {
                // Namespace agar tidak konflik jika halaman di-include ulang
                const lessonId       = <?php echo e($lesson->id); ?>;
                const videoId        = '<?php echo e($videoId); ?>';
                let   player         = null;
                let   maxAllowedTime = 0;
                let   finished       = false;
                let   warningTimer   = null;

                // FIX: Gunakan fungsi global yang dicek lebih dulu
                // agar tidak override jika API sudah terpasang
                window.onYouTubeIframeAPIReady = function () {
                    player = new YT.Player('yt-player', {
                        videoId: videoId,
                        playerVars: {
                            controls     : 1,
                            disablekb    : 0,
                            rel          : 0,
                            modestbranding: 0,
                            fs           : 0,
                            playsinline  : 1
                        },
                       events: {
    onReady            : onPlayerReady,
    onPlaybackRateChange: lockPlaybackRate,
    onStateChange      : onPlayerStateChange
}
                    });
                };
                
                function onPlayerStateChange(e){

    // 🔥 hanya saat benar-benar PLAY
    if(e.data === YT.PlayerState.PLAYING){
        window.dispatchEvent(new Event('yt-playing'));
    }

}

                function onPlayerReady() {
                    // Cek posisi setiap 500ms, cegah skip
                    setInterval(function () {
                        if (!player || typeof player.getCurrentTime !== 'function') return;

                        const current  = player.getCurrentTime();
                        const duration = player.getDuration();

                        if (current > maxAllowedTime + 1.5) {
                            player.seekTo(maxAllowedTime, true);
                            showWarning();
                        } else {
                            maxAllowedTime = Math.max(maxAllowedTime, current);
                        }

                        <?php if(empty($lesson->duration)): ?>
                        if (!finished && duration > 0 && maxAllowedTime >= duration - 1) {
                            finished = true;
                            unlockFinish();
                        }
                        <?php endif; ?>
                    }, 500);

                    // Kirim durasi tonton ke server setiap 5 detik
                    <?php if(empty($lesson->duration)): ?>
                    setInterval(function () {
                        if (!player || typeof player.getPlayerState !== 'function') return;
                        if (player.getPlayerState() !== YT.PlayerState.PLAYING)    return;
                    
                        fetch('/siswa/lesson/' + lessonId + '/duration', {
                            method  : 'POST',
                            headers : {
                                'X-CSRF-TOKEN' : '<?php echo e(csrf_token()); ?>',
                                'Content-Type' : 'application/json'
                            },
                            body: JSON.stringify({ seconds: 5 })
                        }).catch(function () {});
                    }, 5000);
                    <?php endif; ?>
                    
                    // player.addEventListener('onStateChange', function(e){
                    //     if(e.data === YT.PlayerState.PLAYING){
                    //         window.dispatchEvent(new Event('yt-playing'));
                    //     }
                    // });
                }

                function lockPlaybackRate() {
                    if (player && player.getPlaybackRate() !== 1) {
                        player.setPlaybackRate(1);
                    }
                }

                function unlockFinish() {
                    const btn = document.getElementById('btn-selesai');
                    if (!btn) return;
                    btn.disabled = false;
                    btn.classList.remove('bg-gray-300', 'text-gray-500', 'cursor-not-allowed');
                    btn.classList.add('bg-gray-900', 'text-white', 'hover:bg-gray-700');
                }

                function showWarning() {
                    const toast = document.getElementById('forward-warning');
                    if (!toast) return;
                    toast.classList.remove('hidden');
                    clearTimeout(warningTimer);
                    warningTimer = setTimeout(function () {
                        toast.classList.add('hidden');
                    }, 1500);
                }
            })();
            </script>

        <?php else: ?>
            
            <div class="flex items-center justify-center h-[40vh] bg-white text-center p-6">
                <p class="text-red-500">тЪая╕П URL video tidak valid atau tidak dikenali.</p>
            </div>
        <?php endif; ?>

    
    <?php elseif($lesson->content_type === 'link'): ?>
        <div class="flex items-center justify-center min-h-[40vh] bg-white">
            <a href="<?php echo e($lesson->content_url); ?>"
               target="_blank"
               rel="noopener noreferrer"
               class="inline-flex items-center gap-2 text-blue-600 hover:underline text-base font-medium">
                ЁЯФЧ Buka Materi
            </a>
        </div>
    <?php endif; ?>

<?php endif; ?><?php /**PATH /home/gacf7692/public_html/siswa.smkn8medan.sch.id/resources/views/siswa/modul/_content.blade.php ENDPATH**/ ?>