<?php

declare(strict_types=1);



class Player
{
    private static bool $enqueued = false;

    

    public static function render(array $video): string
    {
        if (!empty($video['embed_code'])) {
            return self::renderEmbed($video);
        }

        if (!empty($video['video_folder'])) {
            return self::renderFluid($video);
        }

        return '';
    }

    

    private static function renderEmbed(array $video): string
    {
        $code = Sanitizer::embedCode($video['embed_code']);
        if ($code === '') {
            return '';
        }
        return '<div class="video-player">' . $code . '</div>';
    }

    

    private static function renderFluid(array $video): string
    {
        self::enqueueAssets();

        $folder = $video['video_folder'];
        $sid = isset($video['storage_id']) ? (int)$video['storage_id'] : null;
        $srcH = isset($video['source_height']) ? (int)$video['source_height'] : null;

        $posterUrl = VideoAsset::thumbUrl($video);
        $poster = $posterUrl !== '' ? ' poster="' . htmlspecialchars($posterUrl) . '"' : '';

        $timelineVtt = VideoAsset::timelineVttUrl($video);
        $dataTimeline = $timelineVtt !== '' ? ' data-timeline-vtt="' . htmlspecialchars($timelineVtt) . '"' : '';

        $videoSources = VideoAsset::getVideoSources($folder, $sid, $srcH);
        if (empty($videoSources)) {
            return '<div class="video-player" style="aspect-ratio:16/9;background:#000;display:flex;align-items:center;justify-content:center">'
                . '<span style="color:#666;font-size:14px">Video is being processed...</span>'
                . '</div>';
        }

         
        $defaultQuality = Setting::get('player_default_quality', 'auto');
        if ($defaultQuality !== 'auto') {
            $targetH = (int)$defaultQuality;
             
            $bestIdx = 0;
            $bestDiff = PHP_INT_MAX;
            foreach ($videoSources as $i => $src) {
                $diff = $src['height'] - $targetH;
                if ($diff === 0) { $bestIdx = $i; break; }
                if ($diff < 0 && abs($diff) < $bestDiff) { $bestIdx = $i; $bestDiff = abs($diff); }
                if ($bestDiff === PHP_INT_MAX && $diff > 0 && $diff < $bestDiff) { $bestIdx = $i; }
            }
            if ($bestIdx > 0) {
                $preferred = $videoSources[$bestIdx];
                array_splice($videoSources, $bestIdx, 1);
                array_unshift($videoSources, $preferred);
            }
        }

        $sourcesHtml = '';
        foreach ($videoSources as $src) {
            $ext = strtolower(pathinfo($src['file'], PATHINFO_EXTENSION));
            $mime = match ($ext) { 'webm' => 'video/webm', 'ogg' => 'video/ogg', default => 'video/mp4' };
            $hd = ($src['height'] >= 720) ? ' data-fluid-hd' : '';
            $sourcesHtml .= '<source src="' . htmlspecialchars($src['url']) . '" title="' . htmlspecialchars($src['label']) . '" type="' . $mime . '"' . $hd . '>';
        }

         
        $overlay = '';
        $pauseAd = '';
        if (class_exists('Ads')) {
            ob_start();
            Ads::zone('player_overlay');
            $overlay = (string) ob_get_clean();
            ob_start();
            Ads::zone('player_pause');
            $pauseAd = (string) ob_get_clean();
        }

        return '<div class="video-player video-player--fluid">'
            . '<video id="mainVideo"' . $poster . $dataTimeline . '>'
            . $sourcesHtml
            . 'Your browser does not support video playback.'
            . '</video>'
            . $overlay
            . $pauseAd
            . '</div>';
    }

    

    private static function enqueueAssets(): void
    {
        if (self::$enqueued) {
            return;
        }
        self::$enqueued = true;

         
        ThemeRenderer::enqueueJS('/assets/vendor/fluidplayer/fluidplayer.min.js', 5);

         
        HookSystem::addAction('head.meta', function () {
            echo '<style>'
                . '.video-player--fluid{position:relative;background:#000;overflow:hidden;aspect-ratio:16/9}'
                . '.video-player--fluid .fluid_video_wrapper{width:100%!important;height:100%!important;position:absolute!important;top:0;left:0}'
                . '</style>';
        });

         
        $playbackRate = Setting::get('player_playback_rate', '1') === '1';
        $allowDownload = Setting::get('player_allow_download', '0') === '1';
        $loop = Setting::get('player_loop', '0') === '1';
        $dblClickFs = Setting::get('player_doubleclick_fullscreen', '1') === '1';
        $defaultQuality = Setting::get('player_default_quality', 'auto');
         
        $vastJson = class_exists('Ads') ? Ads::playerVastJson() : '';
        $pauseVastId = class_exists('Ads') ? Ads::pauseVastSpotId() : 0;

        HookSystem::addAction('footer.scripts', function () use ($playbackRate, $allowDownload, $loop, $dblClickFs, $defaultQuality, $vastJson, $pauseVastId) {
            $pbRate = $playbackRate ? 'true' : 'false';
            $dl = $allowDownload ? 'true' : 'false';
            $lp = $loop ? 'true' : 'false';
            $dbl = $dblClickFs ? 'true' : 'false';

            echo '<script>'
                . '(function(){'
                . 'var el=document.getElementById("mainVideo");'
                . 'if(!el||typeof window.fluidPlayer!=="function")return;'
                . 'var c=getComputedStyle(document.documentElement).getPropertyValue("--primary").trim()||"#2563eb";'
                . 'var opts={layoutControls:{'
                . 'fillToContainer:true,'
                . 'primaryColor:c,'
                . 'posterImage:el.getAttribute("poster")||"",'
                . 'playButtonShowing:true,'
                . 'playPauseAnimation:true,'
                . 'autoPlay:false,'
                . 'mute:false,'
                . 'allowTheatre:false,'
                . 'allowDownload:' . $dl . ','
                . 'loop:' . $lp . ','
                . 'doubleclickFullscreen:' . $dbl . ','
                . 'playbackRateEnabled:' . $pbRate . ','
                . 'miniPlayer:{enabled:false},'
                . 'controlBar:{autoHide:true,autoHideTimeout:3,animated:true,playbackRates:["x2","x1.5","x1","x0.5"]}'
                . '}};'
                . ($vastJson !== '' ? 'opts.vastOptions={adList:' . $vastJson . ',adClickable:true,showProgressbarMarkers:true,vastTimeout:8000};' : '')
                . 'var tv=el.getAttribute("data-timeline-vtt");'
                . 'if(tv)opts.layoutControls.timelinePreview={file:tv,type:"VTT"};'
                . 'window.fluidPlayer("mainVideo",opts);'
                . ($pauseVastId > 0 ? 'var pvSent=false;el.addEventListener("pause",function(){if(pvSent)return;setTimeout(function(){if(pvSent||!el.paused)return;var w=el.closest(".fluid_video_wrapper")||el.parentNode;var b=w?w.querySelector(".fluid_nonLinear_ad"):null;if(b&&getComputedStyle(b).display!=="none"){pvSent=true;try{navigator.sendBeacon("/iv/' . $pauseVastId . '");}catch(e){}}},900);});' : '')
                . 'var pa=document.querySelector(".flux--pause");'
                . 'if(pa){var paC=function(){try{return (JSON.parse(sessionStorage.getItem("flux_x")||"[]")||[]).indexOf("player_pause")>=0;}catch(e){return false;}};'
                . 'el.addEventListener("pause",function(){if(!paC())pa.style.display="flex";});'
                . 'el.addEventListener("play",function(){pa.style.display="none";});'
                . 'el.addEventListener("ended",function(){if(!paC())pa.style.display="flex";});}'
                . '})();'
                . '</script>';
        });
    }
}
