@extends('website.layouts.base')
@section('title', __('video_player'))
@section('base.content')

    @php
        if (isset($demoVideo) && isDemoMode()) {
            // Now assign them if needed
            $server = new \stdClass();
            $server->file_source = 'json';
            $server->file_url = $demoVideo['url'];
        } elseif (isDemoMode()) {
            $server = new \stdClass();
            $server->file_source = 'json';
            $server->file_url = $video->url;
        }

        if (isset($server)) {
            if ($server->file_source == 'local') {
                $path = preg_replace('#^public/#i', '', ltrim($server->file_url, '/'));
                $server->file_url = preg_replace('#/public(?=/|$)#', '', url($path));

                // Build folder name: slugified label + ID
                $folderName = $server->id;

                $qualities = ['sd', 'hd', 'fullhd'];
                $fileUrls = [];

                foreach ($qualities as $quality) {
                    $fileRelativePath = "uploads/videos/{$folderName}/{$quality}/video.mp4"; // Assuming mp4
                    $fileUrls[$quality] = preg_replace('#/public(?=/|$)#', '', url($fileRelativePath));
                }

                // Now assign them if needed
                $server->sd_url = $fileUrls['sd'];
                $server->hd_url = $fileUrls['hd'];
                $server->full_hd_url = $fileUrls['fullhd'];

                // $folder_path = public_path('')
                // echo $server->id;
            } elseif ($server->file_source == 'gdrive') {
                $googleApiKey = get_config('google_api_key'); // or set your key directly
                preg_match('/\/d\/(.+?)\//', $server->file_url, $matches);

                if (!empty($matches[1])) {
                    $fileId = $matches[1];
                    $server->file_url = "https://www.googleapis.com/drive/v3/files/{$fileId}?alt=media&key={$googleApiKey}&v=.mp4";
                } else {
                    // fallback if URL pattern is different
                    $server->file_url = null;
                }
            } elseif ($server->file_source == 'youtube') {
                // Normalize youtu.be links to youtube.com/watch?v= so the player recognizes them
                if (preg_match('/(?:youtube\.com\/.*[?&]v=|youtu\.be\/)([^&\s?#]+)/', $server->file_url, $ytMatches)) {
                    $server->file_url = 'https://www.youtube.com/watch?v=' . $ytMatches[1];
                }
            }
        }

        if ($video_type == 'episode' && !isDemoMode()) {
            $video->video_url = $video->video_url ?? $video->file_url ?? '';
            $episodeSourceType = $video->source_type ?? $video->file_source ?? '';
            if ($episodeSourceType == 'youtube') {
                if (preg_match('/(?:youtube\.com\/.*[?&]v=|youtu\.be\/)([^&\s?#]+)/', $video->video_url, $ytMatches)) {
                    $video->video_url = 'https://www.youtube.com/watch?v=' . $ytMatches[1];
                }
            } elseif ($episodeSourceType == 'gdrive') {
                $googleApiKey = get_config('google_api_key');
                if ($googleApiKey && preg_match('/\/d\/([^\/?#]+)/', $video->video_url, $matches)) {
                    $fileId = $matches[1];
                    $video->video_url = "https://www.googleapis.com/drive/v3/files/{$fileId}?alt=media&key={$googleApiKey}&v=.mp4";
                }
            } elseif ($episodeSourceType == 'video' || in_array($episodeSourceType, ['mp4', 'mkv', 'webm', 'm3u8', 'embed', 's3', 'wasabi', 'do'], true)) {
                if (!empty($video->video_url) && !preg_match('#^https?://#i', $video->video_url)) {
                    $path = preg_replace('#^public/#i', '', ltrim($video->video_url, '/'));
                    $video->video_url = preg_replace('#/public(?=/|$)#', '', url($path));
                }
            }
        } elseif (isDemoMode()) {
            // Demo mode: use demo url and placeholders
            $video->video_url = $video->url ?? '';
            $video->poster = '{"original_image":"https:\/\/placehold.co\/500x750"}';
            $video->description = 'Demo video description';
            $video->title = 'Demo Video Title';
        }
        // For movie, video_url is set from repository (first video file's file_url) — do not overwrite

        $subtitleSourceAttr = '';
        if (isset($video->subtitles) && $video->subtitles->isNotEmpty()) {
            $parts = [];
            foreach ($video->subtitles as $s) {
                $url = preg_match('#^https?://#i', $s->file_path) ? $s->file_path : url($s->file_path);
                $parts[] = "{source:'" . addslashes($url) . "', label:'" . addslashes($s->label) . "'}";
            }
            $subtitleSourceAttr = '[' . implode(',', $parts) . ']';
        }
    @endphp

    <link rel="stylesheet" type="text/css" href="{{ static_asset('website/player/content/global.css') }}" />

    <div id="myDiv" class="m-auto"></div>

    <div id="player"></div>

    <!--  Playlists -->
    <ul id="playlists" class="d-none">
        <li data-source="playlist1" data-playlist-name="Related Videos"
            data-thumbnail-path="{{ getFileLink('poster', $video->poster, $video_type . 's', '500x400') }}">
            <p class="fwduvp-categories-title"><span class="fwduvp-header">{{ __('title') }}: </span><span
                    class="fwduvp-title"> {{ $video->title }} </span></p>
            <p class="fwduvp-categories-description"><span class="fwduvp-header">{{ __('description') }}: </span>
                {{ $video->description }} </p>
        </li>
    </ul>

    <!--  HTML playlist -->
    <ul id="playlist1" class="d-none">
        <li data-thumb-source="{{ getFileLink('thumbnail', $video->poster, $video_type . 's', '500x400') }}"
            data-video-source="[
            @if (isset($server) && $server->file_source == 'local') {source:'{{ $server->file_url }}', label:'Original'},
                {source:'{{ $server->sd_url }}', label:'SD'},
                {source:'{{ $server->hd_url }}', label:'HD'},
                {source:'{{ $server->full_hd_url }}', label:'FullHD'}
            @elseif(isset($server) && $server->file_source == 'gdrive')
                {source:'{{ $server->file_url }}', label:'Original'}
            @elseif(isset($server) && $server->file_source == 'youtube')
                {source:'{{ $server->file_url }}', label:'Original'}
            @elseif(isset($server) && $server->file_source == 'json')
                {source:'{{ $server->file_url }}', label:'Original'}
            @elseif($video_type == 'movie' && isset($video_files) && $video_files->isNotEmpty())
                @php
                    $urlSources = $video_files->filter(fn($f) => !empty($f->file_url))->values();
                @endphp
                @foreach ($urlSources as $idx => $vf)
                    @php
                        $playUrl = $vf->file_url ?? '';
                        $srcType = $vf->source_type ?? $vf->file_source ?? '';
                        if ($srcType == 'youtube' && preg_match('/(?:youtube\.com\/.*[?&]v=|youtu\.be\/)([^&\s?#]+)/', $playUrl, $ytM)) {
                            $playUrl = 'https://www.youtube.com/watch?v=' . $ytM[1];
                        } elseif ($srcType == 'gdrive' && ($gkey = get_config('google_api_key')) && preg_match('/\/d\/([^\/?#]+)/', $playUrl, $gdM)) {
                            $playUrl = 'https://www.googleapis.com/drive/v3/files/' . $gdM[1] . '?alt=media&key=' . $gkey . '&v=.mp4';
                        } elseif (!preg_match('#^https?://#i', $playUrl)) {
                            $path = preg_replace('#^public/#i', '', ltrim($playUrl, '/'));
                            $playUrl = preg_replace('#/public(?=/|$)#', '', url($path));
                        }
                    @endphp
                    {source:'{{ addslashes($playUrl) }}', label:'{{ strtoupper($vf->source_type ?? 'Quality ' . ($idx + 1)) }}'}@if (!$loop->last),@endif
                @endforeach
            @else
            {source:'{{ addslashes($video->video_url ?? '') }}', label:'Original'}
            @endif
            ]"
            data-start-at-video="0"
            data-poster-source="{{ getFileLink('thumbnail', $video->poster, $video_type . 's', '500x400') }}"
            @if($subtitleSourceAttr !== '')
            data-subtitle-soruce="{{ $subtitleSourceAttr }}"
            data-start-at-subtitle="1"
            @else
            data-start-at-subtitle="1"
            @endif
            data-downloadable="no">
            <ul data-ads="">
                @if ($pre_roll_ad)
                    <li data-source="{{ $pre_roll_ad->video_link }}" data-time-start="00:00:02"
                        data-time-to-hold-ads={{ $pre_roll_ad->skip_after }} data-link="{{ $pre_roll_ad->redirect_url }}"
                        data-target="_blank"></li>
                @endif
                @if ($mid_roll_ad)
                    <li data-source="{{ $mid_roll_ad->video_link }}" data-time-start="{{ $mid_roll_ad->start_time }}"
                        data-time-to-hold-ads={{ $mid_roll_ad->skip_after }}
                        data-add-duration="{{ $mid_roll_ad->end_time }}" data-thumbnail-source=""
                        data-link="{{ $mid_roll_ad->video_link }}" data-target="_blank"></li>
                @endif
                @if ($post_roll_ad)
                    <li data-source="{{ $post_roll_ad->video_link }}"
                        data-time-start="{{ getVideoAdTimestamp($video->runtime, $post_roll_ad->ad_duration, 'start') }}"
                        data-time-to-hold-ads={{ $post_roll_ad->skip_after }}
                        data-add-duration="{{ getVideoAdTimestamp($video->runtime, $post_roll_ad->ad_duration, 'end') }}"
                        data-thumbnail-source="" data-link="{{ $mid_roll_ad->video_link }}" data-target="_blank"
                        id="post_roll"></li>
                @endif
            </ul>
            <div data-video-short-description="">
                <div>
                    <p class="fwduvp-thumbnail-title"> {{ $video->title }} </p>
                    <p class="fwduvp-thumbnail-description">{{ $video->description }}</p>
                </div>
            </div>
        </li>
    </ul>

    <!--  HTML mixed playlist -->
    <script src="{{ static_asset('website/js/jquery-3.7.1.min.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPData.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPlayer.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPVideoScreen.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPComplexButton.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPContextMenu.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPXConsole.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPController.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPDisplayObject.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPEventDispatcher.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPInfo.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDXAnimation.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPPreloader.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPVolumeButton.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPUtils.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPPoster.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPSimpleButton.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPTransformDisplayObject.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPHider.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPYoutubeScreen.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPYTBQButton.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPLogo.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPCategories.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPCategoriesThumb.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPToolTip.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPPlaylist.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPPlaylistThumb.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDXUVPDL.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPEmbedWindow.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPSimpleSizeButton.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPInfoWindow.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPAdsButton.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPAdsStart.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPSubtitle.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPShareWindow.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPVimeoScreen.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPOpener.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPPreloader2.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPLightBox.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPPupupAds.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPPopupAddButton.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPAnnotations.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPAnnotation.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPComboBox.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPComboBoxSelector.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPComboBoxButton.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPAudioScreen.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPPassword.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPOPWindow.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPScrubberToolip.js') }}"></script>
    <script type="text/javascript" src="{{ static_asset('website/player/js/FWDUVPContextMenuButton.js') }}"></script>

    <!-- Setup video player-->
    <script type="text/javascript">
        FWDConsole.setPrototype();
        var logger;

        FWDUVPlayer.videoStartBehaviour = "stop";

        FWDUVPUtils.onReady(function() {
            const player = new FWDUVPlayer({
                //main settings
                instanceName: "player1",
                parentId: "myDiv",
                playlistsId: "playlists",
                mainFolderPath: "{{ static_asset('website/player/content/') }}",
                skinPath: "minimal_skin_dark",
                displayType: "responsive",
                initializeOnlyWhenVisible: "yes",
                useVectorIcons: "yes",
                fillEntireVideoScreen: "yes",
                fillEntireposterScreen: "yes",
                goFullScreenOnButtonPlay: "no",
                playsinline: "yes",
                privateVideoPassword: "428c841430ea18a70f7b06525d4b748a",
                youtubeAPIKey: "{{ get_config('google_api_key') }}",
                useHEXColorsForSkin: "yes",
                normalHEXButtonsColor: "#FF0000",
                useDeepLinking: "no",
                googleAnalyticsMeasurementId: "G-842HPC3W6L",
                useResumeOnPlay: "no",
                showPreloader: "yes",
                preloaderBackgroundColor: "#000000",
                preloaderFillColor: "#FFFFFF",
                addKeyboardSupport: "yes",
                autoScale: "yes",
                showButtonsToolTip: "yes",
                stopVideoWhenPlayComplete: "yes",
                playAfterVideoStop: "no",
                autoPlay: "yes",
                autoPlayText: "Click To Unmute",
                loop: "no",
                shuffle: "no",
                showErrorInfo: "yes",
                maxWidth: 1500,
                maxHeight: 900,
                buttonsToolTipHideDelay: 1.5,
                volume: 10,
                rewindTime: 10,
                backgroundColor: "#000000",
                videoBackgroundColor: "#000000",
                posterBackgroundColor: "#000000",
                buttonsToolTipFontColor: "#5a5a5a",
                //logo settings
                showLogo: "yes",
                logoPath: "{{ getFileLink('original_image', get_config('player_logo'), 'player_logos', '130x50') }}",
                hideLogoWithController: "yes",
                logoPosition: "topRight",
                logoLink: "{{ route('home') }}",
                logoTarget: '_blank',
                logoMargins: 10,

                //playlists/categories settings
                showPlaylistsSearchInput: "yes",
                usePlaylistsSelectBox: "yes",
                showPlaylistsButtonAndPlaylists: "no",
                showPlaylistsByDefault: "no",
                thumbnailSelectedType: "opacity",
                startAtPlaylist: 0,
                buttonsMargins: 15,
                thumbnailMaxWidth: 350,
                thumbnailMaxHeight: 350,
                horizontalSpaceBetweenThumbnails: 40,
                verticalSpaceBetweenThumbnails: 40,
                inputBackgroundColor: "#333333",
                inputColor: "#999999",
                //playlist settings
                showPlaylistButtonAndPlaylist: "no",
                playlistPosition: "right",
                showPlaylistByDefault: "yes",
                showPlaylistName: "yes",
                showSearchInput: "yes",
                showLoopButton: "no",
                showShuffleButton: "no",
                showPlaylistOnFullScreen: "no",
                showNextAndPrevButtons: "no",
                showThumbnail: "no",
                showOnlyThumbnail: "no",
                forceDisableDownloadButtonForFolder: "no",
                addMouseWheelSupport: "no",
                startAtRandomVideo: "no",
                stopAfterLastVideoHasPlayed: "no",
                addScrollOnMouseMove: "no",
                randomizePlaylist: 'no',
                folderVideoLabel: "VIDEO ",
                playlistRightWidth: 310,
                playlistBottomHeight: 380,
                startAtVideo: 0,
                maxPlaylistItems: 50,
                thumbnailWidth: 71,
                thumbnailHeight: 71,
                spaceBetweenControllerAndPlaylist: 1,
                spaceBetweenThumbnails: 1,
                scrollbarOffestWidth: 8,
                scollbarSpeedSensitivity: .5,
                playlistBackgroundColor: "#000000",
                playlistNameColor: "#FFFFFF",
                thumbnailNormalBackgroundColor: "#1b1b1b",
                thumbnailHoverBackgroundColor: "#313131",
                thumbnailDisabledBackgroundColor: "#272727",
                searchInputBackgroundColor: "#000000",
                searchInputColor: "#999999",
                youtubeAndFolderVideoTitleColor: "#FFFFFF",
                folderAudioSecondTitleColor: "#999999",
                youtubeOwnerColor: "#888888",
                youtubeDescriptionColor: "#888888",
                mainSelectorBackgroundSelectedColor: "#FFFFFF",
                mainSelectorTextNormalColor: "#FFFFFF",
                mainSelectorTextSelectedColor: "#000000",
                mainButtonBackgroundNormalColor: "#212021",
                mainButtonBackgroundSelectedColor: "#FFFFFF",
                mainButtonTextNormalColor: "#FFFFFF",
                mainButtonTextSelectedColor: "#000000",
                //controller settings
                showController: "yes",
                showControllerWhenVideoIsStopped: "yes",
                showNextAndPrevButtonsInController: "no",
                showRewindButton: "yes",
                showPlaybackRateButton: "yes",
                showVolumeButton: "yes",
                showTime: "yes",
                showAudioTracksButton: "yes",
                showQualityButton: "yes",
                showInfoButton: "yes",
                showDownloadButton: "no",
                showShareButton: "yes",
                showEmbedButton: "yes",
                showChromecastButton: "yes",
                show360DegreeVideoVrButton: "yes",
                showFullScreenButton: "yes",
                disableVideoScrubber: "no",
                showScrubberWhenControllerIsHidden: "yes",
                showMainScrubberToolTipLabel: "yes",
                showDefaultControllerForVimeo: "yes",
                repeatBackground: "yes",
                controllerHeight: 42,
                controllerHideDelay: 3,
                startSpaceBetweenButtons: 7,
                spaceBetweenButtons: 8,
                scrubbersOffsetWidth: 2,
                mainScrubberOffestTop: 14,
                timeOffsetLeftWidth: 5,
                timeOffsetRightWidth: 3,
                timeOffsetTop: 0,
                volumeScrubberHeight: 80,
                volumeScrubberOfsetHeight: 12,
                timeColor: "#888888",
                showYoutubeRelAndInfo: "no",
                youtubeQualityButtonNormalColor: "#888888",
                youtubeQualityButtonSelectedColor: "#FFFFFF",
                scrubbersToolTipLabelBackgroundColor: "#FFFFFF",
                scrubbersToolTipLabelFontColor: "#5a5a5a",
                //advertisement on pause window
                aopwTitle: "Advertisement",
                aopwWidth: 400,
                aopwHeight: 240,
                aopwBorderSize: 6,
                aopwTitleColor: "#FFFFFF",
                //subtitle
                subtitlesOffLabel: "Subtitle off",
                showSubtitleButton: '{{ $subtitleSourceAttr !== '' ? 'yes' : 'no' }}',
                //popup add windows
                showPopupAdsCloseButton: "yes",
                //embed window and info window
                embedAndInfoWindowCloseButtonMargins: 15,
                borderColor: "#333333",
                mainLabelsColor: "#FFFFFF",
                secondaryLabelsColor: "#a1a1a1",
                shareAndEmbedTextColor: "#5a5a5a",
                inputBackgroundColor: "#000000",
                inputColor: "#FFFFFF",
                //login
                playIfLoggedIn: "no",
                playIfLoggedInMessage: "Please <a href='https://google.com' target='_blank'>login</a> to play this video.",
                defaultPlaybackRate: 1, //0.25, 0.5, 1, 1.25, 1.2, 2
                //cuepoints
                executeCuepointsOnlyOnce: "no",
                //annotations
                showAnnotationsPositionTool: "no",
                //ads
                openNewPageAtTheEndOfTheAds: "no",
                playAdsOnlyOnce: "no",
                adsButtonsPosition: "right",
                skipToVideoText: "You can skip to video in: ",
                skipToVideoButtonText: "Skip Ad",
                adsTextNormalColor: "#888888",
                adsTextSelectedColor: "#FFFFFF",
                adsBorderNormalColor: "#666666",
                adsBorderSelectedColor: "#FFFFFF",
                //a to b loop
                useAToB: "no",
                atbTimeBackgroundColor: "transparent",
                atbTimeTextColorNormal: "#888888",
                atbTimeTextColorSelected: "#FFFFFF",
                atbButtonTextNormalColor: "#888888",
                atbButtonTextSelectedColor: "#FFFFFF",
                atbButtonBackgroundNormalColor: "#FFFFFF",
                atbButtonBackgroundSelectedColor: "#000000",
            });
        });

        function goFullScreen() {
            player1.goFullScreen();
        }

        setTimeout(() => {
            goFullScreen()
        }, 1000);
    </script>

    <script>
        "use strict";
        // Convert MM:SS or HH:MM:SS to seconds
        function timeToSeconds(time) {
            if (typeof time === 'number') return time;

            const parts = time.split(':');
            if (parts.length === 3) {
                // HH:MM:SS format
                return (+parts[0]) * 3600 + (+parts[1]) * 60 + (+parts[2]);
            } else if (parts.length === 2) {
                // MM:SS format
                return (+parts[0]) * 60 + (+parts[1]);
            }
            return 0;
        }

        // Track video watch history
        function trackWatchHistory(videoType, videoId, duration, watchedSeconds) {

            $.ajax({
                url: '{{ route('watch.history.store') }}',
                type: 'POST',
                dataType: 'json', // Expect JSON back
                data: {
                    watchable_type: videoType,
                    watchable_id: videoId,
                    duration: duration,
                    watched_seconds: watchedSeconds,
                    _token: '{{ csrf_token() }}' // CSRF token
                },
                success: function(data) {

                },
            });
        }


        <?php if(isset($video->id)){?>
        // Setup player tracking
        function setupHistoryTracking() {
            const videoType = "{{ $video_type }}";
            const videoId = {{ $video->id }};
            let lastUpdateTime = 0; // Always store in seconds
            let isPlaying = true;
            let duration = 0; // Should be in seconds

            // Get duration from player if not available
            if (duration <= 0) {
                setTimeout(() => {
                    duration = timeToSeconds(player1.getTotalTime());
                }, 3000);
            }


            // Track every 5 seconds while playing
            const trackingInterval = setInterval(() => {
                if (isPlaying) {
                    const currentTime = timeToSeconds(player1.getCurrentTime());
                    // Only update if at least 5 seconds of new content watched
                    if (currentTime - lastUpdateTime >= 5) {
                        console.log('Updating history - new content watched');
                        trackWatchHistory(videoType, videoId, duration, currentTime);
                        lastUpdateTime = currentTime;
                    }
                }
            }, 5000); // Check every 5 seconds

            // Player event handlers
            player1.onPlay = function() {
                isPlaying = true;
                lastUpdateTime = timeToSeconds(player1.getCurrentTime());
            };

            player1.onPause = function() {
                isPlaying = false;
                const currentTime = timeToSeconds(player1.getCurrentTime());
                trackWatchHistory(videoType, videoId, duration, currentTime);
            };

            player1.onComplete = function() {
                isPlaying = false;
                trackWatchHistory(videoType, videoId, duration, duration);
                clearInterval(trackingInterval);
            };

            // Track when leaving page
            window.addEventListener('beforeunload', () => {
                if (isPlaying) {
                    const currentTime = timeToSeconds(player1.getCurrentTime());

                    navigator.sendBeacon(
                        '{{ route('watch.history.store') }}',
                        JSON.stringify({
                            watchable_type: videoType,
                            watchable_id: videoId,
                            duration: duration,
                            watched_seconds: currentTime,
                            _token: '{{ csrf_token() }}'
                        })
                    );
                }
            });
        }

        // Initialize when player is ready
        FWDUVPUtils.onReady(function() {
            setTimeout(() => {
                setupHistoryTracking();

                // Resume functionality
                @if (auth()->check())
                    @php
                        $history = \App\Models\WatchHistory::where('user_id', auth()->id())
                            ->where('watchable_type', $video_type)
                            ->where('watchable_id', $video->id)
                            ->first();
                    @endphp

                    @if ($history && $history->completion_percentage)
                        const resumeSeconds = {{ $history->watched_seconds ?? 0 }};
                        if (resumeSeconds > 10) {
                            // Convert seconds to hh:mm:ss format for scrubbAtTime
                            const hours = Math.floor(resumeSeconds / 3600);
                            const minutes = Math.floor((resumeSeconds % 3600) / 60);
                            const seconds = Math.floor(resumeSeconds % 60);
                            const timeString =
                                `${hours.toString().padStart(2, '0')}:` +
                                `${minutes.toString().padStart(2, '0')}:` +
                                `${seconds.toString().padStart(2, '0')}`;

                            setTimeout(function() {
                                var totalTime = timeToSeconds(player1.getTotalTime());
                                if (resumeSeconds <= (totalTime - 20)) {
                                    player1.scrubbAtTime(timeString);
                                }
                            }, 100)

                            // Optional: Show brief notification
                            const resumeTimeFormatted = player1.getTotalTime('text', resumeSeconds);
                        }
                    @endif
                @endif
            }, 3000);
        });
        <?php } ?>
        // Format seconds to HH:MM:SS
        function formatTime(totalSeconds) {
            const hours = Math.floor(totalSeconds / 3600);
            const minutes = Math.floor((totalSeconds % 3600) / 60);
            const seconds = Math.floor(totalSeconds % 60);

            return [hours, minutes.toString().padStart(2, '0'), seconds.toString().padStart(2, '0')]
                .filter((num, index) => num > 0 || index > 0)
                .join(':');
        }
    </script>

@endsection
