const WebRTCModule = {
    peerConnection: null, role: null, tid: null, signalingInterval: null, localStream: null,
    config: {
        iceServers: [
            { urls: 'stun:stun.l.google.com:19302' },
            { urls: 'stun:stun1.l.google.com:19302' }
        ]
    },

    init: async function(userRole, teacherId, stream = null) {
        this.role = userRole; this.tid = teacherId; this.localStream = stream;
        this.closeConnection(); 
        this.setupPeerConnection();
        
        if (this.role === 'teacher' && this.localStream) {
            this.localStream.getTracks().forEach(track => {
                if(this.peerConnection && this.peerConnection.signalingState !== "closed") {
                    this.peerConnection.addTrack(track, this.localStream);
                }
            });
            await this.createOffer();
        }
        if (!this.signalingInterval) this.startSignaling();
    },

   setupPeerConnection: function() {
        if (this.peerConnection) this.peerConnection.close();
        this.peerConnection = new RTCPeerConnection(this.config);

        this.peerConnection.ontrack = (event) => {
            try {
                const remoteVideo = document.getElementById('remoteVideo');
                const container = document.getElementById('teacher-cam-panel');
                const track = event.track;

                if (track.label && track.label.toLowerCase().includes('screen')) {
                     console.log("🖥️ بث شاشة");
                     return;
                }

                console.log("📷 مسار ميديا وصل: ", track.kind);
                
                if (remoteVideo) {
                    if (container && track.kind === 'video') {
                        container.style.setProperty('display', 'flex', 'important');
                        container.style.setProperty('visibility', 'visible', 'important');
                        container.style.setProperty('opacity', '1', 'important');
                        container.style.setProperty('z-index', '999999', 'important'); // 🚀 يجب أن تطفو فوق السبورة!
                    }

                    let stream = event.streams && event.streams[0] ? event.streams[0] : null;
                    if (!stream) {
                        stream = new MediaStream([track]);
                    } else if (!stream.getTracks().includes(track)) {
                        stream.addTrack(track);
                    }

                    remoteVideo.srcObject = null;
                    
                    setTimeout(() => {
                        remoteVideo.srcObject = stream;
                        remoteVideo.setAttribute('playsinline', 'true');
                        remoteVideo.setAttribute('autoplay', 'true');
                        // 🚀 إجبار المتصفح على رسم الفيديو كطبقة عليا لكسر التجميد
                        remoteVideo.style.cssText = "width: 100%; flex: 1; object-fit: cover; background: transparent; z-index: 999999; transform: translateZ(0);";
                        
                        remoteVideo.muted = true; 
                        remoteVideo.play().then(() => {
                            remoteVideo.muted = false;
                        }).catch(e => {
                            remoteVideo.muted = true;
                            remoteVideo.play().catch(err=>{});
                        });
                    }, 50);
                }
            } catch (error) {}
        };

        this.peerConnection.onicecandidate = (event) => {
            if (event.candidate) {
                let formData = new FormData(); formData.append('candidate', JSON.stringify(event.candidate));
                fetch(`../zoom_api/waiting_room_api.php?action=save_ice&tid=${this.tid}&role=${this.role}`, { method: 'POST', body: formData });
            }
        };
    },
    
    closeConnection: function() {
        if (this.peerConnection) {
            this.peerConnection.onicecandidate = null;
            this.peerConnection.ontrack = null;
            this.peerConnection.close();
            this.peerConnection = null;
        }
    },

    hideStudentCameraWindow: function() {
        const camPanel = document.getElementById('teacher-cam-panel');
        const remoteVideo = document.getElementById('remoteVideo');
        if (camPanel && camPanel.style.display !== 'none') {
            camPanel.style.setProperty('visibility', 'hidden', 'important');
            camPanel.style.setProperty('opacity', '0', 'important');
        }
        if (remoteVideo) {
            remoteVideo.pause();
            remoteVideo.srcObject = null;
        }
    },

    stopTeacher: function() {
        this.closeConnection();
        fetch(`../zoom_api/waiting_room_api.php?action=clear_signal&tid=${this.tid}`);
    },

    createOffer: async function() {
        const offer = await this.peerConnection.createOffer();
        await this.peerConnection.setLocalDescription(offer);
        let formData = new FormData(); formData.append('offer', JSON.stringify(offer));
        fetch(`../zoom_api/waiting_room_api.php?action=save_offer&tid=${this.tid}&role=teacher`, { method: 'POST', body: formData });
    },

    createAnswer: async function(offerObj) {
        if (!this.peerConnection || this.peerConnection.signalingState === "closed") this.setupPeerConnection();
        try {
            const offerParsed = typeof offerObj === 'string' ? JSON.parse(offerObj) : offerObj;
            await this.peerConnection.setRemoteDescription(new RTCSessionDescription(offerParsed));
            const answer = await this.peerConnection.createAnswer();
            await this.peerConnection.setLocalDescription(answer);
            let formData = new FormData(); formData.append('answer', JSON.stringify(answer));
            fetch(`../zoom_api/waiting_room_api.php?action=save_answer&tid=${this.tid}&role=student`, { method: 'POST', body: formData });
        } catch(e) { }
    },

    startSignaling: function() {
        if (this.signalingInterval) clearInterval(this.signalingInterval);
        let lastOfferString = "";

        this.signalingInterval = setInterval(async () => {
            try {
                const response = await fetch(`../zoom_api/waiting_room_api.php?action=get_signal&tid=${this.tid}&role=${this.role}`);
                const data = await response.json();

                if (this.role === 'student') {
                    if (!data.offer) {
                        this.hideStudentCameraWindow();
                        lastOfferString = ""; 
                    } else if (data.offer) {
                        const currentOfferString = JSON.stringify(data.offer);
                        // 🛑 السطر الذي كان يدمر الاتصال تم تعديله هنا (إزالة closeConnection)
                        if (currentOfferString !== lastOfferString || !this.peerConnection || this.peerConnection.signalingState === "closed") {
                            console.log("📥 إعادة التفاوض (تحديث الكاميرا) تمت بنجاح وبدون قطع الاتصال...");
                            lastOfferString = currentOfferString;
                            // تم إزالة تدمير الاتصال هنا لكي تبقى الشاشة حية
                            await this.createAnswer(data.offer);
                        }
                    }
                }

                if (this.role === 'teacher' && data.answer && this.peerConnection && !this.peerConnection.currentRemoteDescription) {
                    const answerParsed = typeof data.answer === 'string' ? JSON.parse(data.answer) : data.answer;
                    await this.peerConnection.setRemoteDescription(new RTCSessionDescription(answerParsed));
                }

                if (data.candidates && data.candidates.length > 0 && this.peerConnection && this.peerConnection.remoteDescription) {
                    data.candidates.forEach(async (cand) => {
                        try { await this.peerConnection.addIceCandidate(new RTCIceCandidate(JSON.parse(cand))); } catch(e) {}
                    });
                }
            } catch(e) {}
        }, 2000);
    }
};