@extends('layouts.app')

@section('main_class', 'video-view-page')
@section('title', $video->title . ' | ' . config('app.name'))

@push('head')
<meta property="og:title"       content="{{ $video->title }}">
<meta property="og:description" content="{{ Str::limit(strip_tags($video->description ?? config('app.name') . ' — watch now'), 200) }}">
<meta property="og:image"        content="{{ route('videos.ogImage', $video) }}">
<meta property="og:image:width"  content="1200">
<meta property="og:image:height" content="630">
<meta property="og:url"         content="{{ $video->share_url }}">
<meta property="og:type"        content="video.other">
<meta property="og:site_name"   content="{{ config('app.name') }}">
<meta name="twitter:card"       content="summary_large_image">
<meta name="twitter:title"      content="{{ $video->title }}">
<meta name="twitter:description" content="{{ Str::limit(strip_tags($video->description ?? ''), 200) }}">
<meta name="twitter:image"      content="{{ route('videos.ogImage', $video) }}">
@endpush

@section('extra_styles')
    <style>
        /* Video Section */
        .yt-video-section {
            flex: 1;
            min-width: 0;
        }

        /* Video Player */
        .video-container {
            position: relative;
            aspect-ratio: 16/9;
            background: #000;
            border-radius: 12px;
            overflow: hidden;
            max-height: 70vh;
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100%;
        }

        .video-container.portrait,
        .video-container.square,
        .video-container.ultrawide {
            margin: 0 auto;
            width: auto;
        }

        .video-container.portrait {
            aspect-ratio: 9/16;
            max-width: 50vh;
        }

        .video-container.square {
            aspect-ratio: 1/1;
            max-width: 70vh;
        }

        .video-container.ultrawide {
            aspect-ratio: 21/9;
            max-width: 100%;
        }

        .video-container video {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        /* Playlist Navigation Controls */
        .playlist-controls {
            position: absolute;
            bottom: 60px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            align-items: center;
            gap: 12px;
            background: rgba(0, 0, 0, 0.8);
            padding: 8px 16px;
            border-radius: 24px;
            z-index: 10;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .video-container:hover .playlist-controls,
        .playlist-controls.visible {
            opacity: 1;
        }

        .playlist-nav-btn {
            background: transparent;
            border: none;
            color: white;
            cursor: pointer;
            padding: 8px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.2s ease;
        }

        .playlist-nav-btn:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        .playlist-nav-btn:disabled {
            opacity: 0.3;
            cursor: not-allowed;
        }

        .playlist-nav-btn:disabled:hover {
            background: transparent;
        }

        .playlist-nav-btn i {
            font-size: 20px;
        }

        .playlist-nav-label {
            font-size: 12px;
            color: #aaa;
            max-width: 120px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* Autoplay Toggle */
        .autoplay-toggle {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 0 8px;
            border-left: 1px solid rgba(255, 255, 255, 0.2);
        }

        .autoplay-toggle label {
            font-size: 12px;
            color: #aaa;
            cursor: pointer;
            white-space: nowrap;
        }

        .autoplay-switch {
            position: relative;
            width: 36px;
            height: 20px;
        }

        .autoplay-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .autoplay-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #666;
            transition: 0.3s;
            border-radius: 20px;
        }

        .autoplay-slider:before {
            position: absolute;
            content: "";
            height: 14px;
            width: 14px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: 0.3s;
            border-radius: 50%;
        }

        .autoplay-switch input:checked+.autoplay-slider {
            background-color: var(--brand-red);
        }

        .autoplay-switch input:checked+.autoplay-slider:before {
            transform: translateX(16px);
        }

        /* Keyboard hint */
        .keyboard-hint {
            position: absolute;
            bottom: 10px;
            right: 10px;
            font-size: 10px;
            color: rgba(255, 255, 255, 0.5);
            background: rgba(0, 0, 0, 0.6);
            padding: 4px 8px;
            border-radius: 4px;
        }

        /* Video Info */
        .video-title {
            font-size: 20px;
            font-weight: 500;
            margin: 16px 0 8px;
            line-height: 1.3;
        }

        .video-stats-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-bottom: 12px;
            border-bottom: 1px solid var(--border-color);
            flex-wrap: wrap;
            gap: 12px;
        }

        .video-stats-left {
            display: flex;
            align-items: center;
            gap: 16px;
            color: var(--text-secondary);
        }



        /* Description */
        .video-description {
            background: var(--bg-secondary);
            border-radius: 12px;
            padding: 16px;
            margin-top: 16px;
        }

        .description-text {
            white-space: pre-wrap;
            font-size: 14px;
            line-height: 1.5;
        }

        /* Sidebar */
        .yt-sidebar-container {
            width: 400px;
            flex-shrink: 0;
        }

        .sidebar-video-card {
            display: flex;
            gap: 8px;
            margin-bottom: 8px;
            cursor: pointer;
            border-radius: 8px;
            padding: 4px;
            transition: background .15s;
        }

        .sidebar-video-card.current-video {
            background: rgba(239,68,68,.12);
            border-left: 3px solid #ef4444;
        }

        .sidebar-video-card.rec-next-up {
            border-left: 3px solid var(--brand-red);
        }

        .sidebar-video-card.rec-next-up .sidebar-title::before {
            content: '▶ ';
            color: var(--brand-red);
            font-size: 10px;
        }

        .sidebar-thumb {
            width: 168px;
            aspect-ratio: 16/9;
            border-radius: 8px;
            overflow: hidden;
            background: #1a1a1a;
            flex-shrink: 0;
        }

        .sidebar-thumb img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .sidebar-info {
            flex: 1;
            min-width: 0;
        }

        .sidebar-title {
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 4px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .sidebar-meta {
            font-size: 12px;
            color: var(--text-secondary);
        }

        /* Responsive */
        @media (max-width: 1300px) {
            .yt-sidebar-container {
                width: 300px;
            }
        }

        @media (max-width: 991px) {
            .yt-main {
                margin-left: 0;
                flex-direction: column;
            }

            .yt-sidebar-container {
                width: 100%;
            }

            .sidebar-video-card {
                flex-direction: column;
            }

            .sidebar-thumb {
                width: 100%;
            }

            .video-layout-container {
                flex-direction: column !important;
            }

            .yt-video-section {
                width: 100% !important;
                flex: none !important;
            }

            .yt-sidebar-container {
                width: 100% !important;
                margin-top: 16px;
            }
        }

        @media (max-width: 576px) {
            .video-stats-row {
                flex-direction: column;
                align-items: flex-start;
            }

            .video-actions {
                width: 100%;
                overflow-x: auto;
                justify-content: flex-start;
            }

            .video-container {
                max-height: 50vh !important;
                border-radius: 0 !important;
            }

            .video-container video {
                object-fit: contain !important;
            }

            .video-title {
                font-size: 16px !important;
                margin: 12px 0 6px !important;
            }



            .subscribe-btn {
                width: 100%;
            }

            .video-description {
                padding: 12px !important;
            }

            .comment-form {
                flex-direction: column !important;
                align-items: stretch !important;
                gap: 12px !important;
            }

            .comment-form>div {
                flex-direction: column !important;
                align-items: stretch !important;
                gap: 12px !important;
                width: 100% !important;
            }

            .comment-form textarea {
                height: 80px !important;
                width: 100% !important;
            }

            .comment-form button {
                align-self: flex-end !important;
                width: auto !important;
                padding: 8px 20px !important;
            }
        }
    </style>
@endsection

@section('content')

    <!-- Video Layout Container -->
    <div class="video-layout-container" style="display: flex; gap: 24px; max-width: 1800px; margin: 0 auto;">

        <!-- Video Section -->
        <div class="yt-video-section">
            <!-- Video Player -->
            <x-video-player :video="$video"
                :next-video="$nextVideo ?? null"
                :previous-video="$previousVideo ?? null"
                :playlist="$playlist ?? null"
                :playlist-videos="$playlistVideos ?? null" />

            <!-- Video Title with Film Icon (Generic Type) -->
            <h1 class="video-title" style="display: flex; align-items: center; gap: 10px; margin: 8px 0 6px;">
                <i class="bi bi-film" style="color: #ef4444;"></i>
                <span>{{ $video->title }}</span>
            </h1>

            <!-- Stats Row - Hidden, shown in description box -->
            <div class="video-stats-row" style="display: none;">
                <div class="video-stats-left">
                    <span>{{ number_format($video->view_count) }} views</span>
                    <span>•</span>
                    <span>{{ $video->created_at->format('M d, Y') }}</span>
                </div>
            </div>

            <x-channel-row :video="$video" />

            @include('videos.partials.description-box', ['video' => $video])

            <x-video-comments :video="$video" />
        </div>

        <!-- Sidebar - Up Next / Recommendations -->
        <div class="yt-sidebar-container" style="display: flex; flex-direction: column; gap: 16px;">
            @if ($playlist && $playlistVideos && $playlistVideos->count() > 0)
                <h3 style="font-size: 16px; font-weight: 500; margin-bottom: 8px;">
                    <i class="bi bi-collection-play" style="margin-right: 8px;"></i>
                    {{ $playlist->name }}
                    <span
                        style="font-weight: 400; color: var(--text-secondary); font-size: 14px;">({{ $playlistVideos->count() }}
                        videos)</span>
                </h3>

                {{-- Playlist controls --}}
                <div class="pl-controls-bar">
                    <button class="pl-ctrl-btn" id="plPrevBtn" title="Previous" onclick="window.plPrev()">
                        <i class="bi bi-skip-start-fill"></i>
                    </button>
                    <button class="pl-ctrl-btn" id="plNextBtn" title="Next" onclick="window.plNext()">
                        <i class="bi bi-skip-end-fill"></i>
                    </button>
                    <div class="pl-ctrl-divider"></div>
                    <button class="pl-ctrl-btn" id="plShuffleBtn" title="Shuffle" onclick="plToggleShuffle()">
                        <i class="bi bi-shuffle"></i>
                    </button>
                    <button class="pl-ctrl-btn" id="plLoopBtn" title="Loop" onclick="plToggleLoop()">
                        <i class="bi bi-repeat"></i>
                    </button>
                    <button class="pl-ctrl-btn pl-ctrl-autoplay" id="plAutoplayBtn" title="Autoplay" onclick="plToggleAutoplay()">
                        <i class="bi bi-play-circle"></i>
                        <span class="pl-autoplay-label">Autoplay</span>
                    </button>
                </div>

                <script>
                (function () {
                var PL_ID      = '{{ $playlist->share_token }}';
                var PL_CURRENT = {{ $video->id }};
                var PL_VIDEOS  = {!! $playlistVideos->map(fn($v) => ['id' => $v->id, 'url' => route('videos.show', $v).'?playlist='.$playlist->share_token])->values()->toJson() !!};

                function plGet(k,d){ var v=localStorage.getItem('pl_'+k+'_'+PL_ID); return v!==null?v:d; }
                function plSet(k,v){ localStorage.setItem('pl_'+k+'_'+PL_ID,v); }

                var plAutoplay   = plGet('autoplay','1');
                var plLoop       = plGet('loop','off');
                var plShuffle    = plGet('shuffle','0');
                var plTransiting = false;

                function plShuffleOrder(){ var o=PL_VIDEOS.map(function(_,i){return i;}); for(var i=o.length-1;i>0;i--){var j=Math.floor(Math.random()*(i+1));var t=o[i];o[i]=o[j];o[j]=t;} localStorage.setItem('pl_shuffleOrder_'+PL_ID,JSON.stringify(o)); return o; }
                function plGetOrder(){ var r=localStorage.getItem('pl_shuffleOrder_'+PL_ID); if(r){try{return JSON.parse(r);}catch(e){}} return null; }

                function plAdj(curId) {
                    var idx=PL_VIDEOS.findIndex(function(v){ return v.id===curId; });
                    if(plShuffle==='1'){
                        var ord=plGetOrder()||plShuffleOrder();
                        var pos=ord.indexOf(idx);
                        var pp=pos>0?pos-1:(plLoop==='all'?ord.length-1:-1);
                        var np=pos<ord.length-1?pos+1:(plLoop==='all'?0:-1);
                        return { prev:pp>=0?PL_VIDEOS[ord[pp]].url:'', next:np>=0?PL_VIDEOS[ord[np]].url:'' };
                    }
                    return {
                        prev: idx>0?PL_VIDEOS[idx-1].url:'',
                        next: idx<PL_VIDEOS.length-1?PL_VIDEOS[idx+1].url:(plLoop==='all'?PL_VIDEOS[0].url:'')
                    };
                }

                function plFmt(s){ var m=Math.floor(s/60),ss=Math.floor(s%60); return m+':'+(ss<10?'0':'')+ss; }

                async function plTransitionTo(url, pushHist) {
                    if(!url||plTransiting) return;
                    plTransiting=true;
                    try {
                        var m=url.match(/\/videos\/([^/?#]+)/);
                        if(!m){ window.location.href=url; return; }
                        var qs=url.indexOf('?')!==-1?url.substring(url.indexOf('?')):'';
                        var resp=await fetch('/videos/'+m[1]+'/player-data'+qs);
                        if(!resp.ok){ window.location.href=url; return; }
                        var d=await resp.json();

                        // reload video source (HLS or MP4)
                        if(window._ytpLoadSource) window._ytpLoadSource(d.hls_url, d.stream_url);

                        // reset progress bar
                        var pl=document.getElementById('ytpPlayed'),sc=document.getElementById('ytpScrubber');
                        var cu=document.getElementById('ytpCurrent'),dr=document.getElementById('ytpDuration');
                        if(pl) pl.style.width='0%';
                        if(sc) sc.style.left='0%';
                        if(cu) cu.textContent='0:00';
                        if(dr&&d.duration) dr.textContent=plFmt(d.duration);

                        // update page title
                        var ts=document.querySelector('.video-title span');
                        if(ts) ts.textContent=d.title;
                        document.title=d.title+' | {{ config("app.name") }}';

                        // update loop state on video element
                        var vid=document.getElementById('videoPlayer');
                        if(vid) vid.loop=(plLoop==='one');

                        PL_CURRENT=d.id;
                        plRender();
                        plHighlight(d.id);
                        if(pushHist!==false) history.pushState({plVideoId:d.id,url:url},'',url);

                        plSwapContent(url);
                    } catch(e){
                        console.warn('plTransitionTo',e);
                        window.location.href=url;
                    } finally {
                        plTransiting=false;
                    }
                }

                async function plSwapContent(url) {
                    try {
                        var resp=await fetch(url,{headers:{'Accept':'text/html','X-Requested-With':'XMLHttpRequest'}});
                        var html=await resp.text();
                        var doc=new DOMParser().parseFromString(html,'text/html');

                        var nv=doc.getElementById('vdbWrap'),ov=document.getElementById('vdbWrap');
                        if(nv&&ov) ov.innerHTML=nv.innerHTML;

                        var nc=doc.querySelector('.channel-row'),oc=document.querySelector('.channel-row');
                        if(nc&&oc) oc.innerHTML=nc.innerHTML;

                        var ny=doc.getElementById('ytcSection'),oy=document.getElementById('ytcSection');
                        if(ny&&oy){
                            oy.innerHTML=ny.innerHTML;
                            var ytcScript=Array.from(doc.querySelectorAll('script')).find(function(s){return s.textContent.includes('const YTC =');});
                            if(ytcScript){
                                var ns=document.createElement('script');
                                ns.textContent=ytcScript.textContent;
                                document.body.appendChild(ns);
                                document.body.removeChild(ns);
                            }
                        }
                    } catch(e){ console.warn('plSwapContent',e); }
                }

                function plHighlight(activeId){
                    document.querySelectorAll('.sidebar-video-card[data-pl-id]').forEach(function(c){
                        c.classList.toggle('current-video',parseInt(c.dataset.plId)===activeId);
                    });
                    var a=document.querySelector('.sidebar-video-card.current-video');
                    if(a) a.scrollIntoView({behavior:'smooth',block:'nearest'});
                }

                function plRender(){
                    var adj=plAdj(PL_CURRENT);
                    var sb=document.getElementById('plShuffleBtn'),lb=document.getElementById('plLoopBtn');
                    var ab=document.getElementById('plAutoplayBtn'),nb=document.getElementById('plNextBtn'),pb=document.getElementById('plPrevBtn');
                    if(sb){ sb.classList.toggle('pl-ctrl-active',plShuffle==='1'); sb.title='Shuffle: '+(plShuffle==='1'?'On':'Off'); }
                    if(lb){
                        lb.classList.remove('pl-ctrl-active');
                        if(plLoop==='all'){ lb.classList.add('pl-ctrl-active'); lb.innerHTML='<i class="bi bi-repeat"></i>'; lb.title='Loop: All'; }
                        else if(plLoop==='one'){ lb.classList.add('pl-ctrl-active'); lb.innerHTML='<i class="bi bi-repeat-1"></i>'; lb.title='Loop: One'; }
                        else { lb.innerHTML='<i class="bi bi-repeat"></i>'; lb.title='Loop: Off'; }
                    }
                    if(ab){ ab.classList.toggle('pl-ctrl-active',plAutoplay==='1'); ab.title='Autoplay: '+(plAutoplay==='1'?'On':'Off'); }
                    if(nb) nb.disabled=!adj.next;
                    if(pb) pb.disabled=!adj.prev;
                }

                window.plGoTo       = function(url){ if(url) plTransitionTo(url); };
                window.plNext       = function(){ var a=plAdj(PL_CURRENT); if(a.next) plTransitionTo(a.next); };
                window.plPrev       = function(){ var a=plAdj(PL_CURRENT); if(a.prev) plTransitionTo(a.prev); };
                window.plToggleShuffle  = function(){ plShuffle=plShuffle==='1'?'0':'1'; plSet('shuffle',plShuffle); if(plShuffle==='1') plShuffleOrder(); else localStorage.removeItem('pl_shuffleOrder_'+PL_ID); plRender(); };
                window.plToggleLoop     = function(){ var s=['off','all','one']; var i=s.indexOf(plLoop); plLoop=s[(i+1)%s.length]; plSet('loop',plLoop); plRender(); var v=document.getElementById('videoPlayer'); if(v) v.loop=(plLoop==='one'); };
                window.plToggleAutoplay = function(){ plAutoplay=plAutoplay==='1'?'0':'1'; plSet('autoplay',plAutoplay); plRender(); };

                // hook into video player: intercept next/prev and ended
                window._ytpNavOverride = {
                    next: function(_url){ window.plNext(); },
                    prev: function(_url){ window.plPrev(); }
                };
                window._plOnVideoEnd = function(){ if(plLoop==='one') return; if(plAutoplay==='1') window.plNext(); };

                window.addEventListener('popstate',function(e){ if(e.state&&e.state.url) plTransitionTo(e.state.url,false); });

                function plInit(){
                    var v=document.getElementById('videoPlayer');
                    if(v&&plLoop==='one') v.loop=true;
                    plRender();
                    plHighlight(PL_CURRENT);
                }
                if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',plInit); else plInit();
                })();
                </script>

                <div class="recommended-videos-list">
                    @foreach ($playlistVideos as $index => $playlistVideo)
                        @php $isCurrentTrack = $playlistVideo->id === $video->id; @endphp
                        <div class="sidebar-video-card{{ $isCurrentTrack ? ' current-video' : '' }}"
                            data-pl-id="{{ $playlistVideo->id }}"
                            onclick="plGoTo('{{ route('videos.show', $playlistVideo) }}?playlist={{ $playlist->share_token }}')"
                            style="cursor:pointer;">
                                <div class="sidebar-thumb" style="position: relative;">
                                    @if ($playlistVideo->thumbnail)
                                        <img src="{{ route('media.thumbnail', $playlistVideo->thumbnail) }}"
                                            alt="{{ $playlistVideo->title }}">
                                    @else
                                        <img src="https://picsum.photos/seed/{{ $playlistVideo->id }}/320/180"
                                            alt="{{ $playlistVideo->title }}">
                                    @endif
                                    @if ($playlistVideo->duration)
                                        <span
                                            class="yt-video-duration">{{ gmdate('i:s', $playlistVideo->duration) }}</span>
                                    @endif
                                    @if ($playlistVideo->is_shorts)
                                        <span class="yt-shorts-badge"
                                            style="position: absolute; top: 8px; left: 8px; font-size: 10px; padding: 2px 6px;">
                                            <i class="bi bi-collection-play-fill"></i> SHORTS
                                        </span>
                                    @endif
                                    <!-- Playlist position indicator -->
                                    <span
                                        style="position: absolute; bottom: 4px; left: 4px; background: rgba(0,0,0,0.8); color: white; padding: 2px 6px; border-radius: 4px; font-size: 12px; font-weight: 500;">
                                        {{ $index + 1 }}
                                    </span>
                                </div>
                                <div class="sidebar-info">
                                    <div class="sidebar-title">
                                        <i class="bi {{ match ($playlistVideo->type) {'music' => 'bi-music-note','match' => 'bi-trophy',default => 'bi-film'} }}"
                                            style="color: #ef4444; margin-right: 4px; font-size: 12px;"></i>
                                        {{ Str::limit($playlistVideo->title, 60) }}
                                    </div>
                                    <div class="sidebar-meta">
                                        <div>{{ $playlistVideo->user->name ?? 'Unknown' }}</div>
                                        <div>{{ number_format($playlistVideo->view_count) }} views •
                                            {{ $playlistVideo->created_at->diffForHumans() }}</div>
                                    </div>
                                </div>
                            </div>
                    @endforeach
                </div>
                @if ($playlist->canEdit(Auth::user()))
                    <a href="{{ route('playlists.show', $playlist->id) }}" class="action-btn" style="margin-top: 12px;">
                        <i class="bi bi-pencil"></i> <span>Edit Playlist</span>
                    </a>
                @endif
            @else
                {{-- Up Next header + autoplay toggle --}}
                <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:10px;">
                    <h3 style="font-size:16px; font-weight:500; margin:0;">
                        <i class="bi bi-collection-play" style="margin-right:6px;"></i>Up Next
                    </h3>
                    <div class="pl-controls-bar" style="margin-bottom:0; flex-shrink:0;">
                        <button class="pl-ctrl-btn pl-ctrl-autoplay" id="recAutoplayBtn"
                            title="Autoplay" onclick="recToggleAutoplay()">
                            <i class="bi bi-play-circle"></i>
                            <span class="pl-autoplay-label">Autoplay</span>
                        </button>
                    </div>
                </div>

                @if ($recommendedVideos && $recommendedVideos->count() > 0)
                    <div class="recommended-videos-list" id="recList">
                        @foreach ($recommendedVideos as $recVideo)
                            <div class="sidebar-video-card"
                                data-rec-url="{{ route('videos.show', $recVideo) }}"
                                onclick="recGoTo('{{ route('videos.show', $recVideo) }}')">
                                <div class="sidebar-thumb" style="position: relative;">
                                    @if ($recVideo->thumbnail)
                                        <img src="{{ route('media.thumbnail', $recVideo->thumbnail) }}"
                                            alt="{{ $recVideo->title }}">
                                    @else
                                        <img src="https://picsum.photos/seed/{{ $recVideo->id }}/320/180"
                                            alt="{{ $recVideo->title }}">
                                    @endif
                                    @if ($recVideo->duration)
                                        <span class="yt-video-duration">{{ gmdate('i:s', $recVideo->duration) }}</span>
                                    @endif
                                    @if ($recVideo->is_shorts)
                                        <span class="yt-shorts-badge"
                                            style="position: absolute; top: 8px; left: 8px; font-size: 10px; padding: 2px 6px;">
                                            <i class="bi bi-collection-play-fill"></i> SHORTS
                                        </span>
                                    @endif
                                </div>
                                <div class="sidebar-info">
                                    <div class="sidebar-title">
                                        <i class="bi {{ match ($recVideo->type) {'music' => 'bi-music-note','match' => 'bi-trophy',default => 'bi-film'} }}"
                                            style="color: #ef4444; margin-right: 4px; font-size: 12px;"></i>
                                        {{ Str::limit($recVideo->title, 60) }}
                                    </div>
                                    <div class="sidebar-meta">
                                        <div>{{ $recVideo->user->name ?? 'Unknown' }}</div>
                                        <div>{{ number_format($recVideo->view_count) }} views •
                                            {{ $recVideo->created_at->diffForHumans() }}</div>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                @else
                    <div class="text-secondary" id="recList">No recommendations available yet. Check back later!</div>
                @endif

                <script>
                (function () {
                var recTransiting = false;
                var recAutoplay   = localStorage.getItem('ytpAutoplay_solo') === '1';

                function recFmt(s){ var m=Math.floor(s/60),ss=Math.floor(s%60); return m+':'+(ss<10?'0':'')+ss; }

                function recRender() {
                    var btn = document.getElementById('recAutoplayBtn');
                    if (!btn) return;
                    btn.classList.toggle('pl-ctrl-active', recAutoplay);
                    btn.title = 'Autoplay: ' + (recAutoplay ? 'On' : 'Off');
                    // highlight the next-up card
                    var cards = document.querySelectorAll('#recList .sidebar-video-card');
                    cards.forEach(function(c,i){ c.style.opacity = recAutoplay && i===0 ? '1' : ''; });
                    var first = cards[0];
                    if(first) first.classList.toggle('rec-next-up', recAutoplay);
                }

                window.recToggleAutoplay = function() {
                    recAutoplay = !recAutoplay;
                    localStorage.setItem('ytpAutoplay_solo', recAutoplay ? '1' : '0');
                    recRender();
                };

                async function recTransitionTo(url, pushHist) {
                    if (!url || recTransiting) return;
                    recTransiting = true;
                    try {
                        var m = url.match(/\/videos\/([^/?#]+)/);
                        if (!m) { window.location.href = url; return; }
                        var resp = await fetch('/videos/' + m[1] + '/player-data');
                        if (!resp.ok) { window.location.href = url; return; }
                        var d = await resp.json();

                        // load new video source
                        if (window._ytpLoadSource) window._ytpLoadSource(d.hls_url, d.stream_url);

                        // reset progress bar
                        var pl=document.getElementById('ytpPlayed'),sc=document.getElementById('ytpScrubber');
                        var cu=document.getElementById('ytpCurrent'),dr=document.getElementById('ytpDuration');
                        if(pl) pl.style.width='0%'; if(sc) sc.style.left='0%';
                        if(cu) cu.textContent='0:00'; if(dr&&d.duration) dr.textContent=recFmt(d.duration);

                        // update title
                        var ts = document.querySelector('.video-title span');
                        if (ts) ts.textContent = d.title;
                        document.title = d.title + ' | {{ config("app.name") }}';

                        if (pushHist !== false) history.pushState({recUrl: url}, '', url);

                        // async: swap description + comments + sidebar
                        recSwapContent(url);
                    } catch(e) {
                        console.warn('recTransitionTo', e);
                        window.location.href = url;
                    } finally {
                        recTransiting = false;
                    }
                }

                async function recSwapContent(url) {
                    try {
                        var resp = await fetch(url, {headers:{'Accept':'text/html','X-Requested-With':'XMLHttpRequest'}});
                        var html = await resp.text();
                        var doc  = new DOMParser().parseFromString(html, 'text/html');

                        // description
                        var nv=doc.getElementById('vdbWrap'),ov=document.getElementById('vdbWrap');
                        if(nv&&ov) ov.innerHTML=nv.innerHTML;

                        // channel row
                        var nc=doc.querySelector('.channel-row'),oc=document.querySelector('.channel-row');
                        if(nc&&oc) oc.innerHTML=nc.innerHTML;

                        // comments
                        var ny=doc.getElementById('ytcSection'),oy=document.getElementById('ytcSection');
                        if(ny&&oy){
                            oy.innerHTML=ny.innerHTML;
                            var ytcScript=Array.from(doc.querySelectorAll('script')).find(function(s){return s.textContent.includes('const YTC =');});
                            if(ytcScript){
                                var ns=document.createElement('script');
                                ns.textContent=ytcScript.textContent;
                                document.body.appendChild(ns);
                                document.body.removeChild(ns);
                            }
                        }

                        // sidebar: swap inner content and re-run init scripts
                        var nSide=doc.querySelector('.yt-sidebar-container');
                        var oSide=document.querySelector('.yt-sidebar-container');
                        if(nSide&&oSide){
                            oSide.innerHTML=nSide.innerHTML;
                            // re-execute any inline scripts (rec init, playlist init, etc.)
                            Array.from(oSide.querySelectorAll('script')).forEach(function(s){
                                var ns=document.createElement('script');
                                ns.textContent=s.textContent;
                                document.body.appendChild(ns);
                                document.body.removeChild(ns);
                            });
                        }
                    } catch(e){ console.warn('recSwapContent', e); }
                }

                window.recGoTo = function(url) { if(url) recTransitionTo(url); };

                // autoplay: when video ends, play the first rec card
                window._plOnVideoEnd = function() {
                    if (!recAutoplay) return;
                    var first = document.querySelector('#recList .sidebar-video-card[data-rec-url]');
                    if (first) recTransitionTo(first.dataset.recUrl);
                };

                window.addEventListener('popstate', function(e){ if(e.state&&e.state.recUrl) recTransitionTo(e.state.recUrl,false); });

                if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',recRender); else recRender();
                })();
                </script>
            @endif
        </div>

    </div>

    @include('layouts.partials.edit-video-modal')

    @if (Session::has('openEditModal') && Session::get('openEditModal'))
        @auth
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    openEditVideoModal('{{ $video->getRouteKey() }}');
                });
            </script>
        @endauth
    @endif

@endsection
