<div>
    <!-- main menu widget-->
    <livewire:widgets.custom :widget="widget('main_menu')" :view="'theme::widgets.main_menu'" />
    <!--/ main menu widget -->

    @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 {
            height: 100% !important;
        }
    </style>

    <div class="container mx-auto p-4">
        <div class="flex flex-wrap flex-row">
            <!-- main content -->
            <div class="md:p-2 mb-12 lg:basis-2/3 md:bas">
                @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 css="video-player aspect-video w-full" style="width: 100%" id="player" playsinline crossorigin controls ></video>
                @endif
                <div class="bg-white shadow-sm overflow-hidden">

                    <div class="p-4">
                        <h1 class="mt-2 font-bold text-xlg text-gray-600">{{$video->title}}</h1>
                        <span class="leading-10 text-gray-500 block mt-3 blog-container">
                        {!! $video->description !!}
                    </span>
                    </div>
                </div>
            </div>

            <!-- left sidebar -->
            <div class="p-2 mb-12 lg:basis-1/3 w-full">
                @if($cats)
                    <!-- category -->
                    <div class="flex flex-row">
                        <svg id="Layer_2" width="70" class="fill-green-700 rotate-90 w-[20px] mb-3 z-0" data-name="Layer 2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 791.02 945.33">
                            <g id="Layer_1-2" data-name="Layer 1">
                                <path d="m.14,0v585.17c-2.3,55.02,24.38,105.43,68.81,129.18,41.69,22.28,83.49,12.79,95.06,9.75-.64,10.43-1.69,47.87,24.37,82.87,21.13,28.37,48.44,39.52,59.3,43.31,18.42,3.43,44.84,10.61,73.12,26.81,38.74,22.19,62.31,50.6,74.63,68.02v.22s.06-.08.08-.11c.02.03.06.08.08.11v-.22c12.31-17.42,35.89-45.84,74.63-68.02,28.28-16.2,54.7-23.38,73.12-26.81,10.87-3.78,38.18-14.93,59.3-43.31,26.06-35,25.02-72.44,24.37-82.87,11.57,3.04,53.37,12.53,95.06-9.75,44.43-23.75,71.11-74.16,68.81-129.18V0"/>
                            </g>
                        </svg>
                        <span class="pr-3 font-bold text-gray-600">دسته ها</span>
                    </div>
                    <div class="space-y-3">
                        @foreach($cats as $cat)
                        <div class="rounded-lg p-3 border-2 ">
                            <a class="flex flex-row">
                                <div class="flex flex-col mr-3 w-full">
                                    <h5>{{$cat->title}}</h5>
                                </div>
                                <i class="las la-angle-left text-xl"></i>
                            </a>
                        </div>
                        @endforeach
                    </div>
                @endif

                @if($videos)
                    <!-- last articles -->
                    <div class="flex flex-row mt-6">
                        <svg id="Layer_2" width="70" class="fill-green-700 rotate-90 w-[20px] mb-3 z-0" data-name="Layer 2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 791.02 945.33">
                            <g id="Layer_1-2" data-name="Layer 1">
                                <path d="m.14,0v585.17c-2.3,55.02,24.38,105.43,68.81,129.18,41.69,22.28,83.49,12.79,95.06,9.75-.64,10.43-1.69,47.87,24.37,82.87,21.13,28.37,48.44,39.52,59.3,43.31,18.42,3.43,44.84,10.61,73.12,26.81,38.74,22.19,62.31,50.6,74.63,68.02v.22s.06-.08.08-.11c.02.03.06.08.08.11v-.22c12.31-17.42,35.89-45.84,74.63-68.02,28.28-16.2,54.7-23.38,73.12-26.81,10.87-3.78,38.18-14.93,59.3-43.31,26.06-35,25.02-72.44,24.37-82.87,11.57,3.04,53.37,12.53,95.06-9.75,44.43-23.75,71.11-74.16,68.81-129.18V0"/>
                            </g>
                        </svg>
                        <span class="pr-3 font-bold text-gray-600">آخرین ویدیوها</span>
                    </div>
                    <div class=" space-y-3">
                        @foreach($videos as $video)
                        <div class="shadow-sm bg-white p-2">
                            <a href="{{$video->path()}}" class="flex flex-row">
                                <img src="{{url($video->poster ?? theme('/img/photos/vod/default-video.jpg'))}}" style="width: 10rem" class="aspect-video h-auto " alt="">
                                <div class="flex flex-col mr-3 w-full">
                                    <h5>{{$video->title}}</h5>
                                    <div class="mt-3 flex justify-between flex-wrap text-gray-400">
                                        <div class="flex items-center">
                                            <i class="las la-calendar-alt text-xl"></i>
                                            <span class="text-sm">{{$video->getDate()}}</span>
                                        </div>
                                        <div class="flex items-center">
                                            @if($video->getDuration() !== false)
                                            <i class="las la-clock ml-1 text-xl "></i>
                                            <span class="text-sm"><i class="las la-clock-o"></i></span>
                                            <span class="text-sm">{{$video->getDuration()}}</span>
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </div>
                        @endforeach
                    </div>
                @endif



                @if($tags)
                <!-- last tags -->
                <div class="flex flex-row mt-6">
                    <span class="pr-3 font-bold text-gray-600">تگ ها</span>
                </div>
                <div class="flex-row flex flex-wrap space-x-3 rtl:space-x-reverse">
                    @foreach($tags as $tag)
                    <a href="{{url('/videos?tags['.$tag->group->slug.']['.$tag->id.']=true')}}" class="rounded-full shadow-sm bg-gray-50 p-3 w-max mb-3">
                        <div class="flex flex-row cursor-pointer">
                            <span>{{$tag->title}}</span>
                        </div>
                    </a>
                    @endforeach
                </div>
                @endif
            </div>
        </div>

    </div>

    @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 = {};

                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(false)
                            // 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 = {};

                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>
