@extends('layouts.app')

@section('main_class', 'upload-page-only upload-page-responsive')

@section('title', 'Upload Video | ' . config('app.name'))

@section('extra_styles')
    <style>
        /* Hide custom header on mobile */
        .upload-page-header { display: none !important; }

        @media (max-width: 991px) {
            .upload-page-only .yt-header, .upload-page-only .yt-sidebar { display: block !important; }
            .upload-page-only .yt-main { display: block !important; margin-left: 0; padding-bottom: 80px; }
            .upload-page-only.upload-page-responsive { display: block; background: transparent; padding: 0; }
            .upload-page-only.upload-page-responsive .upload-page-standalone { max-width: 100%; border-radius: 0; box-shadow: none; background: var(--bg-primary); border: none; padding: 16px; }
            .upload-page-only.upload-page-responsive .upload-page-header { display: none !important; }
            .upload-page-only.upload-page-responsive .upload-page-body { padding: 0; background: transparent; }
            .upload-page-only.upload-page-responsive .form-input,
            .upload-page-only.upload-page-responsive .form-textarea { background: var(--bg-secondary); border-color: var(--border-color); color: var(--text-primary); }
            .upload-page-only.upload-page-responsive .form-label { color: var(--text-primary); }
            #dropzone { padding: 40px 16px; }
            .options-grid { flex-direction: column; }
            .option-item { min-width: 100%; }
        }

        @media (min-width: 992px) {
            .upload-page-only { min-height: auto; display: block; padding: 20px; background: #121212; }
        }

        .upload-page-standalone {
            background: #1a1a1a;
            border: none;
            border-radius: 0;
            box-shadow: none;
            overflow: hidden;
            width: 100%;
            max-width: 700px;
            margin: 0 auto;
            padding: 20px;
        }

        .upload-page-body { padding: 0; background: transparent; }
        
        /* Form Groups */
        .form-group { margin-bottom: 20px; }
        .form-label { display: block; margin-bottom: 8px; font-weight: 500; font-size: 14px; color: #e5e5e5; }
        .form-input, .form-textarea { width: 100%; background: #121212; border: 1px solid #333; border-radius: 8px; padding: 12px 16px; color: var(--text-primary); font-size: 14px; }
        .form-input:focus, .form-textarea:focus { outline: none; border-color: var(--brand-red); }
        .form-textarea { resize: vertical; min-height: 100px; }
        
        /* Dropzone */
        #dropzone {
            border: 2px dashed var(--border-color);
            border-radius: 12px;
            padding: 60px 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
            background: #151515;
        }
        #dropzone:hover, #dropzone.dragover { border-color: var(--brand-red); background: rgba(230, 30, 30, 0.05); }
        #dropzone .icon { font-size: 48px; color: var(--text-secondary); margin-bottom: 16px; }
        #dropzone p { color: var(--text-secondary); margin: 8px 0; }
        #dropzone .hint { font-size: 12px; color: var(--text-secondary); opacity: 0.7; }
        
        #video { display: none; }
        
        #file-info { display: none; }
        #file-info.active { display: flex; align-items: center; gap: 12px; padding: 16px; background: #1f1f1f; border-radius: 12px; border: 1px solid #333; }
        #file-info .file-icon { width: 56px; height: 56px; background: #333; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 24px; color: white; flex-shrink: 0; }
        #file-info .file-details { flex: 1; text-align: left; }
        #file-info .filename { color: #e5e5e5; font-weight: 500; font-size: 14px; margin: 0 0 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        #file-info .filesize { color: #888; font-size: 13px; margin: 0; }
        #file-info .btn-remove { width: 32px; height: 32px; border-radius: 50%; background: #333; border: none; color: #888; cursor: pointer; display: flex; align-items: center; justify-content: center; }
        
        /* Options Grid */
        .options-section { margin-bottom: 24px; }
        .options-label { font-size: 14px; font-weight: 500; color: #e5e5e5; margin-bottom: 12px; display: block; }
        .options-grid { display: flex; gap: 8px; flex-wrap: wrap; }
        .option-item { flex: 1; min-width: 100px; cursor: pointer; }
        .option-item input { display: none; }
        .option-content { display: flex; align-items: center; gap: 10px; padding: 12px 14px; background: #1a1a1a; border: 2px solid #333; border-radius: 10px; transition: all 0.2s; }
        .option-item:hover .option-content { border-color: #555; background: #1f1f1f; }
        .option-item.active .option-content { border-color: var(--brand-red); background: rgba(230, 30, 30, 0.1); }
        .option-content i { font-size: 18px; color: #666; width: 20px; text-align: center; }
        .option-item.active .option-content i { color: var(--brand-red); }
        .option-content span { font-size: 13px; color: #aaa; }
        .option-item.active .option-content span { color: #fff; }
        
        /* Two Column Layout */
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        
        /* Thumbnail Dropzone */
        #thumbnail-dropzone {
            border: 2px dashed #404040;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
            background: #151515;
            position: relative;
        }
        #thumbnail-dropzone:hover { border-color: var(--brand-red); }
        #thumbnail { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; }
        #thumbnail-default i { font-size: 28px; color: #666; margin-bottom: 6px; }
        #thumbnail-default p { color: #888; font-size: 13px; margin: 0; }
        #thumbnail-info { display: none; }
        #thumbnail-info.active { display: block; }
        #thumbnail-info img { max-width: 100%; max-height: 120px; border-radius: 8px; }
        
        /* Progress */
        #progress-container { display: none; margin: 20px 0; }
        #progress-container.active { display: block; }
        .progress-bar-fill { background: var(--brand-red); height: 4px; width: 0%; transition: width 0.3s; border-radius: 2px; }
        .progress-text { text-align: center; color: var(--text-secondary); font-size: 13px; margin-top: 8px; }
        
        /* Status */
        #status-message { display: none; padding: 12px 16px; border-radius: 8px; margin-bottom: 16px; font-size: 13px; }
        #status-message.success { display: block; background: rgba(34, 197, 94, 0.2); color: #4ade80; border: 1px solid rgba(34, 197, 94, 0.3); }
        #status-message.error { display: block; background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.3); }
        
        /* Submit Button */
        .btn-submit {
            width: 100%;
            justify-content: center;
            font-size: 15px;
            font-weight: 600;
        }
        .btn-submit:disabled { background: #555 !important; border-color: #555 !important; cursor: not-allowed; opacity: 1; }
        
        @media (max-width: 600px) {
            .form-row { grid-template-columns: 1fr; }
            .options-grid { flex-direction: column; }
            .option-item { min-width: 100%; }
        }
    </style>
@endsection

@section('content')
    <div class="upload-page-standalone">
        <div class="upload-page-body">
            <form id="upload-form" enctype="multipart/form-data">
                @csrf
                
                <!-- Video File Dropzone -->
                <div class="form-group">
                    <label class="form-label"><i class="bi bi-camera-video" id="file-label-icon"></i> <span id="file-label-text">Video or Music File *</span></label>
                    <div id="dropzone">
                        <input type="file" name="video" id="video" accept="video/*,audio/mpeg,audio/mp4,audio/aac,audio/flac,audio/wav,.mp3,.m4a,.aac,.flac,.wav" required>
                        <div id="dropzone-default">
                            <div class="icon"><i class="bi bi-cloud-arrow-up"></i></div>
                            <p>Click to select or drag file here</p>
                            <p class="hint">Video: MP4, MOV, AVI, WebM — Audio: MP3, M4A, AAC, FLAC</p>
                        </div>
                        <div id="file-info">
                            <div class="file-icon"><i class="bi bi-film" id="file-preview-icon"></i></div>
                            <div class="file-details">
                                <p class="filename" id="filename"></p>
                                <p class="filesize" id="filesize"></p>
                            </div>
                            <button type="button" class="btn-remove" onclick="removeVideo(event)"><i class="bi bi-x-lg"></i></button>
                        </div>
                    </div>
                </div>
                
                <!-- Title -->
                <div class="form-group">
                    <label class="form-label">Title *</label>
                    <input type="text" name="title" id="video-title" required class="form-input" placeholder="Enter video title">
                </div>
                
                <!-- Description -->
                <div class="form-group">
                    <label class="form-label">Description</label>
                    <textarea name="description" id="video-description" rows="4" class="form-textarea" placeholder="Tell viewers about your video (Markdown supported)"></textarea>
                </div>
                
                <!-- Thumbnail (video) -->
                <div class="form-group" id="thumbnail-section">
                    <label class="form-label"><i class="bi bi-image"></i> <span id="thumbnail-label-text">Thumbnail</span></label>
                    <div id="thumbnail-dropzone">
                        <input type="file" name="thumbnail" id="thumbnail" accept="image/*">
                        <div id="thumbnail-default">
                            <i class="bi bi-card-image"></i>
                            <p id="thumbnail-dropzone-hint">Click to select thumbnail (optional, max 20MB)</p>
                        </div>
                        <div id="thumbnail-info">
                            <div style="display:flex;align-items:center;gap:12px;padding:12px;background:#1f1f1f;border-radius:8px;border:1px solid #333;">
                                <div style="width:80px;height:48px;overflow:hidden;border-radius:6px;flex-shrink:0;">
                                    <img id="thumbnail-preview-img" src="" alt="Thumbnail preview" style="width:100%;height:100%;object-fit:cover;">
                                </div>
                                <div style="flex:1;text-align:left;min-width:0;">
                                    <p id="thumbnail-filename" style="color:#e5e5e5;font-weight:500;font-size:13px;margin:0 0 2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"></p>
                                    <p id="thumbnail-filesize" style="color:#888;font-size:12px;margin:0;"></p>
                                </div>
                                <button type="button" class="btn-remove" onclick="removeThumbnail(event)" style="flex-shrink:0;"><i class="bi bi-x-lg"></i></button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Slides dropzone (audio only) -->
                <div class="form-group" id="slides-section" style="display:none;">
                    <label class="form-label">
                        <i class="bi bi-images"></i> Slides <span style="color:var(--brand-red);">*</span>
                        <span style="font-weight:400;font-size:12px;color:var(--text-secondary);margin-left:6px;">Multiple images will crossfade while playing</span>
                    </label>
                    <div id="slides-dropzone" style="border:2px dashed var(--brand-red);border-radius:10px;padding:12px;cursor:pointer;text-align:center;min-height:72px;">
                        <input type="file" name="slides[]" id="slides-input" accept="image/*" multiple style="display:none;">
                        <div id="slides-default">
                            <i class="bi bi-images" style="font-size:28px;color:var(--text-secondary);"></i>
                            <p style="color:var(--text-secondary);font-size:13px;margin:4px 0 0;">Click or drag to add cover images</p>
                        </div>
                        <div id="slides-preview" style="display:none;">
                            <div id="slides-strip" style="display:flex;gap:8px;flex-wrap:wrap;justify-content:center;margin-bottom:8px;"></div>
                            <div style="display:flex;align-items:center;justify-content:space-between;padding:0 4px;">
                                <span id="slides-count" style="font-size:12px;color:var(--text-secondary);"></span>
                                <button type="button" onclick="removeSlides(event)" style="background:none;border:none;color:var(--text-secondary);cursor:pointer;font-size:12px;"><i class="bi bi-x-lg"></i> Clear</button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Video Type -->
                <div class="options-section">
                    <span class="options-label">Video Type</span>
                    <div class="options-grid" id="type-options">
                        <label class="option-item active" data-type="generic">
                            <input type="radio" name="type" value="generic" checked>
                            <div class="option-content">
                                <i class="bi bi-film"></i>
                                <span>Generic</span>
                            </div>
                        </label>
                        <label class="option-item" data-type="music">
                            <input type="radio" name="type" value="music">
                            <div class="option-content">
                                <i class="bi bi-music-note"></i>
                                <span>Music</span>
                            </div>
                        </label>
                        <label class="option-item" data-type="match">
                            <input type="radio" name="type" value="match">
                            <div class="option-content">
                                <i class="bi bi-trophy"></i>
                                <span>Match</span>
                            </div>
                        </label>
                    </div>
                </div>
                
                <!-- Privacy -->
                <div class="options-section">
                    <span class="options-label">Privacy</span>
                    <div class="options-grid" id="visibility-options">
                        <label class="option-item active" data-privacy="public">
                            <input type="radio" name="visibility" value="public" checked>
                            <div class="option-content">
                                <i class="bi bi-globe"></i>
                                <span>Public</span>
                            </div>
                        </label>
                        <label class="option-item" data-privacy="unlisted">
                            <input type="radio" name="visibility" value="unlisted">
                            <div class="option-content">
                                <i class="bi bi-link-45deg"></i>
                                <span>Unlisted</span>
                            </div>
                        </label>
                        <label class="option-item" data-privacy="private">
                            <input type="radio" name="visibility" value="private">
                            <div class="option-content">
                                <i class="bi bi-lock"></i>
                                <span>Private</span>
                            </div>
                        </label>
                    </div>
                </div>
                
                <!-- Hidden Shorts - Auto-detected -->
                <input type="hidden" name="is_shorts" id="is_shorts" value="0">

                <!-- Download Access -->
                <div class="form-group" style="margin-bottom: 16px;">
                    <label class="form-label">
                        <i class="bi bi-download"></i> Who can download?
                    </label>
                    <div class="options-grid" id="download-options">
                        <label class="option-item active" data-download="disabled">
                            <input type="radio" name="download_access" value="disabled" checked>
                            <div class="option-content">
                                <i class="bi bi-slash-circle"></i>
                                <span>Disabled</span>
                            </div>
                        </label>
                        <label class="option-item" data-download="everyone">
                            <input type="radio" name="download_access" value="everyone">
                            <div class="option-content">
                                <i class="bi bi-globe"></i>
                                <span>Everyone</span>
                            </div>
                        </label>
                        <label class="option-item" data-download="registered">
                            <input type="radio" name="download_access" value="registered">
                            <div class="option-content">
                                <i class="bi bi-person-check"></i>
                                <span>Members</span>
                            </div>
                        </label>
                        <label class="option-item" data-download="subscribers">
                            <input type="radio" name="download_access" value="subscribers">
                            <div class="option-content">
                                <i class="bi bi-star"></i>
                                <span>Subscribers</span>
                            </div>
                        </label>
                    </div>
                </div>

                <!-- Progress Bar -->
                <div id="progress-container">
                    <div class="progress-bar-wrapper">
                        <div id="progress-bar" class="progress-bar-fill"></div>
                    </div>
                    <p id="progress-text" class="progress-text">Uploading... 0%</p>
                </div>
                
                <!-- Status Message -->
                <div id="status-message"></div>
                
                <!-- Submit Button -->
                <button type="submit" id="submit-btn" class="action-btn action-btn-primary btn-submit">
                    <i class="bi bi-cloud-arrow-up-fill"></i> <span>Upload Video</span>
                </button>
            </form>
        </div>
    </div>
@endsection

@section('scripts')
    <script>
        const dropzone          = document.getElementById('dropzone');
        const fileInput         = document.getElementById('video');
        let thumbnailInput      = document.getElementById('thumbnail');
        const thumbnailDropzone = document.getElementById('thumbnail-dropzone');
        const slidesDropzone    = document.getElementById('slides-dropzone');
        let slidesInput         = document.getElementById('slides-input');
        let currentFile = null;

        // ── Helpers ──────────────────────────────────────────────
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024, sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        const AUDIO_EXTS = ['mp3', 'm4a', 'aac', 'flac', 'wav'];
        function isAudioFile(file) {
            const ext = file.name.split('.').pop().toLowerCase();
            return AUDIO_EXTS.includes(ext) || file.type.startsWith('audio/');
        }

        function setAudioMode(audio) {
            document.getElementById('file-label-icon').className = audio ? 'bi bi-music-note-beamed' : 'bi bi-camera-video';
            document.getElementById('file-label-text').textContent = audio ? 'Music File *' : 'Video or Music File *';

            // Toggle thumbnail vs slides section
            document.getElementById('thumbnail-section').style.display = audio ? 'none' : '';
            document.getElementById('slides-section').style.display    = audio ? '' : 'none';
            slidesDropzone.style.borderColor = audio ? 'var(--brand-red)' : '';

            if (audio) {
                document.querySelectorAll('#type-options .option-item').forEach(o => o.classList.remove('active'));
                const musicOpt = document.querySelector('#type-options .option-item[data-type="music"]');
                if (musicOpt) { musicOpt.classList.add('active'); musicOpt.querySelector('input').checked = true; }
            }

            document.getElementById('file-preview-icon').className = audio ? 'bi bi-music-note-beamed' : 'bi bi-film';
            document.getElementById('submit-btn').innerHTML =
                '<i class="bi bi-cloud-arrow-up-fill"></i> <span>' + (audio ? 'Upload Track' : 'Upload Video') + '</span>';
        }

        // ── Video/Audio File ─────────────────────────────────────
        fileInput.addEventListener('change', function() { handleFileSelect(this); });
        dropzone.addEventListener('click', function(e) {
            if (e.target.closest('.btn-remove')) return;
            fileInput.click();
        });
        dropzone.addEventListener('dragover', e => { e.preventDefault(); dropzone.classList.add('dragover'); });
        dropzone.addEventListener('dragleave', () => dropzone.classList.remove('dragover'));
        dropzone.addEventListener('drop', e => {
            e.preventDefault(); dropzone.classList.remove('dragover');
            if (e.dataTransfer.files.length) { fileInput.files = e.dataTransfer.files; handleFileSelect(fileInput); }
        });

        function handleFileSelect(input) {
            if (!input.files || !input.files[0]) return;
            const file = input.files[0];
            const maxSize = 512 * 1024 * 1024;
            const validVideoTypes = ['video/mp4','video/webm','video/ogg','video/quicktime','video/x-msvideo','video/x-flv','video/x-matroska'];
            const validVideoExts  = ['.mp4','.webm','.ogg','.mov','.avi','.wmv','.flv','.mkv'];
            const ext = '.' + file.name.split('.').pop().toLowerCase();
            const audio = isAudioFile(file);
            const validVideo = validVideoTypes.includes(file.type) || validVideoExts.includes(ext);

            if (!audio && !validVideo) {
                showError('Invalid format. Accepted: MP4, MOV, AVI, WebM, MKV, MP3, M4A, AAC, FLAC, WAV.');
                input.value = ''; return;
            }
            if (file.size > maxSize) {
                showError('File size exceeds 512MB limit.');
                input.value = ''; return;
            }

            currentFile = file;
            setAudioMode(audio);

            const titleWithoutExt = file.name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' ');
            document.getElementById('video-title').value = titleWithoutExt;
            document.getElementById('filename').textContent = file.name;
            document.getElementById('filesize').textContent = formatFileSize(file.size);
            document.getElementById('dropzone-default').style.display = 'none';
            document.getElementById('file-info').classList.add('active');
        }

        function removeVideo(e) {
            e.preventDefault(); e.stopPropagation();
            fileInput.value = ''; currentFile = null;
            document.getElementById('dropzone-default').style.display = 'block';
            document.getElementById('file-info').classList.remove('active');
            document.getElementById('video-title').value = '';
            setAudioMode(false);
        }

        // ── Thumbnail / Cover Art ─────────────────────────────────
        let _thumbClickTs = 0;
        thumbnailInput.addEventListener('change', function() { _thumbClickTs = 0; handleThumbnailSelect(this); });
        thumbnailDropzone.addEventListener('click', function(e) {
            if (e.target.closest('.btn-remove')) return;
            const now = Date.now();
            if (now - _thumbClickTs < 800) return;
            _thumbClickTs = now;
            if (typeof window.openCropperModal_thumb_create_mobile === 'function') {
                window.openCropperModal_thumb_create_mobile();
            } else {
                thumbnailInput.click();
            }
        });
        thumbnailDropzone.addEventListener('dragover', e => { e.preventDefault(); thumbnailDropzone.classList.add('dragover'); });
        thumbnailDropzone.addEventListener('dragleave', () => thumbnailDropzone.classList.remove('dragover'));
        thumbnailDropzone.addEventListener('drop', e => {
            e.preventDefault(); thumbnailDropzone.classList.remove('dragover');
            if (e.dataTransfer.files.length) {
                const droppedFile = e.dataTransfer.files[0];
                if (typeof window.tcPreload_thumb_create_mobile === 'function') {
                    window.tcPreload_thumb_create_mobile(droppedFile);
                    window.openCropperModal_thumb_create_mobile();
                } else {
                    thumbnailInput.files = e.dataTransfer.files;
                    handleThumbnailSelect(thumbnailInput);
                }
            }
        });

        function handleThumbnailSelect(input) {
            if (!input.files || !input.files[0]) return;
            const file = input.files[0];
            document.getElementById('thumbnail-filename').textContent = file.name;
            document.getElementById('thumbnail-filesize').textContent = formatFileSize(file.size);
            const reader = new FileReader();
            reader.onload = e => { document.getElementById('thumbnail-preview-img').src = e.target.result; };
            reader.readAsDataURL(file);
            document.getElementById('thumbnail-default').style.display = 'none';
            document.getElementById('thumbnail-info').classList.add('active');
        }

        function removeThumbnail(e) {
            e.preventDefault(); e.stopPropagation();
            const fresh = thumbnailInput.cloneNode(false);
            thumbnailInput.parentNode.replaceChild(fresh, thumbnailInput);
            thumbnailInput = fresh;
            thumbnailInput.addEventListener('change', function() { handleThumbnailSelect(this); });
            document.getElementById('thumbnail-default').style.display = 'block';
            document.getElementById('thumbnail-info').classList.remove('active');
        }

        // ── Slides dropzone (audio mode) ─────────────────────────
        slidesDropzone.addEventListener('click', e => { if (e.target.closest('button')) return; slidesInput.click(); });
        slidesInput.addEventListener('change', function() { handleSlidesSelect(this); });
        slidesDropzone.addEventListener('dragover', e => { e.preventDefault(); slidesDropzone.classList.add('dragover'); });
        slidesDropzone.addEventListener('dragleave', () => slidesDropzone.classList.remove('dragover'));
        slidesDropzone.addEventListener('drop', e => {
            e.preventDefault(); slidesDropzone.classList.remove('dragover');
            if (e.dataTransfer.files.length) { slidesInput.files = e.dataTransfer.files; handleSlidesSelect(slidesInput); }
        });

        function handleSlidesSelect(input) {
            if (!input.files || !input.files.length) return;
            const files = Array.from(input.files);
            const strip = document.getElementById('slides-strip');
            strip.innerHTML = '';
            files.forEach(f => {
                const reader = new FileReader();
                reader.onload = e => {
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.style.cssText = 'width:56px;height:56px;object-fit:cover;border-radius:6px;border:1px solid rgba(255,255,255,.15);';
                    strip.appendChild(img);
                };
                reader.readAsDataURL(f);
            });
            document.getElementById('slides-count').textContent =
                files.length === 1 ? '1 image — static cover' : files.length + ' images — will crossfade';
            document.getElementById('slides-default').style.display = 'none';
            document.getElementById('slides-preview').style.display = '';
            slidesDropzone.style.borderColor = '#22c55e';
        }

        function removeSlides(e) {
            e.preventDefault(); e.stopPropagation();
            const fresh = slidesInput.cloneNode(false);
            slidesInput.parentNode.replaceChild(fresh, slidesInput);
            slidesInput = fresh;
            slidesInput.addEventListener('change', function() { handleSlidesSelect(this); });
            document.getElementById('slides-default').style.display = 'block';
            document.getElementById('slides-preview').style.display = 'none';
            slidesDropzone.style.borderColor = 'var(--brand-red)';
        }

        // ── Option selectors ─────────────────────────────────────
        document.querySelectorAll('#type-options .option-item').forEach(item => {
            item.querySelector('input').addEventListener('change', () => {
                document.querySelectorAll('#type-options .option-item').forEach(o => o.classList.remove('active'));
                item.classList.add('active');
            });
        });
        document.querySelectorAll('#visibility-options .option-item').forEach(item => {
            item.querySelector('input').addEventListener('change', () => {
                document.querySelectorAll('#visibility-options .option-item').forEach(o => o.classList.remove('active'));
                item.classList.add('active');
            });
        });

        document.querySelectorAll('#download-options .option-item').forEach(item => {
            item.querySelector('input').addEventListener('change', () => {
                document.querySelectorAll('#download-options .option-item').forEach(o => o.classList.remove('active'));
                item.classList.add('active');
            });
        });

        // ── Form submission ───────────────────────────────────────
        document.getElementById('upload-form').addEventListener('submit', function(e) {
            e.preventDefault();

            if (!currentFile) { showError('Please select a video or audio file.'); return; }

            const title = document.getElementById('video-title').value.trim();
            if (!title) { showError('Please enter a title.'); return; }

            if (isAudioFile(currentFile)) {
                if (!slidesInput.files || !slidesInput.files.length) {
                    showError('At least one cover image is required for audio tracks.');
                    slidesDropzone.style.borderColor = 'var(--brand-red)';
                    return;
                }
            }

            const formData = new FormData(this);
            const xhr = new XMLHttpRequest();
            xhr.timeout = 1800000; // 30 min

            document.getElementById('progress-container').classList.add('active');
            document.getElementById('submit-btn').disabled = true;
            document.getElementById('submit-btn').innerHTML = '<i class="bi bi-arrow-repeat"></i> Uploading...';
            document.getElementById('status-message').className = '';

            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    const pct = Math.round((e.loaded / e.total) * 100);
                    document.getElementById('progress-bar').style.width = pct + '%';
                    document.getElementById('progress-text').textContent = 'Uploading... ' + pct + '%';
                }
            });

            xhr.addEventListener('load', function() {
                document.getElementById('progress-bar').style.width = '100%';
                document.getElementById('progress-text').textContent = 'Processing...';

                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        const res = JSON.parse(xhr.responseText);
                        if (res.success) {
                            document.getElementById('progress-text').textContent = 'Done! Redirecting...';
                            window.location.href = res.redirect;
                        } else {
                            showError(res.message || 'Upload failed.');
                        }
                    } catch(err) { showError('Invalid response from server.'); }
                } else {
                    try {
                        const res = JSON.parse(xhr.responseText);
                        if (res.errors) {
                            const msgs = Object.entries(res.errors).map(([f, errs]) => `<b>${f}:</b> ${errs.join(', ')}`).join('<br>');
                            showError(msgs);
                        } else {
                            showError(res.message || `Server error (${xhr.status})`);
                        }
                    } catch(err) { showError(`Upload failed (${xhr.status}).`); }
                }
            });

            xhr.addEventListener('error',   () => showError('Upload failed. Check your connection.'));
            xhr.addEventListener('timeout', () => showError('Upload timed out. The file may be too large.'));

            xhr.open('POST', '{{ route("videos.store") }}');
            xhr.setRequestHeader('X-CSRF-TOKEN', '{{ csrf_token() }}');
            xhr.send(formData);
        });

        function showError(message) {
            const status = document.getElementById('status-message');
            status.innerHTML = '<i class="bi bi-exclamation-circle-fill"></i> ' + message;
            status.className = 'error';
            document.getElementById('submit-btn').disabled = false;
            document.getElementById('submit-btn').innerHTML = '<i class="bi bi-cloud-arrow-up-fill"></i> <span>Upload Video</span>';
            document.getElementById('progress-container').classList.remove('active');
        }
    </script>
<x-image-cropper
    id="thumb_create_mobile"
    :width="448"
    :height="252"
    shape="square"
    target-input="thumbnail"
    preview-img="thumbnail-preview-img"
    output-width="1280"
    title="Crop Thumbnail"
/>
@endsection
