const WhiteboardModule = {
    canvas: null,
    ctx: null,
    isDrawing: false,
    
    currentTool: 'pen',
    currentColor: '#000000',
    currentLineWidth: 3,
    textInput: null,
    currentStrokeId: null,      // بصمة الحرف الحالي
    currentPoints: [],          // مصفوفة لتجميع نقاط الخط الحالي

    role: 'teacher', 
    syncInterval: null,
    onSyncDataReady: null, 

    init: function(userRole = 'teacher', syncCallback = null) {
        this.role = userRole;
        this.onSyncDataReady = syncCallback;
        
        this.canvas = document.getElementById('whiteboard');
        if (!this.canvas) return;
        this.ctx = this.canvas.getContext('2d');
        
        // 🚀 تنظيف السبورة فوراً عند التحميل
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        this.ctx.lineCap = "round";
        this.ctx.lineJoin = "round";

        this.resize();
        this.attachEvents(); 
        
        if (this.role === 'teacher') {
            this.setupToolbar();
            this.startSyncEngine();
        } else {
            // تفعيل الأدوات للطالب أيضاً
            this.setupToolbar();
        }
    },
// 🚀 دالة ذكية للتبديل بين وضع السبورة البيضاء ووضع "الزجاج الشفاف"
    setMode: function(mode) {
        if (mode === 'transparent') {
            this.canvas.style.backgroundColor = 'transparent';
        } else {
            this.canvas.style.backgroundColor = '#ffffff';
        }
    },
    resize: function() {
        this.canvas.width = this.canvas.offsetWidth;
        this.canvas.height = this.canvas.offsetHeight;
        // أزلنا الخلفية البيضاء الإجبارية لكي يبقى الزجاج شفافاً دائماً فوق المجسمات
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },
    // أضف هذه الدالة هنا
    toggleInteraction: function(isDrawingMode) {
        if (isDrawingMode) {
            this.canvas.style.pointerEvents = 'auto'; // السبورة تسمح بالرسم
            this.canvas.style.backgroundColor = 'transparent'; // زجاج شفاف فوق الملفات
        } else {
            this.canvas.style.pointerEvents = 'none'; // السبورة "زجاج مكسور" يمرر الماوس للملفات تحتها
            this.canvas.style.backgroundColor = 'transparent';
        }
    },

    // 🚀 دالة جديدة للتحكم الذكي بالأدوات وشفافية الزجاج
    setTool: function(toolName, btnElement) {
        this.currentTool = toolName;
        this.updateActiveBtn(btnElement);

        if (toolName === 'hand') {
            // إخفاء السبورة فيزيائياً ليتمكن المستخدم من تدوير مجسم الـ 3D
            this.canvas.style.pointerEvents = 'none';
        } else {
            // إعادة تفعيل السبورة لالتقاط الرسم
            this.canvas.style.pointerEvents = 'auto';
        }
    },

   setupToolbar: function() {
        const btnPen = document.getElementById('tool-pen');
        const btnText = document.getElementById('tool-text');
        const btnEraser = document.getElementById('tool-eraser');
        const btnHand = document.getElementById('tool-hand'); 
        const colorPicker = document.getElementById('color-picker');
        const widthSlider = document.getElementById('pen-width');
        const widthVal = document.getElementById('width-val');
        const btnClearAll = document.getElementById('btn-clear-all');

        // 🚀 دالة ذكية مدمجة للتحكم بالأدوات والشفافية
        const applyTool = (toolName, activeBtn) => {
            this.currentTool = toolName;
            
            // تفعيل شكل الزر
            document.querySelectorAll('.tool-group .btn').forEach(btn => btn.classList.remove('active'));
            if(activeBtn) activeBtn.classList.add('active');
            
            // 🚀 السر هنا: التحكم باختراق الماوس للسبورة
            if (toolName === 'hand') {
                this.canvas.style.pointerEvents = 'none'; // الماوس يخترق السبورة ليحرك الملفات
            } else {
                this.canvas.style.pointerEvents = 'auto'; // السبورة تلتقط الماوس للرسم
            }
        };

        if(btnPen) btnPen.onclick = () => { applyTool('pen', btnPen); };
        if(btnText) btnText.onclick = () => { applyTool('text', btnText); };
        if(btnEraser) btnEraser.onclick = () => { applyTool('eraser', btnEraser); };
        if(btnHand) btnHand.onclick = () => { applyTool('hand', btnHand); };

        if (colorPicker) {
            colorPicker.oninput = (e) => {
                this.currentColor = e.target.value;
                if ((this.currentTool === 'eraser' || this.currentTool === 'hand') && btnPen) {
                    applyTool('pen', btnPen);
                }
            };
        }

        if (widthSlider) {
            widthSlider.oninput = (e) => {
                this.currentLineWidth = e.target.value;
                if (widthVal) widthVal.innerText = this.currentLineWidth + 'px';
            };
        }
        
        if (btnClearAll) {
            btnClearAll.onclick = () => {
                this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
                
                if (typeof WhiteboardSync !== 'undefined') {
                    const currentTid = typeof phpTid !== 'undefined' ? phpTid : new URLSearchParams(window.location.search).get('tid');
                    WhiteboardSync.pauseSync = true;
                    WhiteboardSync.sendClearSignal(currentTid);
                    setTimeout(() => { WhiteboardSync.pauseSync = false; }, 2000);
                }
            };
        }

        // 🚀 تفعيل القلم فوراً عند فتح الصفحة لكي لا تكون السبورة معطلة أو ميتة
        if (btnPen) {
            setTimeout(() => { btnPen.click(); }, 300);
        }
    },

    updateActiveBtn: function(activeBtn) {
        document.querySelectorAll('.tool-group .btn').forEach(btn => btn.classList.remove('active'));
        if(activeBtn) activeBtn.classList.add('active');
    },

    attachEvents: function() {
        this.canvas.addEventListener('mousedown', (e) => this.start(e));
        this.canvas.addEventListener('mousemove', (e) => this.draw(e));
        this.canvas.addEventListener('mouseup', () => this.stop());
        this.canvas.addEventListener('mouseleave', () => this.stop());

        this.canvas.addEventListener('touchstart', (e) => this.start(e), {passive: false});
        this.canvas.addEventListener('touchmove', (e) => this.draw(e), {passive: false});
        this.canvas.addEventListener('touchend', () => this.stop());
    },

    getPos: function(e) {
        const rect = this.canvas.getBoundingClientRect();
        let clientX = e.touches ? e.touches[0].clientX : e.clientX;
        let clientY = e.touches ? e.touches[0].clientY : e.clientY;
        
        const scaleX = this.canvas.width / rect.width;    
        const scaleY = this.canvas.height / rect.height;  

        return { 
            x: (clientX - rect.left) * scaleX, 
            y: (clientY - rect.top) * scaleY 
        };
    },

    lastSendTime: 0,

    start: function(e) {
        if (this.role === 'student' && window.canStudentDraw !== true) return;
        if (this.currentTool === 'hand') return; // لا نرسم إذا كانت الأداة يد
        if (e.cancelable) e.preventDefault();
        
        if (this.currentTool === 'text') {
            this.spawnTextInput(e);
            return;
        }

        const pos = this.getPos(e);
        this.isDrawing = true;
        
        this.currentStrokeId = Date.now();
        this.currentPoints = [{ x: pos.x / this.canvas.width, y: pos.y / this.canvas.height }];
        
        this.ctx.beginPath();
        this.ctx.moveTo(pos.x, pos.y);

        // جعل الممحاة تمسح بخاصية الشفافية (لكي لا تترك لوناً أبيضاً فوق المجسم)
        if (this.currentTool === 'eraser') {
            this.ctx.globalCompositeOperation = 'destination-out';
            this.ctx.lineWidth = this.currentLineWidth * 4;
            this.ctx.strokeStyle = "rgba(0,0,0,1)";
        } else {
            this.ctx.globalCompositeOperation = 'source-over';
            this.ctx.strokeStyle = this.currentColor;
            this.ctx.lineWidth = this.currentLineWidth;
        }
        
        if (this.role === 'student' && typeof WhiteboardSync !== 'undefined') {
            const currentTid = typeof phpTid !== 'undefined' ? phpTid : new URLSearchParams(window.location.search).get('tid');
            let strokeColor = this.currentTool === 'eraser' ? 'eraser' : this.currentColor;
            WhiteboardSync.sendStudentData(this.currentPoints, strokeColor, this.ctx.lineWidth, this.currentTool, currentTid, this.currentStrokeId);
            this.lastSendTime = Date.now(); 
        }
    },

    draw: function(e) {
        if (!this.isDrawing || this.currentTool === 'text' || this.currentTool === 'hand') return;
        if (e.cancelable) e.preventDefault();
        
        const pos = this.getPos(e);
        this.ctx.lineTo(pos.x, pos.y);
        this.ctx.stroke();
        
        if (this.role === 'student' && typeof WhiteboardSync !== 'undefined') {
            this.currentPoints.push({ x: pos.x / this.canvas.width, y: pos.y / this.canvas.height });
            
            if (Date.now() - this.lastSendTime > 100) {
                const currentTid = typeof phpTid !== 'undefined' ? phpTid : new URLSearchParams(window.location.search).get('tid');
                let strokeColor = this.currentTool === 'eraser' ? 'eraser' : this.currentColor;
                WhiteboardSync.sendStudentData(this.currentPoints, strokeColor, this.ctx.lineWidth, this.currentTool, currentTid, this.currentStrokeId);
                this.lastSendTime = Date.now();
            }
        }
        
        if (typeof window.socket !== 'undefined' && window.socket.connected) {
            window.socket.emit('draw', {
                points: this.currentPoints,
                color: this.currentTool === 'eraser' ? 'eraser' : this.currentColor,
                width: this.ctx.lineWidth,
                tool: this.currentTool,
                strokeId: this.currentStrokeId
            });
        } else if (window.sendDrawViaSocket) {
            window.sendDrawViaSocket({
                points: this.currentPoints,
                color: this.currentTool === 'eraser' ? 'eraser' : this.currentColor,
                width: this.ctx.lineWidth,
                tool: this.currentTool,
                strokeId: this.currentStrokeId
            });
        }
    },

    stop: function() {
        if(this.isDrawing) {
            this.isDrawing = false;
            this.ctx.closePath();
            // إعادة الوضع الطبيعي للرسم بعد الممحاة
            this.ctx.globalCompositeOperation = 'source-over';
            
            if (this.role === 'student' && typeof WhiteboardSync !== 'undefined') {
                const currentTid = typeof phpTid !== 'undefined' ? phpTid : new URLSearchParams(window.location.search).get('tid');
                let strokeColor = this.currentTool === 'eraser' ? 'eraser' : this.currentColor;
                WhiteboardSync.sendStudentData(this.currentPoints, strokeColor, this.ctx.lineWidth, this.currentTool, currentTid, this.currentStrokeId);
            }
        }
    },

    spawnTextInput: function(e) {
        if (this.textInput) this.finalizeText(); 
        let clientX = e.clientX;
        let clientY = e.clientY;

        const wrapper = document.createElement('div');
        wrapper.className = 'text-wrapper';
        wrapper.style.position = 'absolute';
        wrapper.style.left = clientX + 'px';
        wrapper.style.top = clientY + 'px';
        wrapper.style.zIndex = '1000';
        wrapper.style.border = '1px dashed #6b1024';
        wrapper.style.padding = '5px';

        const textarea = document.createElement('textarea');
        textarea.style.color = this.currentColor;
        
        const btnConfirm = document.createElement('button');
        btnConfirm.innerHTML = '✔ تثبيت';
        btnConfirm.onclick = () => this.finalizeText();

        wrapper.appendChild(textarea);
        wrapper.appendChild(btnConfirm);
        document.body.appendChild(wrapper);

        textarea.focus();
        this.textInput = { wrapper, textarea };
    },

    finalizeText: function() {
        if (!this.textInput) return;
        const wrapper = this.textInput.wrapper;
        const textarea = this.textInput.textarea;
        const text = textarea.value;

        if (text.trim() !== '') {
            const rect = this.canvas.getBoundingClientRect();
            const wrapperRect = wrapper.getBoundingClientRect();
            
            const finalX = (wrapperRect.left - rect.left); 
            const finalY = (wrapperRect.top - rect.top); 

            this.ctx.font = `bold 20px 'Segoe UI', Arial`;
            this.ctx.fillStyle = this.currentColor;
            this.ctx.textBaseline = "top";
            this.ctx.fillText(text, finalX, finalY);
        }
        wrapper.remove();
        this.textInput = null;
    },

    startSyncEngine: function() {
        if (this.role !== 'teacher' || !this.onSyncDataReady) return;
        this.syncInterval = setInterval(() => {
            // نستخدم PNG لدعم الشفافية بدلاً من JPEG الذي يضع خلفية سوداء/بيضاء
            const snapshot = this.canvas.toDataURL('image/png');
            this.onSyncDataReady({ image: snapshot });
        }, 1000);
    },

    executeRemoteSync: function(payload) {
        if (!payload || !payload.image) return;
        const img = new Image();
        img.onload = () => {
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
            this.ctx.drawImage(img, 0, 0, this.canvas.width, this.canvas.height);
        };
        img.src = payload.image;
    }
};