/**
 * Roozmari Academy - Students Video Grid WebRTC Engine
 * Developed by: Eng. Ammar
 */

const StudentsGridModule = {
    peerConnections: {}, 
    failedSids: new Set(), 
    tid: null,
    pollingInterval: null,
    config: { 
        iceServers: [
            { urls: 'stun:stun.l.google.com:19302' }, 
            { urls: 'stun:stun1.l.google.com:19302' },
            { urls: 'turn:openrelay.metered.ca:80', username: 'openrelayproject', credential: 'openrelayproject' },
            { urls: 'turn:openrelay.metered.ca:443', username: 'openrelayproject', credential: 'openrelayproject' },
            { urls: 'turn:openrelay.metered.ca:443?transport=tcp', username: 'openrelayproject', credential: 'openrelayproject' }
        ] 
    },

    init: function(teacherId) {
        this.tid = teacherId;
        console.log("🚀 [Students Grid] تم تشغيل محرك مراقبة كاميرات الطلاب:", this.tid);
        if (!this.pollingInterval) {
            this.pollingInterval = setInterval(() => this.checkIncomingStudentCams(), 3000);
        }
    },

    checkIncomingStudentCams: async function() {
        try {
            const response = await fetch(`../zoom_api/waiting_room_api.php?action=get_all_students_signals&tid=${this.tid}`);
            const studentsSignals = await response.json(); 
            
            const activeSids = studentsSignals ? studentsSignals.map(s => s.sid) : [];
            Object.keys(this.peerConnections).forEach(sid => {
                if (!activeSids.includes(sid)) {
                    this.removeStudentFromGrid(sid);
                }
            });

            if (!studentsSignals || studentsSignals.length === 0) return;

            studentsSignals.forEach(async (signal) => {
                const studentSid = signal.sid;
                
                if (signal.offer) {
                    if (!this.peerConnections[studentSid]) {
                        await this.handleStudentOffer(studentSid, signal.offer);
                    } 
                    else {
                        const state = this.peerConnections[studentSid].iceConnectionState;
                        if (state === 'disconnected' || state === 'failed' || state === 'closed') {
                            this.removeStudentFromGrid(studentSid);
                            await this.handleStudentOffer(studentSid, signal.offer);
                        }
                    }
                }

                if (signal.student_ice && this.peerConnections[studentSid]) {
                    const pc = this.peerConnections[studentSid];
                    if (pc.remoteDescription) {
                        try {
                            const candidates = JSON.parse(signal.student_ice);
                            candidates.forEach(async (cand) => {
                                await pc.addIceCandidate(new RTCIceCandidate(cand));
                            });
                        } catch (e) { }
                    }
                }
            });
        } catch (error) {
            console.error("❌ خطأ أثناء فحص كاميرات الطلاب:", error);
        }
    },

    handleStudentOffer: async function(sid, offerObj) {
        try {
            const pc = new RTCPeerConnection(this.config);
            this.peerConnections[sid] = pc;
            
            // 🚀 تم الحل: إضافة مسارات الكاميرا بشكل صحيح لكي لا يختفي الفيديو
            pc.ontrack = (event) => {
                let stream = (event.streams && event.streams.length > 0) ? event.streams[0] : null;
                if (!stream && event.track) {
                    stream = new MediaStream([event.track]);
                }
                if (stream) {
                    this.renderStudentVideo(sid, stream);
                }
            };

            pc.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_teacher_ice_for_student&tid=${this.tid}&sid=${sid}`, { method: 'POST', body: formData });
                }
            };

            pc.oniceconnectionstatechange = (event) => {
                if (pc.iceConnectionState === 'failed' || pc.iceConnectionState === 'disconnected') {
                    this.failedSids.add(sid); 
                    this.removeStudentFromGrid(sid); 
                }
            };
            const offerParsed = typeof offerObj === 'string' ? JSON.parse(offerObj) : offerObj;
            await pc.setRemoteDescription(new RTCSessionDescription(offerParsed));
            const answer = await pc.createAnswer();
            await pc.setLocalDescription(answer);
            let formData = new FormData();
            formData.append('answer', JSON.stringify(answer));
            await fetch(`../zoom_api/waiting_room_api.php?action=save_answer_for_student&tid=${this.tid}&sid=${sid}`, { method: 'POST', body: formData });
        } catch (err) {
            this.removeStudentFromGrid(sid);
        }
    },

    renderStudentVideo: function(sid, stream) {
        const gridContainer = document.getElementById('students-video-grid');
        const noStudentsMsg = document.getElementById('no-students-msg');
        if (!gridContainer) return;
        if (noStudentsMsg) noStudentsMsg.style.display = 'none'; 

        let studentBox = document.getElementById(`cam-box-${sid}`);
        let videoEl = document.getElementById(`video-student-${sid}`);

        if (!studentBox) {
            studentBox = document.createElement('div');
            studentBox.id = `cam-box-${sid}`;
            studentBox.className = 'student-cam-box';
            videoEl = document.createElement('video');
            videoEl.id = `video-student-${sid}`;
            videoEl.autoplay = true;
            videoEl.playsInline = true;
            videoEl.muted = true;
            const nameTag = document.createElement('div');
            nameTag.className = 'student-name-tag';
            nameTag.innerHTML = `<i class="fas fa-user"></i> طالب (${sid})`;
            const audioBtn = document.createElement('button');
            audioBtn.className = 'student-audio-ctrl muted'; 
            audioBtn.id = `audio-ctrl-${sid}`;
            audioBtn.innerHTML = '<i class="fas fa-microphone-slash"></i>';
            audioBtn.onclick = (e) => { e.stopPropagation(); this.toggleStudentAudio(sid); };
            studentBox.appendChild(videoEl);
            studentBox.appendChild(audioBtn);
            studentBox.appendChild(nameTag);
            gridContainer.appendChild(studentBox);
            studentBox.onclick = () => {
                if (studentBox.classList.contains('spotlight-active')) {
                    studentBox.classList.remove('spotlight-active');
                } else {
                    document.querySelectorAll('.student-cam-box').forEach(box => box.classList.remove('spotlight-active'));
                    studentBox.classList.add('spotlight-active');
                }
            };
        }
        
        // 🚀 كسر تجميد الشاشة السوداء: التعيين المباشر وإجبار التشغيل
        if (videoEl) {
            videoEl.srcObject = stream;
            videoEl.onloadedmetadata = () => { videoEl.play().catch(e=>{}); };
            setTimeout(() => { videoEl.play().catch(e=>{}); }, 500);
        }
    },

    removeStudentFromGrid: function(sid) {
        if (this.peerConnections[sid]) {
            this.peerConnections[sid].close();
            delete this.peerConnections[sid];
        }
        const studentBox = document.getElementById(`cam-box-${sid}`);
        if (studentBox) studentBox.remove();
        const gridContainer = document.getElementById('students-video-grid');
        if (gridContainer && gridContainer.querySelectorAll('.student-cam-box').length === 0) {
            const noStudentsMsg = document.getElementById('no-students-msg');
            if (noStudentsMsg) noStudentsMsg.style.display = 'block';
        }
    }, 

    toggleStudentAudio: function(sid) {
        const videoEl = document.getElementById(`video-student-${sid}`);
        const audioBtn = document.getElementById(`audio-ctrl-${sid}`);
        if (videoEl && audioBtn) {
            videoEl.muted = !videoEl.muted;
            if (videoEl.muted) {
                audioBtn.classList.add('muted');
                audioBtn.innerHTML = '<i class="fas fa-microphone-slash"></i>';
            } else {
                audioBtn.classList.remove('muted');
                audioBtn.innerHTML = '<i class="fas fa-microphone"></i>';
            }
        }
    },

    muteAll: function() {
        const allVideos = document.querySelectorAll('.student-cam-box video');
        const allBtns = document.querySelectorAll('.student-audio-ctrl');
        allVideos.forEach(vid => vid.muted = true);
        allBtns.forEach(btn => {
            btn.classList.add('muted');
            btn.innerHTML = '<i class="fas fa-microphone-slash"></i>';
        });
    }
};