@extends('layouts.student')

@section('title', 'Watch Video')
@section('page-title', 'Watch Video')

@section('content')
    <div class="back-button-container" style="margin-bottom: 20px;">
        <a href="{{ route('student.videos.index') }}" class="btn btn-secondary">← Back to Videos</a>
    </div>
    
    <!-- Udemy-style Video Player Layout -->
    <div class="video-watch-container" style="display: flex; gap: 20px; align-items: flex-start;">
        <!-- Main Video Player Area (Left) -->
        <div class="video-main-area" style="flex: 1; min-width: 0;">
            <div class="card" style="margin-bottom: 20px;">
                <div class="card-header">
                    <h3 id="videoTitle">{{ $video->title }}</h3>
                </div>
                
                <div style="padding: 0;">
                    @if($video->mega_storage_link)
                        <!-- Mega.nz Embedded Video Player -->
                        <div class="video-iframe-wrapper" style="position: relative; width: 100%; padding-bottom: 56.25%; background: #000; border-radius: 0; overflow: hidden;">
                            <iframe 
                                id="videoPlayer"
                                src="{{ $megaEmbedUrl ?? '' }}" 
                                width="100%" 
                                height="100%" 
                                frameborder="0" 
                                allowfullscreen
                                style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none;"
                                allow="autoplay; fullscreen"
                                loading="lazy">
                            </iframe>
                        </div>
                    @else
                        <div style="text-align: center; padding: 60px; background: #1a1a1a;">
                            <i class="fas fa-video-slash" style="font-size: 64px; color: #404040; margin-bottom: 20px;"></i>
                            <p style="color: #888;">Video link not available yet.</p>
                        </div>
                    @endif
                </div>
                
                <!-- Video Information and Actions -->
                <div style="padding: 20px;">
                    <!-- Action Buttons -->
                    <div class="video-actions" style="display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 20px;">
                        @if($video->mega_storage_link)
                            <a href="{{ $video->mega_storage_link }}" target="_blank" class="btn btn-secondary">
                                <i class="fas fa-external-link-alt"></i> Open on Mega.nz
                            </a>
                            <a href="{{ $video->mega_storage_link }}" download class="btn btn-primary">
                                <i class="fas fa-download"></i> Download Video
                            </a>
                        @endif
                        @if($video->download_key)
                            <button type="button" onclick="copyToClipboard('{{ $video->download_key }}')" class="btn btn-secondary">
                                <i class="fas fa-copy"></i> Copy Download Key
                            </button>
                        @endif
                    </div>
                    
                    <!-- Video Details -->
                    <div style="border-top: 1px solid #404040; padding-top: 20px;">
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 20px;">
                            <div>
                                <strong style="color: #888; display: block; margin-bottom: 5px; font-size: 13px;">Course</strong>
                                <span style="color: #e0e0e0; font-size: 15px;">{{ $video->course->name }}</span>
                            </div>
                            @if($video->session_date)
                            <div>
                                <strong style="color: #888; display: block; margin-bottom: 5px; font-size: 13px;">Session Date</strong>
                                <span style="color: #e0e0e0; font-size: 15px;">{{ \Carbon\Carbon::parse($video->session_date)->format('M d, Y') }}</span>
                            </div>
                            @endif
                            @if($video->video_duration)
                            <div>
                                <strong style="color: #888; display: block; margin-bottom: 5px; font-size: 13px;">Duration</strong>
                                <span style="color: #e0e0e0; font-size: 15px;">{{ $video->video_duration }}</span>
                            </div>
                            @endif
                        </div>
                        
                        @if($video->description)
                        <div id="videoDescription">
                            <h4 style="color: #4a9eff; margin-bottom: 15px; font-size: 18px;">About this video</h4>
                            <p style="color: #e0e0e0; line-height: 1.6; white-space: pre-wrap;">{{ $video->description }}</p>
                        </div>
                        @endif
                        
                        @if($video->download_key)
                        <div style="margin-top: 20px; padding: 12px; background: #2d2d2d; border-radius: 5px; border-left: 3px solid #4a9eff;">
                            <p style="color: #888; font-size: 13px; margin-bottom: 5px;">
                                <strong style="color: #e0e0e0;">Download Key:</strong>
                            </p>
                            <code id="downloadKey" style="background: #1a1a1a; padding: 8px 12px; border-radius: 3px; color: #4a9eff; font-size: 13px; display: block; word-break: break-all;">{{ $video->download_key }}</code>
                        </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Video List Sidebar (Right) -->
        <div class="video-sidebar" style="width: 350px; flex-shrink: 0;">
            <div class="card" style="position: sticky; top: 80px;">
                <div class="card-header video-sidebar-header" style="padding: 15px 20px; cursor: pointer;" onclick="toggleVideoList()">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <h3 style="font-size: 16px; margin: 0;">
                                <i class="fas fa-list"></i> Course Videos
                            </h3>
                            <p style="color: #888; font-size: 12px; margin: 5px 0 0 0;">{{ $video->course->name }}</p>
                        </div>
                        <i class="fas fa-chevron-down video-list-toggle-icon" style="color: #888; font-size: 14px; transition: transform 0.3s;"></i>
                    </div>
                </div>
                
                <div class="video-list-content" style="max-height: calc(100vh - 200px); overflow-y: auto;">
                    @if($videosWithEmbeds && $videosWithEmbeds->count() > 0)
                        <div class="video-list" style="padding: 0;">
                            @foreach($videosWithEmbeds as $index => $v)
                                <div 
                                    class="video-list-item {{ $v->id == $video->id ? 'active' : '' }}" 
                                    data-video-id="{{ $v->id }}"
                                    data-video-title="{{ $v->title }}"
                                    data-video-embed="{{ $v->embed_url ?? '' }}"
                                    data-video-link="{{ $v->mega_storage_link }}"
                                    data-video-description="{{ $v->description ?? '' }}"
                                    data-video-session-date="{{ $v->session_date ? \Carbon\Carbon::parse($v->session_date)->format('M d, Y') : '' }}"
                                    data-video-duration="{{ $v->video_duration ?? '' }}"
                                    data-video-download-key="{{ $v->download_key ?? '' }}"
                                    onclick="switchVideo(this)"
                                    style="padding: 15px 20px; border-bottom: 1px solid #404040; cursor: pointer; transition: all 0.2s; display: flex; align-items: center; gap: 12px;"
                                    onmouseover="this.style.background='#1a1a1a'"
                                    onmouseout="if(!this.classList.contains('active')) this.style.background='transparent'">
                                    <div style="flex-shrink: 0; width: 40px; height: 40px; background: {{ $v->id == $video->id ? '#4a9eff' : '#404040' }}; border-radius: 5px; display: flex; align-items: center; justify-content: center; color: white; font-size: 14px;">
                                        @if($v->id == $video->id)
                                            <i class="fas fa-play"></i>
                                        @else
                                            {{ $index + 1 }}
                                        @endif
                                    </div>
                                    <div style="flex: 1; min-width: 0;">
                                        <h4 style="color: {{ $v->id == $video->id ? '#4a9eff' : '#e0e0e0' }}; font-size: 14px; margin: 0 0 5px 0; font-weight: {{ $v->id == $video->id ? '600' : '400' }}; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                                            {{ $v->title }}
                                        </h4>
                                        @if($v->session_date)
                                        <p style="color: #888; font-size: 11px; margin: 0;">
                                            <i class="fas fa-calendar"></i> {{ \Carbon\Carbon::parse($v->session_date)->format('M d, Y') }}
                                        </p>
                                        @endif
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @else
                        <div style="padding: 40px 20px; text-align: center;">
                            <p style="color: #888;">No other videos available.</p>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
    
    <style>
        /* Video Watch Container */
        .video-watch-container {
            display: flex;
            gap: 20px;
            align-items: flex-start;
        }
        
        .video-main-area {
            flex: 1;
            min-width: 0;
        }
        
        .video-sidebar {
            width: 350px;
            flex-shrink: 0;
        }
        
        /* Active Video Item */
        .video-list-item.active {
            background: #1a1a1a !important;
            border-left: 3px solid #4a9eff;
        }
        
        /* Scrollbar Styling */
        .video-sidebar .card > div::-webkit-scrollbar {
            width: 6px;
        }
        
        .video-sidebar .card > div::-webkit-scrollbar-track {
            background: #1a1a1a;
        }
        
        .video-sidebar .card > div::-webkit-scrollbar-thumb {
            background: #404040;
            border-radius: 3px;
        }
        
        .video-sidebar .card > div::-webkit-scrollbar-thumb:hover {
            background: #505050;
        }
        
        /* Responsive Styles */
        @media (max-width: 1024px) {
            .video-sidebar {
                width: 300px;
            }
        }
        
        @media (max-width: 768px) {
            .video-watch-container {
                flex-direction: column;
                gap: 15px;
            }
            
            .video-main-area {
                width: 100%;
            }
            
            .video-sidebar {
                width: 100%;
            }
            
            .video-sidebar .card {
                position: static !important;
            }
            
            .video-sidebar .card > div {
                max-height: 400px;
            }
            
            .video-sidebar-header {
                user-select: none;
            }
            
            .video-list-content {
                display: block;
            }
            
            .video-list-content.collapsed {
                display: none;
            }
            
            .video-list-toggle-icon {
                transform: rotate(0deg);
            }
            
            .video-list-toggle-icon.collapsed {
                transform: rotate(-90deg);
            }
            
            .video-actions {
                flex-direction: column;
                gap: 10px;
            }
            
            .video-actions .btn {
                width: 100%;
                margin-bottom: 0;
                min-height: 44px; /* iOS touch target minimum */
                display: flex;
                align-items: center;
                justify-content: center;
            }
            
            .card-header h3 {
                font-size: 18px !important;
            }
            
            .video-main-area .card > div:last-child {
                padding: 15px !important;
            }
            
            .video-main-area .card > div:last-child > div:first-child {
                margin-bottom: 15px !important;
            }
        }
        
        @media (max-width: 480px) {
            .video-watch-container {
                gap: 10px;
            }
            
            .video-main-area .card {
                margin-bottom: 15px;
            }
            
            .card-header {
                padding: 15px !important;
            }
            
            .card-header h3 {
                font-size: 16px !important;
                line-height: 1.4;
            }
            
            .video-main-area .card > div:last-child {
                padding: 15px !important;
            }
            
            .video-iframe-wrapper {
                padding-bottom: 56.25% !important;
            }
            
            .video-list-item {
                padding: 12px 15px !important;
                gap: 10px !important;
                min-height: 50px; /* Ensure touch target is large enough */
            }
            
            .video-list-item > div:first-child {
                width: 35px !important;
                height: 35px !important;
                font-size: 12px !important;
            }
            
            .video-list-item h4 {
                font-size: 13px !important;
                line-height: 1.4;
            }
            
            .video-list-item p {
                font-size: 10px !important;
            }
            
            .video-sidebar .card-header {
                padding: 12px 15px !important;
            }
            
            .video-sidebar .card-header h3 {
                font-size: 15px !important;
            }
            
            .video-sidebar .card-header p {
                font-size: 11px !important;
            }
            
            .video-sidebar .card > div {
                max-height: 350px;
            }
            
            .video-sidebar-header {
                padding: 12px 15px !important;
            }
            
            .video-list-content {
                max-height: 300px !important;
            }
            
            /* Video Info Grid */
            .video-main-area .card > div:last-child > div:last-child > div:first-child {
                grid-template-columns: 1fr !important;
                gap: 15px !important;
            }
            
            .video-main-area .card > div:last-child > div:last-child > div:first-child > div {
                margin-bottom: 0 !important;
            }
            
            /* Back button */
            .content-area > div:first-child {
                margin-bottom: 15px !important;
            }
            
            .content-area > div:first-child a {
                padding: 8px 15px !important;
                font-size: 13px !important;
            }
            
            /* Description */
            #videoDescription h4 {
                font-size: 16px !important;
            }
            
            #videoDescription p {
                font-size: 14px !important;
            }
            
            /* Download key section */
            .video-main-area .card > div:last-child > div:last-child > div:last-child {
                margin-top: 15px !important;
                padding: 10px !important;
            }
            
            .video-main-area .card > div:last-child > div:last-child > div:last-child p {
                font-size: 12px !important;
            }
            
            .video-main-area .card > div:last-child > div:last-child > div:last-child code {
                font-size: 12px !important;
                padding: 6px 10px !important;
            }
        }
        
        @media (max-width: 360px) {
            .video-list-item {
                padding: 10px 12px !important;
            }
            
            .video-list-item > div:first-child {
                width: 30px !important;
                height: 30px !important;
                font-size: 11px !important;
            }
            
            .video-list-item h4 {
                font-size: 12px !important;
            }
            
            .card-header h3 {
                font-size: 15px !important;
            }
        }
    </style>
    
    <script>
        // Current video ID
        const currentVideoId = {{ $video->id }};
        
        // Toggle video list on mobile
        function toggleVideoList() {
            if (window.innerWidth <= 768) {
                const content = document.querySelector('.video-list-content');
                const icon = document.querySelector('.video-list-toggle-icon');
                if (content && icon) {
                    content.classList.toggle('collapsed');
                    icon.classList.toggle('collapsed');
                }
            }
        }
        
        // Ensure video list is visible on desktop
        window.addEventListener('resize', function() {
            if (window.innerWidth > 768) {
                const content = document.querySelector('.video-list-content');
                const icon = document.querySelector('.video-list-toggle-icon');
                if (content && icon) {
                    content.classList.remove('collapsed');
                    icon.classList.remove('collapsed');
                }
            }
        });
        
        // Switch video function
        function switchVideo(element) {
            const videoId = element.dataset.videoId;
            const videoTitle = element.dataset.videoTitle;
            const videoEmbed = element.dataset.videoEmbed;
            const videoLink = element.dataset.videoLink;
            const videoDescription = element.dataset.videoDescription || '';
            const videoSessionDate = element.dataset.videoSessionDate || '';
            const videoDuration = element.dataset.videoDuration || '';
            const videoDownloadKey = element.dataset.videoDownloadKey || '';
            
            // Update video player
            const iframe = document.getElementById('videoPlayer');
            if (videoEmbed) {
                iframe.src = videoEmbed;
            } else {
                // Fallback: show message
                iframe.style.display = 'none';
                const wrapper = iframe.parentElement;
                wrapper.innerHTML = `
                    <div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; flex-direction: column; padding: 20px; text-align: center;">
                        <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #ffc107; margin-bottom: 15px;"></i>
                        <p style="color: #888; margin-bottom: 15px;">Unable to load embedded video player.</p>
                        <a href="${videoLink}" target="_blank" class="btn btn-primary" style="background: #4a9eff; color: white; padding: 10px 20px; border-radius: 5px; text-decoration: none;">
                            <i class="fas fa-external-link-alt"></i> Open Video on Mega
                        </a>
                    </div>
                `;
            }
            
            // Update video title
            document.getElementById('videoTitle').textContent = videoTitle;
            
            // Update video description
            const descDiv = document.getElementById('videoDescription');
            if (videoDescription) {
                if (descDiv) {
                    descDiv.innerHTML = `
                        <h4 style="color: #4a9eff; margin-bottom: 15px; font-size: 18px;">About this video</h4>
                        <p style="color: #e0e0e0; line-height: 1.6; white-space: pre-wrap;">${videoDescription}</p>
                    `;
                } else {
                    const infoDiv = document.querySelector('.video-main-area .card > div:last-child');
                    const newDesc = document.createElement('div');
                    newDesc.id = 'videoDescription';
                    newDesc.innerHTML = `
                        <h4 style="color: #4a9eff; margin-bottom: 15px; font-size: 18px;">About this video</h4>
                        <p style="color: #e0e0e0; line-height: 1.6; white-space: pre-wrap;">${videoDescription}</p>
                    `;
                    infoDiv.querySelector('.video-actions').parentElement.insertBefore(newDesc, infoDiv.querySelector('.video-actions').nextSibling);
                }
            } else if (descDiv) {
                descDiv.remove();
            }
            
            // Update download key
            const downloadKeyDiv = document.querySelector('#downloadKey')?.parentElement?.parentElement;
            if (videoDownloadKey) {
                if (downloadKeyDiv) {
                    downloadKeyDiv.querySelector('#downloadKey').textContent = videoDownloadKey;
                } else {
                    const actionsDiv = document.querySelector('.video-actions').parentElement;
                    const newKeyDiv = document.createElement('div');
                    newKeyDiv.style.cssText = 'margin-top: 20px; padding: 12px; background: #2d2d2d; border-radius: 5px; border-left: 3px solid #4a9eff;';
                    newKeyDiv.innerHTML = `
                        <p style="color: #888; font-size: 13px; margin-bottom: 5px;">
                            <strong style="color: #e0e0e0;">Download Key:</strong>
                        </p>
                        <code id="downloadKey" style="background: #1a1a1a; padding: 8px 12px; border-radius: 3px; color: #4a9eff; font-size: 13px; display: block; word-break: break-all;">${videoDownloadKey}</code>
                    `;
                    actionsDiv.appendChild(newKeyDiv);
                }
            } else if (downloadKeyDiv) {
                downloadKeyDiv.remove();
            }
            
            // Update action buttons
            const actionsDiv = document.querySelector('.video-actions');
            actionsDiv.innerHTML = `
                ${videoLink ? `
                    <a href="${videoLink}" target="_blank" class="btn btn-secondary">
                        <i class="fas fa-external-link-alt"></i> Open on Mega.nz
                    </a>
                    <a href="${videoLink}" download class="btn btn-primary">
                        <i class="fas fa-download"></i> Download Video
                    </a>
                ` : ''}
                ${videoDownloadKey ? `
                    <button type="button" onclick="copyToClipboard('${videoDownloadKey}')" class="btn btn-secondary">
                        <i class="fas fa-copy"></i> Copy Download Key
                    </button>
                ` : ''}
            `;
            
            // Update active state in sidebar
            document.querySelectorAll('.video-list-item').forEach(item => {
                item.classList.remove('active');
                item.style.background = 'transparent';
                const iconDiv = item.querySelector('div:first-child');
                const index = Array.from(item.parentElement.children).indexOf(item);
                iconDiv.innerHTML = index + 1;
                iconDiv.style.background = '#404040';
                item.querySelector('h4').style.color = '#e0e0e0';
                item.querySelector('h4').style.fontWeight = '400';
            });
            
            element.classList.add('active');
            element.style.background = '#1a1a1a';
            const activeIconDiv = element.querySelector('div:first-child');
            activeIconDiv.innerHTML = '<i class="fas fa-play"></i>';
            activeIconDiv.style.background = '#4a9eff';
            element.querySelector('h4').style.color = '#4a9eff';
            element.querySelector('h4').style.fontWeight = '600';
            
            // Update URL without page reload
            const newUrl = window.location.pathname.replace(/\/\d+$/, '/' + videoId);
            window.history.pushState({videoId: videoId}, '', newUrl);
            
            // Scroll to top of video player on mobile
            if (window.innerWidth <= 768) {
                document.querySelector('.video-main-area').scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        }
        
        // Copy download key to clipboard
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(function() {
                const btn = event.target.closest('button');
                const originalText = btn.innerHTML;
                btn.innerHTML = '<i class="fas fa-check"></i> Copied!';
                btn.style.background = '#28a745';
                
                setTimeout(function() {
                    btn.innerHTML = originalText;
                    btn.style.background = '';
                }, 2000);
            }).catch(function(err) {
                const textArea = document.createElement('textarea');
                textArea.value = text;
                textArea.style.position = 'fixed';
                textArea.style.opacity = '0';
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                
                const btn = event.target.closest('button');
                const originalText = btn.innerHTML;
                btn.innerHTML = '<i class="fas fa-check"></i> Copied!';
                btn.style.background = '#28a745';
                
                setTimeout(function() {
                    btn.innerHTML = originalText;
                    btn.style.background = '';
                }, 2000);
            });
        }
        
        // Handle browser back/forward buttons
        window.addEventListener('popstate', function(event) {
            // Reload page to show correct video
            window.location.reload();
        });
    </script>
@endsection
