const ThreeDModule = {
    screenShareCount: 0,
    modal: null,
    subjectSelector: null,
    lessonsList: null,
    modelViewer: null,
    canvas2d: null,
    ctx2d: null,
    placeholder: null,
    mediaTitle: null,
    mediaBadge: null,
    animationInterval: null,
    
    init: function() {
        this.modal = document.getElementById('modal-3d');
        this.subjectSelector = document.getElementById('subject-selector');
        this.lessonsList = document.getElementById('lessons-list');
        this.modelViewer = document.getElementById('real-3d-viewer');
        this.canvas2d = document.getElementById('interactive-2d-canvas');
        this.placeholder = document.getElementById('theater-placeholder');
        this.mediaTitle = document.getElementById('current-media-title');
        this.mediaBadge = document.getElementById('media-type-badge');
        this.setupUploadForm();
        
        if(this.canvas2d) this.ctx2d = this.canvas2d.getContext('2d');

        const btnOpen = document.getElementById('btn-3d');
        const btnClose = document.getElementById('close-3d');

        if(btnOpen) btnOpen.onclick = () => this.openModal();
        if(btnClose) btnClose.onclick = () => this.closeModal();

        if(this.subjectSelector) {
            this.subjectSelector.onchange = () => this.loadLessonsFromServer();
            this.loadLessonsFromServer(); 
        }
        
        const btnScreenShare = document.getElementById('btn-screen-share');
        if(btnScreenShare) btnScreenShare.onclick = () => this.startScreenShare();
    },

    startScreenShare: async function() {
        try {
            const stream = await navigator.mediaDevices.getDisplayMedia({ 
                video: { width: { ideal: 1920, max: 3840 }, height: { ideal: 1080, max: 2160 }, frameRate: { ideal: 30, max: 60 } }, 
                audio: true 
            });
            this.screenShareCount++; 
            const screenLesson = { type: 'SCREEN', title: `بث شاشة (${this.screenShareCount})`, stream: stream };
            this.closeModal(); 
            this.spawnFloatingMedia(screenLesson); 
        } catch (err) {
            console.log("تم إلغاء مشاركة الشاشة من قبل المدرس.");
        }
    },
    
    openModal: function() { this.modal.classList.add('open'); },
    closeModal: function() { this.modal.classList.remove('open'); this.stop2DAnimation(); this.stopAllMedia(); },

    createDeleteButton: function(lesson, btnElement) {
        const del = document.createElement('span');
        del.innerHTML = "🗑️";
        del.title = "حذف نهائياً";
        del.style.cssText = "background: #ef4444; color: white; padding: 4px 8px; border-radius: 4px; cursor: pointer; margin-left: 10px; font-size: 12px; transition: 0.2s;";
        
        del.onmouseover = () => del.style.background = "#dc2626";
        del.onmouseout = () => del.style.background = "#ef4444";

        del.onclick = (e) => {
            e.stopPropagation(); 
            if (confirm(`هل أنت متأكد من حذف (${lesson.title}) نهائياً؟`)) {
                fetch('delete_media.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ media_id: lesson.id })
                })
                .then(res => res.text())
                .then(text => {
                    try {
                        const result = JSON.parse(text);
                        if (result.success) {
                            btnElement.remove();
                        } else {
                            alert("رسالة من السيرفر: " + result.error);
                        }
                    } catch (parseError) {
                        alert("عذراً، السيرفر أرجع خطأً برمجياً بدلاً من الجواب:\n\n" + text);
                    }
                })
                .catch(err => alert("الرابط delete_media.php غير موجود إطلاقاً، أو أن هناك مشكلة بالإنترنت."));
            }
        };
        return del;
    },

    loadLessonsFromServer: function() {
        this.lessonsList.innerHTML = "<p style='color:#6b1024;font-size:12px;padding:10px;'>جاري تحميل الوسائل...</p>";
        const subjectKey = this.subjectSelector.value;

        fetch(`fetch_media.php?subject=${subjectKey}`)
            .then(response => response.json())
            .then(data => {
                this.lessonsList.innerHTML = "";
                
                if (data.error || data.length === 0) {
                    this.lessonsList.innerHTML = "<p style='color:gray;font-size:12px;padding:10px;'>لا توجد وسائل مرفوعة لهذه المادة حتى الآن.</p>";
                    this.addDemoButtons(subjectKey);
                    return;
                }

                data.forEach(lesson => {
                    const btn = document.createElement('button');
                    btn.className = "lesson-item-btn";
                    
                    btn.style.display = "flex";
                    btn.style.justifyContent = "space-between";
                    btn.style.alignItems = "center";
                    btn.style.width = "100%";
                    
                    let icon = "🔮 ";
                    if(lesson.type === '3D') icon = "📦 ";
                    else if(lesson.type === 'YOUTUBE') icon = "▶️ ";
                    else if(lesson.type === 'VIDEO') icon = "🎬 ";
                    else if(lesson.type === 'IMAGE') icon = "🖼️ ";
                    else if(lesson.type === 'PDF') icon = "📄 ";
                    
                    const titleSpan = document.createElement('span');
                    titleSpan.innerText = icon + lesson.title;
                    btn.appendChild(titleSpan);
                    
                    const deleteBtn = this.createDeleteButton(lesson, btn);
                    btn.appendChild(deleteBtn);
                    
                    btn.onclick = (e) => {
                        if (!deleteBtn.contains(e.target)) {
                            this.playMedia(lesson, btn);
                        }
                    };
                    
                    this.lessonsList.appendChild(btn);
                });
            })
            .catch(err => {
                this.lessonsList.innerHTML = "<p style='color:red;font-size:12px;padding:10px;'>خطأ في الاتصال.</p>";
            });
    },

    addDemoButtons: function(subjectKey) {
        let demoLessons = [];
        if(subjectKey === 'arabic') demoLessons = [{ id: "grammar_tree", title: "شجرة النحو التفاعلية", type: "2D" }];
        else if(subjectKey === 'math') demoLessons = [{ id: "trig_circle", title: "موجات الجيب (Sin)", type: "2D" }];
        else if(subjectKey === 'biology') demoLessons = [{ id: "dna_helix", title: "شريط الـ DNA", type: "2D" }];
        
        demoLessons.forEach(lesson => {
            const btn = document.createElement('button');
            btn.className = "lesson-item-btn";
            btn.innerText = "🔮 (تجريبي) " + lesson.title;
            btn.onclick = (e) => this.playMedia(lesson, e.target);
            this.lessonsList.appendChild(btn);
        });
    },

    stopAllMedia: function() {
        this.stop2DAnimation();
        this.modelViewer.style.display = "none";
        this.canvas2d.style.display = "none";
        
        const imgViewer = document.getElementById('image-viewer');
        const videoViewer = document.getElementById('video-viewer');
        const pdfViewer = document.getElementById('pdf-viewer');

        if(imgViewer) { imgViewer.style.display = "none"; imgViewer.src = ""; }
        if(videoViewer) { videoViewer.style.display = "none"; videoViewer.pause(); videoViewer.src = ""; }
        if(pdfViewer) { pdfViewer.style.display = "none"; pdfViewer.src = ""; }
    },

    getYouTubeEmbedUrl: function(url) {
        let videoId = "";
        if (url.includes("v=")) {
            videoId = url.split("v=")[1].split("&")[0];
        } else if (url.includes("youtu.be/")) {
            videoId = url.split("youtu.be/")[1].split("?")[0];
        }
        return videoId ? `https://www.youtube.com/embed/${videoId}?autoplay=1&rel=0` : url;
    },

    playMedia: function(lesson, clickedButton) {
        this.closeModal();
        this.spawnFloatingMedia(lesson);
        document.querySelectorAll('.lesson-item-btn').forEach(b => b.classList.remove('active'));
        if(clickedButton) clickedButton.classList.add('active');
    },

    // 🚀 دالة الفتح مع المزامنة العالية الدقة (High Precision Sync)
    spawnFloatingMedia: function(lesson) {
        const uniqueId = 'media-' + Date.now(); 

        const wrapper = document.createElement('div');
        wrapper.id = uniqueId;
        wrapper.className = 'draggable-video-wrapper';
        
        wrapper.style.cssText = 'position: absolute; top: 15%; left: 20%; width: 50%; height: 60%; z-index: 890; background: #fff; border: 2px solid #6b1024; border-radius: 8px; overflow: hidden; resize: both; box-shadow: 0 5px 15px rgba(0,0,0,0.3); flex-direction: column; display: flex; pointer-events: auto;';

        wrapper.innerHTML = `
            <div id="drag-${uniqueId}" style="background: #6b1024; color: white; padding: 8px 15px; display: flex; justify-content: space-between; align-items: center; font-size: 14px; cursor: grab; user-select: none;">
                <span><i class="fas fa-cube"></i> ${lesson.title || 'وسيلة تعليمية'}</span>
                <button id="close-btn-${uniqueId}" style="background: none; border: none; color: white; cursor: pointer; font-size: 16px;"><i class="fas fa-times"></i></button>
            </div>
            <div id="content-${uniqueId}" style="width: 100%; flex: 1; position: relative; background: #f0f2f5;"></div>
        `;

        const boardWrapper = document.getElementById('board-wrapper');
        const whiteboard = document.getElementById('whiteboard');
        if (boardWrapper && whiteboard) boardWrapper.insertBefore(wrapper, whiteboard);
        else document.body.appendChild(wrapper);

        document.getElementById(`close-btn-${uniqueId}`).onclick = () => {
            wrapper.remove();
            const tid = new URLSearchParams(window.location.search).get('tid');
            if (tid) fetch(`../zoom_api/media_sync_api.php?action=send_command&tid=${tid}`, { method: 'POST', body: JSON.stringify({ action: 'CLEAR' }) }).catch(e=>{});
        };

        const content = document.getElementById(`content-${uniqueId}`);
        if (lesson.type === "3D" || (lesson.url && lesson.url.toLowerCase().endsWith('.glb'))) {
            content.innerHTML = `<model-viewer src="${lesson.url}" camera-controls auto-rotate shadow-intensity="1" style="width:100%; height:100%; outline:none; background: transparent;"></model-viewer>`;
        } else if (lesson.type === "YOUTUBE") {
            content.innerHTML = `<iframe src="${this.getYouTubeEmbedUrl(lesson.url)}" allow="autoplay; encrypted-media" allowfullscreen style="width:100%; height:100%; border:none; border-radius: 10px;"></iframe>`;
        } else if (lesson.type === "IMAGE") {
            content.innerHTML = `<img src="${lesson.url}" style="object-fit: contain; width:100%; height:100%; background: transparent;">`;
        } else if (lesson.type === "VIDEO") {
            content.innerHTML = `<video src="${lesson.url}" controls style="width:100%; height:100%; border-radius: 10px; background: #000;"></video>`;
        } else if (lesson.type === "PDF") {
            content.innerHTML = `<iframe src="${lesson.url}" style="width:100%; height:100%; border:none; border-radius: 10px; background: white;"></iframe>`;
        } else if (lesson.type === "SCREEN") {
            const videoEl = document.createElement('video');
            videoEl.style.cssText = "width:100%; height:100%; background:#000; object-fit:contain; border-radius: 10px;";
            videoEl.autoplay = true;
            videoEl.srcObject = lesson.stream;
            content.appendChild(videoEl);
            lesson.stream.getVideoTracks()[0].onended = () => document.getElementById(`close-btn-${uniqueId}`).click();
        }

        let canSyncMove = false;
        setTimeout(() => { canSyncMove = true; }, 2000);

        // 🚀 دالة المزامنة بدقة عالية جداً (4 أرقام عشرية للتطابق التام)
        const triggerSync = () => {
            if(!canSyncMove) return;
            const parent = document.getElementById('board-wrapper') || document.body;
            
            const exactLeft = ((wrapper.offsetLeft / parent.offsetWidth) * 100).toFixed(4);
            const exactTop = ((wrapper.offsetTop / parent.offsetHeight) * 100).toFixed(4);
            const exactWidth = ((wrapper.offsetWidth / parent.offsetWidth) * 100).toFixed(4);
            const exactHeight = ((wrapper.offsetHeight / parent.offsetHeight) * 100).toFixed(4);

            const tid = new URLSearchParams(window.location.search).get('tid');
            if (tid) {
                fetch(`../zoom_api/media_sync_api.php?action=send_command&tid=${tid}`, { 
                    method: 'POST', headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ action: 'MOVE_MEDIA', data: { id: uniqueId, left: exactLeft + '%', top: exactTop + '%', width: exactWidth + '%', height: exactHeight + '%' } }) 
                }).catch(e=>{});
            }
        };

        // 🚀 المزامنة الحية أثناء السحب (ليرى الطالب الحركة بسلاسة)
        let syncThrottle = null;
        const throttledSync = () => {
            if(!syncThrottle) {
                triggerSync();
                syncThrottle = setTimeout(() => { syncThrottle = null; }, 150); 
            }
        };

        const header = document.getElementById(`drag-${uniqueId}`);
        let isDragging = false, startX, startY, initialLeft, initialTop;
        header.onmousedown = (e) => {
            isDragging = true; header.style.cursor = 'grabbing';
            startX = e.clientX; startY = e.clientY;
            initialLeft = wrapper.offsetLeft; initialTop = wrapper.offsetTop;
            
            const blocker = document.createElement('div');
            blocker.style.cssText = 'position:absolute; top:0; left:0; width:100%; height:100%; z-index:10;';
            content.appendChild(blocker);

            document.onmousemove = (moveEvent) => {
                if (!isDragging) return;
                wrapper.style.left = (initialLeft + moveEvent.clientX - startX) + 'px';
                wrapper.style.top = (initialTop + moveEvent.clientY - startY) + 'px';
                throttledSync(); // إرسال الحركة للطالب أثناء سحب الماوس
            };
            document.onmouseup = () => {
                isDragging = false; header.style.cursor = 'grab';
                document.onmousemove = null; document.onmouseup = null;
                if(content.contains(blocker)) content.removeChild(blocker);
                clearTimeout(syncThrottle); syncThrottle = null;
                triggerSync(); // المزامنة النهائية عند إفلات الماوس
            };
        };

        // المزامنة فوراً عند التكبير أو التصغير
        new ResizeObserver(() => throttledSync()).observe(wrapper);

        // 🚀 دقة عالية في مزامنة المجسم 3D من الداخل
        if (lesson.type === "3D" || (lesson.url && lesson.url.toLowerCase().endsWith('.glb'))) {
            setTimeout(() => {
                const mv = document.querySelector(`#content-${uniqueId} model-viewer`);
                let cameraSyncTimeout;
                if (mv) {
                    mv.addEventListener('camera-change', (e) => {
                        if (!canSyncMove) return;
                        // نرسل الحركة فقط إذا كان المدرس هو من يحرك الماوس (لتجنب التضارب)
                        if (e.detail.source === 'user-interaction') {
                            clearTimeout(cameraSyncTimeout);
                            cameraSyncTimeout = setTimeout(() => {
                                const tid = new URLSearchParams(window.location.search).get('tid');
                                if (tid) {
                                    fetch(`../zoom_api/media_sync_api.php?action=send_command&tid=${tid}`, { 
                                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                                        body: JSON.stringify({ action: 'SYNC_3D', data: { id: uniqueId, orbit: mv.getCameraOrbit(), target: mv.getCameraTarget() } }) 
                                    }).catch(err=>{});
                                }
                            }, 150);
                        }
                    });
                }
            }, 1000);
        }

        if(lesson.type !== "SCREEN") {
            const tid = new URLSearchParams(window.location.search).get('tid');
            if (tid) {
                const payload = { action: 'LOAD_FILE', data: { id: uniqueId, url: lesson.url, title: lesson.title, type: lesson.type } };
                fetch(`../zoom_api/media_sync_api.php?action=send_command&tid=${tid}`, { 
                    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) 
                }).catch(e => console.log(e));
            }
        }
    },

    setupUploadForm: function() {
        const uploadBtn = document.getElementById('btn-toggle-upload');
        const uploadForm = document.getElementById('upload-media-form');
        const typeSelect = document.getElementById('upload-type');
        const fileInput = document.getElementById('upload-file');
        const urlInput = document.getElementById('upload-url');
        
        if(uploadBtn && uploadForm && typeSelect) {
            typeSelect.onchange = () => {
                if (typeSelect.value === 'YOUTUBE') {
                    fileInput.style.display = 'none';
                    fileInput.removeAttribute('required');
                    urlInput.style.display = 'block';
                    urlInput.setAttribute('required', 'true');
                } else {
                    urlInput.style.display = 'none';
                    urlInput.removeAttribute('required');
                    fileInput.style.display = 'block';
                    fileInput.setAttribute('required', 'true');
                }
            };

            uploadBtn.onclick = () => {
                uploadForm.style.display = uploadForm.style.display === 'none' ? 'flex' : 'none';
            };
            
            uploadForm.onsubmit = (e) => {
                e.preventDefault(); 
                
                const title = document.getElementById('upload-title').value;
                const type = typeSelect.value;
                const statusDiv = document.getElementById('upload-status');
                const currentSubject = this.subjectSelector.value;
                
                const formData = new FormData();
                formData.append('subject', currentSubject);
                formData.append('title', title);
                formData.append('type', type);
                
                if (type === 'YOUTUBE') {
                    formData.append('url', urlInput.value);
                } else {
                    if(fileInput.files.length === 0) return;
                    formData.append('file', fileInput.files[0]);
                }
                
                statusDiv.innerHTML = "<span style='color:#2980b9;'>⏳ جاري الرفع... الرجاء الانتظار</span>";
                document.getElementById('btn-submit-upload').disabled = true;
                
                fetch('upload_media.php', { method: 'POST', body: formData })
                .then(res => res.json())
                .then(data => {
                    document.getElementById('btn-submit-upload').disabled = false;
                    if(data.success) {
                        statusDiv.innerHTML = "<span style='color:#27ae60;'>✅ تم الحفظ بنجاح!</span>";
                        uploadForm.reset();
                        uploadForm.style.display = 'none';
                        urlInput.style.display = 'none'; fileInput.style.display = 'block';
                        this.loadLessonsFromServer(); 
                    } else {
                        statusDiv.innerHTML = `<span style='color:#e74c3c;'>❌ ${data.error}</span>`;
                    }
                })
                .catch(err => {
                    document.getElementById('btn-submit-upload').disabled = false;
                    statusDiv.innerHTML = "<span style='color:#e74c3c;'>❌ حدث خطأ في الاتصال</span>";
                });
            };
        }
    },

    run2DAnimation: function(lessonId) {
        this.canvas2d.width = this.canvas2d.offsetWidth;
        this.canvas2d.height = this.canvas2d.offsetHeight;
        let frame = 0;
        this.animationInterval = setInterval(() => {
            frame++; let w = this.canvas2d.width; let h = this.canvas2d.height;
            let cx = w / 2; let cy = h / 2;
            this.ctx2d.clearRect(0, 0, w, h);
            this.ctx2d.fillStyle = "#ffffff"; this.ctx2d.fillRect(0, 0, w, h);
            this.ctx2d.textAlign = "center"; this.ctx2d.textBaseline = "middle";

            if (String(lessonId).includes("DNA") || String(lessonId).includes("dna")) {
                for (let i = 50; i < w - 50; i += 25) {
                    let y1 = cy + Math.sin(i * 0.01 + frame * 0.05) * 80; let y2 = cy + Math.sin(i * 0.01 + frame * 0.05 + Math.PI) * 80;
                    this.ctx2d.strokeStyle = (i % 50 === 0) ? "#2980b9" : "#e74c3c"; this.ctx2d.lineWidth = 2;
                    this.ctx2d.beginPath(); this.ctx2d.moveTo(i, y1); this.ctx2d.lineTo(i, y2); this.ctx2d.stroke();
                    this.ctx2d.fillStyle = "#6b1024"; this.ctx2d.beginPath(); this.ctx2d.arc(i, y1, 6, 0, Math.PI*2); this.ctx2d.fill();
                    this.ctx2d.fillStyle = "#27ae60"; this.ctx2d.beginPath(); this.ctx2d.arc(i, y2, 6, 0, Math.PI*2); this.ctx2d.fill();
                }
            } else if (String(lessonId).includes("النحو") || String(lessonId).includes("grammar")) {
                this.ctx2d.font = "bold 22px 'Segoe UI'"; this.ctx2d.fillStyle = "#6b1024"; this.ctx2d.fillText("تفرع الكلام في اللغة العربية", cx, 40);
                this.ctx2d.strokeStyle = "#6b1024"; this.ctx2d.lineWidth = 4;
                this.ctx2d.beginPath(); this.ctx2d.moveTo(cx, h - 80); this.ctx2d.lineTo(cx, cy + 40); 
                let pulse = Math.sin(frame * 0.04) * 15;
                this.ctx2d.lineTo(cx - 150 + pulse, cy - 20); this.ctx2d.moveTo(cx, cy + 40); this.ctx2d.lineTo(cx + 150 - pulse, cy - 20); this.ctx2d.stroke();
                this.ctx2d.fillStyle = "#27ae60"; this.ctx2d.fillText("الجملة الاسمية", cx - 160 + pulse, cy - 50);
                this.ctx2d.fillStyle = "#2980b9"; this.ctx2d.fillText("الجملة الفعلية", cx + 160 - pulse, cy - 50);
            } else if (String(lessonId).includes("موجات") || String(lessonId).includes("trig")) {
                let radius = 70; let circleCx = cx - 150; let angle = frame * 0.04;
                let pointerX = circleCx + Math.cos(angle) * radius; let pointerY = cy + Math.sin(angle) * radius;
                this.ctx2d.strokeStyle = "#333"; this.ctx2d.lineWidth = 2;
                this.ctx2d.beginPath(); this.ctx2d.arc(circleCx, cy, radius, 0, Math.PI*2); this.ctx2d.stroke();
                this.ctx2d.strokeStyle = "#e74c3c"; this.ctx2d.beginPath(); this.ctx2d.moveTo(circleCx, cy); this.ctx2d.lineTo(pointerX, pointerY); this.ctx2d.stroke();
                this.ctx2d.strokeStyle = "#6b1024"; this.ctx2d.lineWidth = 3; this.ctx2d.beginPath();
                for(let i = 0; i < 300; i++) {
                    let waveY = cy + Math.sin(angle - i * 0.03) * radius;
                    if(i === 0) this.ctx2d.moveTo(circleCx + radius + 40 + i, waveY); else this.ctx2d.lineTo(circleCx + radius + 40 + i, waveY);
                }
                this.ctx2d.stroke();
            } else {
                this.ctx2d.strokeStyle = "#6b1024"; this.ctx2d.lineWidth = 3; this.ctx2d.beginPath();
                for(let x = 0; x < w; x++) {
                    let y = cy + Math.sin(x * 0.02 + frame * 0.08) * 50;
                    if(x === 0) this.ctx2d.moveTo(x, y); else this.ctx2d.lineTo(x, y);
                }
                this.ctx2d.stroke();
                this.ctx2d.fillStyle = "#333"; this.ctx2d.font = "bold 16px 'Segoe UI'"; this.ctx2d.fillText("🔬 نظام البث الذكي والمتحرك", cx, h - 40);
            }
        }, 30);
    },

    stop2DAnimation: function() {
        if (this.animationInterval) { clearInterval(this.animationInterval); this.animationInterval = null; }
    }
};