/**
 * بوابة واتساب - واجهة المحادثة
 * مع خطوات التحقق المرئية عند تسجيل الدخول
 */

(() => {
    'use strict';

    const POLL_INTERVAL = 3000;
    const API = {
        login:   'api/login.php',
        logout:  'api/logout.php',
        send:    'api/send.php',
        poll:    'api/poll.php',
        history: 'api/history.php',
    };

    const STRINGS = {
        connected:       'متصل',
        reconnecting:    'جاري إعادة الاتصال...',
        invalidPhone:    'الرجاء إدخال رقم هاتف صالح (10-15 رقم مع رمز الدولة).',
        loginFailed:     'فشل تسجيل الدخول. حاول مرة أخرى.',
        connectionError: 'خطأ في الاتصال بالخادم. حاول مرة أخرى.',
        confirmLogout:   'هل تريد قطع الاتصال عن هذه الجلسة؟',
        sessionStart:    'بدأت جلسة المحادثة. يتم نقل الرسائل عبر واتساب.',
        notOnWhatsApp:   'هذا الرقم غير مسجل في واتساب.',
    };

    let lastTimestamp = 0;
    let pollTimer     = null;
    let isSending     = false;

    const $ = (sel) => document.querySelector(sel);
    const loginScreen   = $('#loginScreen');
    const chatScreen    = $('#chatScreen');
    const loginForm     = $('#loginForm');
    const loginBtn      = $('#loginBtn');
    const loginError    = $('#loginError');
    const phoneInput    = $('#phoneNumber');
    const messageForm   = $('#messageForm');
    const messageInput  = $('#messageInput');
    const sendBtn       = $('#sendBtn');
    const messagesInner = $('#messagesInner');
    const chatMessages  = $('#chatMessages');
    const logoutBtn     = $('#logoutBtn');
    const headerPhone   = $('#headerPhone');
    const connStatus    = $('#connectionStatus');
    const verifyStatus  = $('#verifyStatus');
    const stepFormat    = $('#stepFormat');
    const stepWhatsApp  = $('#stepWhatsApp');
    const stepSession   = $('#stepSession');
    const imageInput    = $('#imageInput');
    const imagePreview  = $('#imagePreview');
    const previewImg    = $('#previewImg');
    const cancelImage   = $('#cancelImage');
    let selectedImage   = null; // File object


    // ============================================================
    // تسجيل الدخول مع خطوات التحقق
    // ============================================================

    loginForm?.addEventListener('submit', async (e) => {
        e.preventDefault();
        const phone = phoneInput.value.replace(/[^0-9]/g, '');

        // إعادة تعيين حالة التحقق
        resetVerifySteps();
        hideLoginError();

        // الخطوة 1: التحقق من صيغة الرقم (محلياً)
        verifyStatus.classList.remove('hidden');
        
        if (phone.length < 10 || phone.length > 15) {
            setStepState(stepFormat, 'error');
            showLoginError(STRINGS.invalidPhone);
            return;
        }
        setStepState(stepFormat, 'success');

        // الخطوة 2: التحقق من واتساب (عبر API)
        setStepState(stepWhatsApp, 'loading');
        setLoginLoading(true);

        try {
            const res = await fetch(API.login, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ phone }),
            });
            const data = await res.json();

            if (data.success && data.verified) {
                // الرقم صالح ومسجل في واتساب
                setStepState(stepWhatsApp, 'success');
                
                // الخطوة 3: إنشاء الجلسة
                setStepState(stepSession, 'loading');
                await sleep(400); // تأخير بسيط للتأثير البصري
                setStepState(stepSession, 'success');
                
                await sleep(500);
                
                headerPhone.textContent = '+' + phone;
                switchToChat();
                loadChatHistory();
            } else {
                // فشل التحقق
                if (data.step === 'whatsapp_verification') {
                    setStepState(stepWhatsApp, 'error');
                } else {
                    setStepState(stepWhatsApp, 'error');
                }
                showLoginError(data.error || STRINGS.notOnWhatsApp);
            }
        } catch (err) {
            setStepState(stepWhatsApp, 'error');
            showLoginError(STRINGS.connectionError);
            console.error('Login error:', err);
        } finally {
            setLoginLoading(false);
        }
    });

    // ── دوال خطوات التحقق ───────────────────────────────

    function setStepState(stepEl, state) {
        const icon = stepEl.querySelector('.step-icon');
        stepEl.className = 'verify-step ' + state;
        switch (state) {
            case 'loading': icon.textContent = '⏳'; break;
            case 'success': icon.textContent = '✅'; break;
            case 'error':   icon.textContent = '❌'; break;
            default:        icon.textContent = '⏳';
        }
    }

    function resetVerifySteps() {
        [stepFormat, stepWhatsApp, stepSession].forEach(el => {
            if (el) {
                el.className = 'verify-step';
                el.querySelector('.step-icon').textContent = '⏳';
            }
        });
        verifyStatus?.classList.add('hidden');
    }

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    function setLoginLoading(loading) {
        loginBtn.disabled = loading;
        loginBtn.querySelector('.btn-text').classList.toggle('hidden', loading);
        loginBtn.querySelector('.btn-loader').classList.toggle('hidden', !loading);
    }

    function showLoginError(msg) {
        loginError.textContent = msg;
        loginError.classList.remove('hidden');
    }

    function hideLoginError() {
        loginError.classList.add('hidden');
    }

    function switchToChat() {
        loginScreen.classList.add('hidden');
        chatScreen.classList.remove('hidden');
        messageInput.focus();
        startPolling();
    }

    function switchToLogin() {
        chatScreen.classList.add('hidden');
        loginScreen.classList.remove('hidden');
        stopPolling();
        resetVerifySteps();
        messagesInner.innerHTML = `<div class="system-msg"><span>${STRINGS.sessionStart}</span></div>`;
        lastTimestamp = 0;
    }


    // ============================================================
    // تسجيل الخروج
    // ============================================================

    logoutBtn?.addEventListener('click', async () => {
        if (!confirm(STRINGS.confirmLogout)) return;
        try {
            await fetch(API.logout, { method: 'POST' });
        } catch (_) {}
        switchToLogin();
    });


    // ============================================================
    // إرسال الرسائل
    // ============================================================

    messageForm?.addEventListener('submit', (e) => {
        e.preventDefault();
        sendMessage();
    });

    async function sendMessage() {
        const body = messageInput.value.trim();
        const hasImage = selectedImage !== null;
        
        if (!body && !hasImage) return;
        if (isSending) return;

        isSending = true;
        sendBtn.disabled = true;

        // عرض الرسالة مباشرة
        let displayBody = body;
        let previewSrc = null;
        if (hasImage) {
            displayBody = body || '[صورة]';
            previewSrc = previewImg.src;
        }
        const tempMsg = appendMessage('outgoing', displayBody, Date.now() / 1000, 'sending', previewSrc);
        
        messageInput.value = '';
        autoResizeTextarea();
        scrollToBottom();

        try {
            let res;
            
            if (hasImage) {
                // إرسال بصورة عبر FormData
                const formData = new FormData();
                formData.append('image', selectedImage);
                formData.append('message', body);
                
                res = await fetch('api/send_image.php', {
                    method: 'POST',
                    body: formData,
                });
                
                // تنظيف الصورة
                selectedImage = null;
                imageInput.value = '';
                previewImg.src = '';
                imagePreview.classList.add('hidden');
            } else {
                // إرسال نص عادي
                res = await fetch(API.send, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message: body }),
                });
            }
            
            const data = await res.json();

            if (data.success) {
                const statusEl = tempMsg.querySelector('.msg-status');
                if (statusEl) {
                    statusEl.textContent = '✓';
                    statusEl.className = 'msg-status delivered';
                }
                lastTimestamp = Math.max(lastTimestamp, data.message.timestamp);
            } else {
                const statusEl = tempMsg.querySelector('.msg-status');
                if (statusEl) {
                    statusEl.textContent = '✗';
                    statusEl.className = 'msg-status failed';
                }
                if (res.status === 401) switchToLogin();
            }
        } catch (err) {
            console.error('Send error:', err);
            const statusEl = tempMsg.querySelector('.msg-status');
            if (statusEl) {
                statusEl.textContent = '✗';
                statusEl.className = 'msg-status failed';
            }
        } finally {
            isSending = false;
            updateSendButton();
        }
    }


    // ============================================================
    // رفع الصور
    // ============================================================

    imageInput?.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (!file) return;
        
        if (!file.type.startsWith('image/')) {
            alert('الرجاء اختيار صورة فقط');
            imageInput.value = '';
            return;
        }
        
        if (file.size > 10 * 1024 * 1024) {
            alert('حجم الصورة يجب أن لا يتجاوز 10 ميجابايت');
            imageInput.value = '';
            return;
        }
        
        selectedImage = file;
        const reader = new FileReader();
        reader.onload = (ev) => {
            previewImg.src = ev.target.result;
            imagePreview.classList.remove('hidden');
        };
        reader.readAsDataURL(file);
        updateSendButton();
    });

    cancelImage?.addEventListener('click', () => {
        selectedImage = null;
        imageInput.value = '';
        previewImg.src = '';
        imagePreview.classList.add('hidden');
        updateSendButton();
    });


    // ============================================================
    // استقبال الرسائل
    // ============================================================

    function startPolling() {
        stopPolling();
        poll();
        pollTimer = setInterval(poll, POLL_INTERVAL);
        connStatus.textContent = STRINGS.connected;
        connStatus.classList.remove('offline');
    }

    function stopPolling() {
        if (pollTimer) {
            clearInterval(pollTimer);
            pollTimer = null;
        }
    }

    async function poll() {
        try {
            const res = await fetch(`${API.poll}?since=${lastTimestamp}`);
            const data = await res.json();

            if (data.success && data.messages.length > 0) {
                data.messages.forEach((msg) => {
                    if (msg.direction === 'incoming') {
                        appendMessage('incoming', msg.body, msg.timestamp);
                    }
                    lastTimestamp = Math.max(lastTimestamp, msg.timestamp);
                });
                scrollToBottom();
            }

            connStatus.textContent = STRINGS.connected;
            connStatus.classList.remove('offline');
        } catch (err) {
            connStatus.textContent = STRINGS.reconnecting;
            connStatus.classList.add('offline');
        }
    }


    // ============================================================
    // سجل المحادثة
    // ============================================================

    window.loadChatHistory = async function() {
        try {
            const res = await fetch(API.history);
            const data = await res.json();

            if (data.success && data.messages.length > 0) {
                messagesInner.innerHTML = '';
                data.messages.forEach((msg) => {
                    appendMessage(msg.direction, msg.body, msg.timestamp, msg.status);
                    lastTimestamp = Math.max(lastTimestamp, msg.timestamp);
                });
                scrollToBottom();
            }
            startPolling();
        } catch (err) {
            console.error('History load error:', err);
            startPolling();
        }
    };


    // ============================================================
    // أدوات الواجهة
    // ============================================================

    function appendMessage(direction, body, timestamp, status = 'delivered', imageSrc = null) {
        const msg = document.createElement('div');
        msg.className = `msg ${direction}`;

        const timeStr = formatTime(timestamp);
        let statusIcon = '';
        if (direction === 'outgoing') {
            switch (status) {
                case 'sending':        statusIcon = '<span class="msg-status">⏳</span>'; break;
                case 'delivered':      statusIcon = '<span class="msg-status delivered">✓</span>'; break;
                case 'read':           statusIcon = '<span class="msg-status read">✓✓</span>'; break;
                case 'failed':
                case 'failed_relay':   statusIcon = '<span class="msg-status failed">✗</span>'; break;
                default:               statusIcon = '<span class="msg-status delivered">✓</span>';
            }
        }

        const safeBody = escapeHtml(body).replace(/\n/g, '<br>');
        
        let imageHtml = '';
        if (imageSrc) {
            imageHtml = `<img src="${imageSrc}" class="msg-image" alt="صورة">`;
        }

        msg.innerHTML = `
            <div class="msg-bubble">${imageHtml}${safeBody}</div>
            <div class="msg-meta">
                <span class="msg-time">${timeStr}</span>
                ${statusIcon}
            </div>
        `;

        messagesInner.appendChild(msg);
        return msg;
    }

    function scrollToBottom() {
        requestAnimationFrame(() => {
            chatMessages.scrollTop = chatMessages.scrollHeight;
        });
    }

    function formatTime(ts) {
        const d = new Date(ts * 1000);
        return d.toLocaleTimeString('ar-EG', { hour: '2-digit', minute: '2-digit' });
    }

    function escapeHtml(str) {
        const div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }

    messageInput?.addEventListener('input', () => {
        autoResizeTextarea();
        updateSendButton();
    });

    messageInput?.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });

    function autoResizeTextarea() {
        messageInput.style.height = 'auto';
        messageInput.style.height = Math.min(messageInput.scrollHeight, 120) + 'px';
    }

    function updateSendButton() {
        sendBtn.disabled = (!messageInput.value.trim() && !selectedImage) || isSending;
    }

    if (!chatScreen.classList.contains('hidden')) {
        startPolling();
    }
})();
