<div>
    @php
        $this->video->play_link = $this->video->playerLink();
        $this->video->tooltip_url = false;
    @endphp

        <!-- modules hook -->
    @action('vod::video-column-player', $this->video)

    <style>
        :root {
            --plyr-color-main : #007f3f;
        }

        /*.plyr:fullscreen video {*/
        /*    max-width: 100vh !important;*/
        /*    max-height: 100vh !important;*/
        /*}*/
    </style>

    @if($video->type === \Modules\Vod\Enums\LinkType::IFRAME->value)
        {!! $video->iframe !!}
    @elseif(in_array($video->type, [\Modules\Vod\Enums\LinkType::HLS->value, \Modules\Vod\Enums\LinkType::LINK->value, \Modules\Vod\Enums\LinkType::UPLOUD->value]))
        <video  data-poster="{{url($video->poster ?? theme('/img/photos/vod/default-video.jpg'))}}"css="video-player " style="height: 100vh" id="player" playsinline crossorigin controls ></video>
    @endif

    @if(in_array($this->video->type, [\Modules\Vod\Enums\LinkType::HLS->value]))
        <script>
            document.addEventListener('livewire:navigated', () => {
                const source = '{{$this->video->play_link}}';
                const video = document.querySelector('video');

                const defaultOptions = {
                    autoplay: true
                };

                if (!Hls.isSupported()) {
                    video.src = source;
                    var player = new Plyr(video, defaultOptions);
                } else {
                    // For more Hls.js options, see https://github.com/dailymotion/hls.js
                    const hls = new Hls();
                    hls.loadSource(source);

                    // From the m3u8 playlist, hls parses the manifest and returns
                    // all available video qualities. This is important, in this approach,
                    // we will have one source on the Plyr player.
                    hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) {

                        // Transform available levels into an array of integers (height values).
                        const availableQualities = hls.levels.map((l) => l.height)
                        availableQualities.unshift(0) //prepend 0 to quality array

                        // Add new qualities to option
                        defaultOptions.quality = {
                            default: 0, //Default - AUTO
                            options: availableQualities,
                            forced: true,
                            onChange: (e) => updateQuality(e),
                        }
                        // Add Auto Label
                        defaultOptions.i18n = @json(trans("vod::lang.player"))

                        @if(true)
                            // set thumbnail vtt file
                            defaultOptions.previewThumbnails = {
                                enabled: true,
                                src: '{{$this->video->tooltip_url}}'
                            }
                        @endif

                        hls.on(Hls.Events.LEVEL_SWITCHED, function (event, data) {
                            var span = document.querySelector(".plyr__menu__container [data-plyr='quality'][value='0'] span")
                            if (hls.autoLevelEnabled) {
                                span.innerHTML = `{{trans("vod::lang.auto")}} (${hls.levels[data.level].height}p)`
                            } else {
                                span.innerHTML = `{{trans("vod::lang.auto_with_description")}}`
                            }
                        })

                        // Initialize new Plyr player with quality options
                        var player = new Plyr(video, defaultOptions);
                    });

                    hls.attachMedia(video);
                    window.hls = hls;
                }

                // Load the last watched time of the video on page load
                // loadLastWatchedTime();

                // Schedule sending the last watched time to the API every minute
                // scheduleAPICall();

                // Save the last watched time of the video every time it is paused
                // video.addEventListener('pause', saveLastWatchedTime);

                // Save the last watched time of the video every time it is paused
                // window.addEventListener('beforeunload', saveLastWatchedTime);

                function updateQuality(newQuality) {
                    if (newQuality === 0) {
                        window.hls.currentLevel = -1; //Enable AUTO quality if option.value = 0
                    } else {
                        window.hls.levels.forEach((level, levelIndex) => {
                            if (level.height === newQuality) {
                                window.hls.currentLevel = levelIndex;
                            }
                        });
                    }
                }

                // Function to save the last watched time of the video
                function saveLastWatchedTime() {
                    if (video) {
                        const currentTime = video.currentTime;
                        localStorage.setItem('{{$this->video->uuid}}-lastWatchedTime', currentTime);
                    }
                }

                // Function to load the last watched time of the video
                function loadLastWatchedTime() {
                    const lastWatchedTime = localStorage.getItem('{{$this->video->uuid}}-lastWatchedTime');
                    if (lastWatchedTime) {
                        video.currentTime = parseFloat(lastWatchedTime);
                    }
                }

                // Function to send the last watched time to the API
                function sendLastWatchedTimeToAPI(lastWatchedTime) {
                    // Replace 'YOUR_API_URL' with the actual URL of your API endpoint
                    const apiUrl = 'YOUR_API_URL';

                    // Make a POST request to the API with the last watched time as data
                    fetch(apiUrl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ lastWatchedTime: lastWatchedTime }),
                    })
                        .then(response => response.json())
                        .then(data => {
                            console.log('Last watched time sent to the API successfully:', data);
                        })
                        .catch(error => {
                            console.error('Error sending last watched time to the API:', error);
                        });
                }

                // Function to schedule sending last watched time to the API every minute
                function scheduleAPICall() {
                    // Set the interval to 1 minute (60 seconds)
                    const interval = 60 * 1000; // 60 seconds in milliseconds

                    // Schedule the API call using setInterval
                    setInterval(() => {
                        // Get the last watched time from the localStorage
                        const lastWatchedTime = localStorage.getItem('lastWatchedTime');

                        // If the last watched time is available, send it to the API
                        if (lastWatchedTime) {
                            sendLastWatchedTimeToAPI(parseFloat(lastWatchedTime));
                        }
                    }, interval);
                }

            });
        </script>
    @elseif(in_array($this->video->type, [ \Modules\Vod\Enums\LinkType::LINK->value, \Modules\Vod\Enums\LinkType::UPLOUD->value]))
        <script>
            document.addEventListener('livewire:navigated', () => {
                const source = '{{$this->video->play_link}}';
                const video = document.querySelector('video');

                const defaultOptions = {
                    autoplay: true
                };

                defaultOptions.i18n = @json(trans("vod::lang.player"))

                    video.src = source;
                var player = new Plyr(video, defaultOptions);

                // Load the last watched time of the video on page load
                // loadLastWatchedTime();

                // Schedule sending the last watched time to the API every minute
                // scheduleAPICall();

                // Save the last watched time of the video every time it is paused
                // video.addEventListener('pause', saveLastWatchedTime);

                // Save the last watched time of the video every time it is paused
                // window.addEventListener('beforeunload', saveLastWatchedTime);

                function updateQuality(newQuality) {
                    if (newQuality === 0) {
                        window.hls.currentLevel = -1; //Enable AUTO quality if option.value = 0
                    } else {
                        window.hls.levels.forEach((level, levelIndex) => {
                            if (level.height === newQuality) {
                                window.hls.currentLevel = levelIndex;
                            }
                        });
                    }
                }

                // Function to save the last watched time of the video
                function saveLastWatchedTime() {
                    if (video) {
                        const currentTime = video.currentTime;
                        localStorage.setItem('{{$this->video->uuid}}-lastWatchedTime', currentTime);
                    }
                }

                // Function to load the last watched time of the video
                function loadLastWatchedTime() {
                    const lastWatchedTime = localStorage.getItem('{{$this->video->uuid}}-lastWatchedTime');
                    if (lastWatchedTime) {
                        video.currentTime = parseFloat(lastWatchedTime);
                    }
                }

                // Function to send the last watched time to the API
                function sendLastWatchedTimeToAPI(lastWatchedTime) {
                    // Replace 'YOUR_API_URL' with the actual URL of your API endpoint
                    const apiUrl = 'YOUR_API_URL';

                    // Make a POST request to the API with the last watched time as data
                    fetch(apiUrl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ lastWatchedTime: lastWatchedTime }),
                    })
                        .then(response => response.json())
                        .then(data => {
                            console.log('Last watched time sent to the API successfully:', data);
                        })
                        .catch(error => {
                            console.error('Error sending last watched time to the API:', error);
                        });
                }

                // Function to schedule sending last watched time to the API every minute
                function scheduleAPICall() {
                    // Set the interval to 1 minute (60 seconds)
                    const interval = 60 * 1000; // 60 seconds in milliseconds

                    // Schedule the API call using setInterval
                    setInterval(() => {
                        // Get the last watched time from the localStorage
                        const lastWatchedTime = localStorage.getItem('lastWatchedTime');

                        // If the last watched time is available, send it to the API
                        if (lastWatchedTime) {
                            sendLastWatchedTimeToAPI(parseFloat(lastWatchedTime));
                        }
                    }, interval);
                }

            });
        </script>
    @endif
</div>
