@extends('layouts.app')

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

@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);
        }

        .video-actions {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .yt-action-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            border-radius: 20px;
            border: none;
            background: var(--bg-secondary);
            color: var(--text-primary);
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
        }

        .yt-action-btn:hover {
            background: var(--border-color);
        }

        .action-btn,
        .comments-section .action-btn {
            border: none;
            border-radius: 8px;
            padding: 8px 14px;
            font-size: 0.82rem;
            font-weight: 500;
            cursor: pointer;
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 6px;
            transition: all 0.2s ease;
        }

        .action-btn:hover,
        .comments-section .action-btn:hover {
            background: var(--border-color);
            transform: translateY(-1px);
        }

        .action-btn:active,
        .comments-section .action-btn:active {
            transform: translateY(0);
        }

        .action-btn svg,
        .action-btn i,
        .comments-section .action-btn svg,
        .comments-section .action-btn i {
            flex-shrink: 0;
        }

        .action-btn.comment-btn {
            background: var(--brand-red);
            color: white;
            border-color: var(--brand-red);
        }

        .yt-action-btn.liked {
            color: var(--brand-red);
        }

        /* Channel Row */
        .channel-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 16px 0;
        }

        .channel-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .channel-avatar {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            background: #555;
        }

        .channel-name {
            font-size: 16px;
            font-weight: 500;
        }

        .channel-subs {
            font-size: 14px;
            color: var(--text-secondary);
        }

        .subscribe-btn {
            border: none;
            border-radius: 8px;
            padding: 8px 14px;
            font-size: 0.82rem;
            font-weight: 500;
            cursor: pointer;
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 6px;
            transition: all 0.2s ease;
            white-space: nowrap;
        }

        .subscribe-btn:hover {
            background: var(--border-color);
            transform: translateY(-1px);
        }

        .mobile-action-dropdown {
            display: none;
            position: relative;
        }

        .mobile-action-dropdown .dropdown-menu {
            right: 0;
            left: auto;
            min-width: 200px;
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 10px;
            padding: 6px 0;
            z-index: 1200;
        }

        .mobile-action-dropdown .dropdown-item {
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            padding: 8px 12px;
            background: transparent;
            border: none;
            width: 100%;
            text-align: left;
        }

        .mobile-action-dropdown .dropdown-item:hover {
            background: var(--border-color);
        }

        /* 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;
        }

        .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;
            }

            .yt-main {
                padding: 12px !important;
            }

            .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;
            }

            .channel-row {
                flex-direction: column;
                align-items: flex-start !important;
                gap: 12px;
            }

            .channel-info {
                width: 100%;
            }

            .subscribe-btn {
                width: 100%;
            }

            .video-description {
                padding: 12px !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 -->
            <div class="video-container @if ($video->orientation === 'portrait') portrait @elseif($video->orientation === 'square') square @elseif($video->orientation === 'ultrawide') ultrawide @endif"
                id="videoContainer">
                <video id="videoPlayer" controls playsinline preload="metadata" autoplay>
                    <source src="{{ route('videos.stream', $video->id) }}" type="video/mp4">
                </video>

                <!-- Playlist Navigation Controls (only show when in playlist) -->
                @if ($nextVideo || $previousVideo)
                    <div class="playlist-controls" id="playlistControls">
                        <!-- Previous Video -->
                        @if ($previousVideo)
                            <button class="playlist-nav-btn" onclick="goToPreviousVideo()" title="Previous video">
                                <i class="bi bi-skip-backward-fill"></i>
                            </button>
                            <span class="playlist-nav-label">{{ Str::limit($previousVideo->title, 20) }}</span>
                        @else
                            <button class="playlist-nav-btn" disabled title="No previous video">
                                <i class="bi bi-skip-backward-fill"></i>
                            </button>
                        @endif

                        <!-- Autoplay Toggle -->
                        <div class="autoplay-toggle">
                            <label for="autoplayToggle">Autoplay</label>
                            <label class="autoplay-switch">
                                <input type="checkbox" id="autoplayToggle" checked>
                                <span class="autoplay-slider"></span>
                            </label>
                        </div>

                        <!-- Next Video -->
                        @if ($nextVideo)
                            <span class="playlist-nav-label">{{ Str::limit($nextVideo->title, 20) }}</span>
                            <button class="playlist-nav-btn" onclick="goToNextVideo()" title="Next video">
                                <i class="bi bi-skip-forward-fill"></i>
                            </button>
                        @else
                            <button class="playlist-nav-btn" disabled title="No next video">
                                <i class="bi bi-skip-forward-fill"></i>
                            </button>
                        @endif
                    </div>
                    <div class="keyboard-hint">
                        <i class="bi bi-arrow-left"></i> <i class="bi bi-arrow-right"></i>
                    </div>
                @endif
            </div>

            <!-- 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>

            <!-- Channel Row - All in one line -->
            <div class="channel-row"
                style="display: flex; align-items: center; justify-content: space-between; padding: 12px 0; flex-wrap: wrap; gap: 16px;">
                <div style="display: flex; align-items: center; gap: 12px;">
                    <a href="{{ route('channel', $video->user_id) }}" class="channel-info text-decoration-none"
                        style="color: inherit; display: flex; align-items: center; gap: 12px;">
                        @if ($video->user)
                            <img src="{{ $video->user->avatar_url }}" class="channel-avatar"
                                style="width: 40px; height: 40px; border-radius: 50%;" alt="{{ $video->user->name }}">
                        @else
                            <div class="channel-avatar" style="width: 40px; height: 40px; border-radius: 50%;"></div>
                        @endif
                        <div>
                            <div class="channel-name" style="font-weight: 600;">{{ $video->user->name ?? 'Unknown' }}</div>
                            <div class="channel-subs" style="font-size: 12px; color: var(--text-secondary);">
                                {{ number_format($video->user->subscriber_count ?? 0) }} subscribers</div>
                        </div>
                    </a>
                </div>

                <div class="video-actions"
                    style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap; overflow: visible;">
                    @auth
                        @if (Auth::id() !== $video->user_id)
                            <button class="subscribe-btn desktop-action">
                                <i class="bi bi-bell"></i>
                                <span>Subscribe</span>
                            </button>
                        @else
                            <!-- Edit button only in mobile dropdown now -->
                        @endif
                    @else
                        <a href="{{ route('login') }}" class="subscribe-btn desktop-action">
                            <i class="bi bi-bell"></i>
                            <span>Subscribe</span>
                        </a>
                    @endauth

                    @auth
                        <form method="POST"
                            action="{{ $video->isLikedBy(Auth::user()) ? route('videos.unlike', $video->id) : route('videos.like', $video->id) }}"
                            class="d-inline">
                            @csrf
                            <button type="submit" class="action-btn {{ $video->isLikedBy(Auth::user()) ? 'liked' : '' }}">
                                <i
                                    class="bi {{ $video->isLikedBy(Auth::user()) ? 'bi-hand-thumbs-up-fill' : 'bi-hand-thumbs-up' }}"></i>
                                {{ $video->like_count > 0 ? number_format($video->like_count) : 'Like' }}
                            </button>
                        </form>
                    @else
                        <a href="{{ route('login') }}" class="yt-action-btn">
                            <i class="bi bi-hand-thumbs-up"></i> Like
                        </a>
                    @endauth

                    @if ($video->isShareable())
                        <button class="action-btn"
                            onclick="openShareModal('{{ $video->share_url }}', '{{ addslashes($video->title) }}')">
                            <i class="bi bi-share"></i> Share
                        </button>
                    @endif

                    <!-- Save to Playlist Button -->
                    <button class="action-btn" onclick="openAddToPlaylistModal({{ $video->id }})">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                            stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"></path>
                        </svg>
                        <span>Save</span>
                    </button>


                </div>
            </div>

            <!-- Description Box -->
            @if ($video->description)
                @php
                    $fullDescription = $video->description;
                    $shortDescription = Str::limit($fullDescription, 200);
                    $needsExpand = strlen($fullDescription) > 200;
                @endphp

                <div class="video-description-box"
                    style="background: var(--bg-secondary); border-radius: 12px; padding: 12px; margin-bottom: 16px;">
                    <div class="description-stats" style="font-size: 14px; font-weight: 500; margin-bottom: 8px;">
                        <span>{{ number_format($video->view_count) }} views</span>
                        <span>•</span>
                        <span>{{ $video->created_at->format('M d, Y') }}</span>
                    </div>
                    <div style="border-bottom: 1px solid var(--border-color); margin: 8px 0;"></div>
                    <div class="description-content" id="descriptionContent">
                        @if ($needsExpand)
                            <div class="description-short" id="descShort">
                                <span class="description-text">{!! Str::markdown($shortDescription) !!}</span>
                                <span class="description-ellipsis" style="color: var(--text-secondary);">... </span>
                            </div>
                            <div class="description-full" id="descFull" style="display: none;">
                                <span class="description-text">{!! Str::markdown($fullDescription) !!}</span>
                            </div>
                            <button onclick="toggleDescription()" id="descToggleBtn"
                                style="background: none; border: none; color: var(--text-primary); font-weight: 600; font-size: 14px; cursor: pointer; padding: 0; margin-top: 4px;">
                                Show more
                            </button>
                        @else
                            <span class="description-text">{!! Str::markdown($fullDescription) !!}</span>
                        @endif
                    </div>
                </div>

                <script>
                    function toggleDescription() {
                        const descShort = document.getElementById('descShort');
                        const descFull = document.getElementById('descFull');
                        const toggleBtn = document.getElementById('descToggleBtn');

                        if (descShort.style.display !== 'none') {
                            descShort.style.display = 'none';
                            descFull.style.display = 'block';
                            toggleBtn.textContent = 'Show less';
                        } else {
                            descShort.style.display = 'block';
                            descFull.style.display = 'none';
                            toggleBtn.textContent = 'Show more';
                        }
                    }
                </script>

                <style>
                    .video-description-box .description-text {
                        font-size: 14px;
                        line-height: 1.5;
                        color: var(--text-primary);
                    }

                    .video-description-box .description-text p {
                        margin-bottom: 8px;
                    }

                    .video-description-box .description-text a {
                        color: #3ea6ff;
                    }
                </style>
            @endif

            <!-- Comment Section -->
            <div class="comments-section"
                style="margin-top: 24px; padding-top: 16px; border-top: 1px solid var(--border-color);">
                <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 16px;">
                    Comments <span
                        style="color: var(--text-secondary); font-weight: 400;">({{ $video->comment_count }})</span>
                </h3>

                @auth
                    <div class="comment-form" style="display: flex; gap: 12px; margin-bottom: 24px;">
                        <img src="{{ Auth::user()->avatar_url }}" class="channel-avatar" style="width: 40px; height: 40px;"
                            alt="{{ Auth::user()->name }}">
                        <div style="flex: 1; display: flex; align-items: center; gap: 8px;">
                            <textarea id="commentBody" class="form-control" placeholder="Add a comment... Use @ to mention someone"
                                rows="1"
                                style="background: transparent; border: none; border-bottom: 2px solid var(--border-color); color: var(--text-primary); border-radius: 0; padding: 12px 0 8px 0; flex: 1; margin: 0; height: 40px; font-size: 14px; outline: none; overflow: hidden;"></textarea>
                            <button type="button" class="action-btn"
                                onclick="document.getElementById('commentBody').value = ''" style="flex-shrink: 0;">
                                <i class="bi bi-x-lg"></i>
                                <span>Cancel</span>
                            </button>
                            <button type="button" class="action-btn comment-btn"
                                onclick="submitComment({{ $video->id }})" style="flex-shrink: 0;">
                                <i class="bi bi-chat-dots"></i>
                                <span>Comment</span>
                            </button>
                        </div>
                    </div>
                @else
                    <div
                        style="margin-bottom: 24px; padding: 16px; background: var(--bg-secondary); border-radius: 8px; text-align: center;">
                        <a href="{{ route('login') }}" style="color: var(--brand-red);">Sign in</a> to comment
                    </div>
                @endauth

                <div id="commentsList">
                    @forelse($video->comments()->whereNull('parent_id')->with('user', 'replies.user')->latest()->get() as $comment)
                        @include('videos.partials.comment', ['comment' => $comment])
                    @empty
                        <p style="color: var(--text-secondary); text-align: center; padding: 20px;">No comments yet. Be the
                            first to comment!</p>
                    @endforelse
                </div>
            </div>

            <script>
                function submitComment(videoId) {
                    const body = document.getElementById('commentBody').value.trim();
                    if (!body) return;

                    fetch(`/videos/${videoId}/comments`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                body: body
                            })
                        })
                        .then(response => response.json())
                        .catch(error => {
                            console.error('Error:', error);
                            showToast('Failed to post comment: ' + error, 'error');
                        })
                        .then(data => {
                            if (data && data.success) {
                                document.getElementById('commentBody').value = '';
                                addCommentToList(data.comment);
                            } else {
                                showToast('Failed to post comment', 'error');
                            }
                        });
                }

                function addCommentToList(comment) {
                    const commentsList = document.getElementById('commentsList');
                    const commentHtml = `
                    <div class="comment-item" style="display: flex; gap: 12px; margin-bottom: 16px;" id="comment-${comment.id}">
                        <img src="${comment.user.avatar_url}" class="channel-avatar" style="width: 36px; height: 36px; flex-shrink: 0;" alt="${comment.user.name}">
                        <div style="flex: 1;">
                            <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 4px;">
                                <span style="font-weight: 600; font-size: 14px;">${comment.user.name}</span>
                                <span style="color: var(--text-secondary); font-size: 12px;">just now</span>
                            </div>
                            <div class="comment-body" style="font-size: 14px; line-height: 1.5; word-wrap: break-word;">
                                ${comment.body.replace(/@(\\w+)/g, '<span style="color: #3ea6ff; font-weight: 500;">@$1</span>')}
                            </div>
                            <div style="display: flex; gap: 12px; margin-top: 8px;">
                                <button onclick="toggleReplyForm(${comment.id})" style="background: none; border: none; color: var(--text-secondary); font-size: 12px; font-weight: 600; cursor: pointer; padding: 0;">
                                    Reply
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                    commentsList.insertAdjacentHTML('afterbegin', commentHtml);
                    const commentCount = document.querySelector('h3 span');
                    if (commentCount) {
                        const count = parseInt(commentCount.textContent.match(/\\((\\d+)\\)/)?.[2] || 0) + 1;
                        commentCount.textContent = `(${count})`;
                    }
                }

                function deleteComment(commentId) {
                    showConfirm('Are you sure you want to delete this comment?', function() {
                        fetch(`/comments/${commentId}`, {
                                method: 'DELETE',
                                headers: {
                                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                                }
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    document.getElementById('comment-' + commentId).remove();
                                    const commentCount = document.querySelector('h3 span');
                                    if (commentCount) {
                                        const count = parseInt(commentCount.textContent.match(/\\((\\d+)\\)/)?.[2] || 0) - 1;
                                        commentCount.textContent = `(${count})`;
                                    }
                                }
                            });
                    }, 'Delete');
                }

                document.addEventListener('DOMContentLoaded', function() {
                    const commentTexts = document.querySelectorAll('.comment-body');
                    commentTexts.forEach(text => {
                        const html = text.innerHTML.replace(/@(\w+)/g,
                            '<span style="color: #3ea6ff; font-weight: 500;">@$1</span>');
                        text.innerHTML = html;
                    });
                });

                function submitReply(videoId, parentId) {
                    const textarea = document.querySelector(`#replyForm${parentId} textarea`);
                    const body = textarea.value.trim();
                    if (!body) return;

                    fetch(`/videos/${videoId}/comments`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                body: body,
                                parent_id: parentId
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                location.reload();
                            }
                        });
                }
            </script>
        </div>

        <!-- Sidebar - Up Next / Recommendations -->
        <div class="yt-sidebar-container">
            @if ($playlist && $playlistVideos && $playlistVideos->count() > 0)
                <h3 style="font-size: 16px; font-weight: 500; margin-bottom: 12px;">
                    <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>
                <div class="recommended-videos-list">
                    @foreach ($playlistVideos as $index => $playlistVideo)
                        @if ($playlistVideo->id !== $video->id)
                            <div class="sidebar-video-card{{ $playlistVideo->id === $video->id ? ' current-video' : '' }}"
                                onclick="window.location.href='{{ route('videos.show', $playlistVideo->id) }}?playlist={{ $playlist->id }}'">
                                <div class="sidebar-thumb" style="position: relative;">
                                    @if ($playlistVideo->thumbnail)
                                        <img src="{{ asset('storage/thumbnails/' . $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>
                        @endif
                    @endforeach
                </div>
                @if ($playlist->canEdit(Auth::user()))
                    <a href="{{ route('playlists.show', $playlist->id) }}" class="yt-action-btn"
                        style="margin-top: 12px; display: inline-block;">
                        <i class="bi bi-pencil"></i> Edit Playlist
                    </a>
                @endif
            @else
                <h3 style="font-size: 16px; font-weight: 500; margin-bottom: 12px;">Up Next</h3>
                @if ($recommendedVideos && $recommendedVideos->count() > 0)
                    <div class="recommended-videos-list">
                        @foreach ($recommendedVideos as $recVideo)
                            <div class="sidebar-video-card"
                                onclick="window.location.href='{{ route('videos.show', $recVideo->id) }}'">
                                <div class="sidebar-thumb">
                                    @if ($recVideo->thumbnail)
                                        <img src="{{ asset('storage/thumbnails/' . $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">No recommendations available yet. Check back later!</div>
                @endif
            @endif
        </div>

    </div>

    <x-share-modal />
    @include('layouts.partials.edit-video-modal')

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

    <script>
        // Playlist navigation URLs
        const previousVideoUrl = @json($previousVideo ? route('videos.show', $previousVideo->id) . '?playlist=' . $playlist->id : null);
        const nextVideoUrl = @json($nextVideo ? route('videos.show', $nextVideo->id) . '?playlist=' . $playlist->id : null);

        // Autoplay management
        let autoplayEnabled = true;

        document.addEventListener('DOMContentLoaded', function() {
            var videoPlayer = document.getElementById('videoPlayer');
            var playlistControls = document.getElementById('playlistControls');
            var autoplayToggle = document.getElementById('autoplayToggle');

            if (videoPlayer) {
                videoPlayer.volume = 0.5;
                var playPromise = videoPlayer.play();
                if (playPromise !== undefined) {
                    playPromise.then(function() {
                        console.log('Video autoplayed');
                    }).catch(function(error) {
                        console.log('Autoplay blocked');
                    });
                }

                // Handle video ended - autoplay next
                if (nextVideoUrl) {
                    videoPlayer.addEventListener('ended', function() {
                        if (autoplayEnabled) {
                            console.log('Video ended, going to next...');
                            window.location.href = nextVideoUrl;
                        }
                    });
                }
            }

            // Show playlist controls on hover
            if (playlistControls) {
                const videoContainer = document.getElementById('videoContainer');
                videoContainer.addEventListener('mouseenter', function() {
                    playlistControls.classList.add('visible');
                });
                videoContainer.addEventListener('mouseleave', function() {
                    playlistControls.classList.remove('visible');
                });

                // Initially show for a few seconds
                setTimeout(function() {
                    playlistControls.classList.add('visible');
                }, 2000);
                setTimeout(function() {
                    playlistControls.classList.remove('visible');
                }, 6000);
            }

            // Autoplay toggle handler
            if (autoplayToggle) {
                autoplayToggle.addEventListener('change', function() {
                    autoplayEnabled = this.checked;
                    localStorage.setItem('playlistAutoplay', autoplayEnabled ? '1' : '0');
                });

                // Load saved preference
                const savedAutoplay = localStorage.getItem('playlistAutoplay');
                if (savedAutoplay !== null) {
                    autoplayEnabled = savedAutoplay === '1';
                    autoplayToggle.checked = autoplayEnabled;
                }
            }

            // Keyboard navigation
            document.addEventListener('keydown', function(e) {
                if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
                    return;
                }
                if (e.key === 'ArrowLeft') {
                    e.preventDefault();
                    goToPreviousVideo();
                } else if (e.key === 'ArrowRight') {
                    e.preventDefault();
                    goToNextVideo();
                }
            });
        });

        function goToPreviousVideo() {
            if (previousVideoUrl) {
                window.location.href = previousVideoUrl;
            }
        }

        function goToNextVideo() {
            if (nextVideoUrl) {
                window.location.href = nextVideoUrl;
            }
        }
    </script>
@endsection
