/**
 * SMART PKBM CHAT SYSTEM - chat.js (Laravel Version)
 * Diperbarui: April 2026
 * Optimasi: Pencegahan Race-Condition & Smart Dynamic Polling
 */

let isSending = false;
let selectedMsgId = null;
let selectedMsgText = "";
let isUserScrollingUp = false;
let pollingTimer = null; // Menyimpan ID interval dynamic timeout

document.addEventListener("DOMContentLoaded", () => {
    const form = document.querySelector("#chat-form");
    const inputField = document.querySelector("#input-message");
    const chatContainer = document.querySelector("#chat-container");
    const settingsModal = document.getElementById('settings-modal');
    const openSettingsBtn = document.getElementById('open-settings');
    const settingsForm = document.getElementById('settings-form');

    // --- 1. LOGIKA PENGATURAN PROFIL (SETTINGS) ---
    if(openSettingsBtn && settingsModal) {
        openSettingsBtn.onclick = () => {
            settingsModal.classList.remove('hidden');
        };
    }
    
    window.closeSettings = () => {
        if(settingsModal) settingsModal.classList.add('hidden');
    };
    
    window.previewImage = (input) => {
        if (input.files && input.files[0]) {
            let reader = new FileReader();
            reader.onload = (e) => {
                const preview = document.getElementById('settings-avatar-preview');
                if(preview) preview.src = e.target.result;
            };
            reader.readAsDataURL(input.files[0]);
        }
    };
    
    if(settingsForm) {
        settingsForm.onsubmit = (e) => {
            e.preventDefault();
            const btnSave = document.getElementById('btn-save-settings');
            const originalHTML = btnSave.innerHTML;
            
            btnSave.innerHTML = '<i class="fa-solid fa-spinner animate-spin"></i> Menyimpan...';
            btnSave.disabled = true;
    
            let formData = new FormData(settingsForm);
            
            $.ajax({
                url: profileUpdateUrl,
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function(response) {
                    if (response.status === "success") {
                        alert("Profil berhasil diperbarui!");
                        location.reload();
                    } else {
                        alert("Gagal memperbarui profil.");
                        btnSave.innerHTML = originalHTML;
                        btnSave.disabled = false;
                    }
                },
                error: function(xhr) {
                    alert("Terjadi kesalahan sistem.");
                    btnSave.innerHTML = originalHTML;
                    btnSave.disabled = false;
                }
            });
        };
    }

    // --- 2. LOGIKA SCROLLING ---
    if (chatContainer) {
        chatContainer.addEventListener('scroll', () => {
            const distanceFromBottom = chatContainer.scrollHeight - chatContainer.scrollTop - chatContainer.clientHeight;
            isUserScrollingUp = (distanceFromBottom > 50);
        });
    }

    function scrollToBottom() {
        if(chatContainer) {
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
    }

    // --- 3. FUNGSI KIRIM & EDIT PESAN ---
    window.sendMessage = () => {
        const receiverId = document.getElementById('receiver_id').value;
        const messageVal = inputField.value.trim();
    
        if (isSending || receiverId === "" || messageVal === "") return;
        isSending = true; 

        // Siapkan data json ringan
        const data = {
            receiver_id: receiverId,
            message: messageVal,
            reply_id: document.getElementById('reply_id').value
        };

        // Reset UI langsung agar terasa cepat
        inputField.value = ""; 
        window.cancelReply();
        isUserScrollingUp = false; 
        
        $.ajax({
            url: chatSendUrl,
            type: 'POST',
            data: data,
            success: function(response) {
                if (response.status === 'success') {
                    window.loadChat(); // Tarik pesan terbaru dari server
                } else {
                    alert("Gagal mengirim pesan.");
                }
                isSending = false; 
            },
            error: function(xhr, status, error) {
                alert("Gagal dikirim. Periksa koneksi internet.");
                isSending = false; 
            }
        });
    };

    window.saveEdit = () => {
        const newText = inputField.value.trim();
        if (isSending || newText === "" || selectedMsgId === null) return;

        isSending = true;
        
        $.ajax({
            url: chatEditUrl,
            type: 'POST',
            data: {
                msg_id: selectedMsgId,
                new_msg: newText
            },
            success: function(response) {
                if (response.status === 'success') {
                    window.cancelEdit(); 
                    window.loadChat();   
                }
                isSending = false;
            },
            error: function() {
                isSending = false;
            }
        });
    };

    if (form) {
        form.onsubmit = (e) => {
            e.preventDefault();
            const indicator = document.getElementById('edit-indicator');
            if (indicator && !indicator.classList.contains('hidden')) {
                window.saveEdit();
            } else {
                window.sendMessage();
            }
        };
    }

    // --- 4. POLLING CHAT OPTIMIZED (DYNAMIC TIMEOUT) ---
    window.loadChat = () => {
        if (pollingTimer) clearTimeout(pollingTimer); 

        const receiverId = document.getElementById('receiver_id').value;
        const chatBox = document.getElementById('messages-display');
        
        if (!receiverId || !chatBox) {
            pollingTimer = setTimeout(window.loadChat, 2000);
            return;
        }

        $.ajax({
            url: chatFetchUrl,
            type: 'POST',
            data: { receiver_id: receiverId },
            success: function(response) {
                if (chatBox.innerHTML !== response) {
                    chatBox.innerHTML = response;
                    if (!isUserScrollingUp) {
                        scrollToBottom();
                    }
                }
                pollingTimer = setTimeout(window.loadChat, 2000);
            },
            error: function() {
                pollingTimer = setTimeout(window.loadChat, 4000);
            }
        });
    };

    window.loadChat();

});

// --- 6. FUNGSI GLOBAL ---

window.openChat = function(id, name, avatar, status) {
    const receiverInput = document.getElementById('receiver_id');
    const inputField = document.getElementById('input-message');
    const sidePanel = document.getElementById('side-panel');
    const statusLabel = document.getElementById('chat-status-text');
    
    if(!receiverInput || !inputField) return;

    receiverInput.value = id;
    document.getElementById('header-avatar').src = avatar;
    document.getElementById('chat-with-name').innerText = name;
    
    if(statusLabel) {
        const currentStatus = status.toLowerCase();
        statusLabel.innerText = (currentStatus === 'online') ? 'Online' : 'Offline';
        statusLabel.className = (currentStatus === 'online') ? 
            'text-[10px] text-green-600 font-bold uppercase' : 
            'text-[10px] text-gray-400 font-bold uppercase';
    }

    if (window.innerWidth <= 768 && sidePanel) {
        sidePanel.style.transform = 'translateX(-100%)';
    }
    
    window.cancelEdit(); 
    window.cancelReply(); 
    isUserScrollingUp = false; 
    inputField.focus();
    window.loadChat(); 
};

window.showMsgOptions = (id, text) => {
    selectedMsgId = id;
    selectedMsgText = text;
    const msgModal = document.getElementById('msg-modal');
    if(msgModal) msgModal.classList.remove('hidden');
};

window.closeMsgModal = () => {
    const msgModal = document.getElementById('msg-modal');
    if(msgModal) msgModal.classList.add('hidden');
};

window.prepareReply = () => {
    window.closeMsgModal();
    const indicator = document.getElementById('reply-indicator');
    const previewText = document.getElementById('reply-text-preview');
    const replyInput = document.getElementById('reply_id');
    
    if(replyInput) replyInput.value = selectedMsgId;
    if(previewText) previewText.innerText = selectedMsgText;
    
    if(indicator) indicator.classList.remove('hidden');
    window.cancelEdit(); 
    const input = document.getElementById('input-message');
    if(input) input.focus();
};

window.cancelReply = () => {
    const replyInput = document.getElementById('reply_id');
    const indicator = document.getElementById('reply-indicator');
    if(replyInput) replyInput.value = "";
    if(indicator) indicator.classList.add('hidden');
};

window.prepareEdit = () => {
    window.closeMsgModal();
    const input = document.getElementById('input-message');
    const indicator = document.getElementById('edit-indicator');
    
    if(input) {
        input.value = selectedMsgText;
        input.focus();
    }
    if(indicator) indicator.classList.remove('hidden');
    window.cancelReply(); 
};

window.cancelEdit = () => {
    const input = document.getElementById('input-message');
    const indicator = document.getElementById('edit-indicator');
    if(input) input.value = "";
    if(indicator) indicator.classList.add('hidden');
    selectedMsgId = null;
};

window.confirmDelete = () => {
    if (confirm("Hapus pesan ini?")) {
        $.ajax({
            url: chatDeleteUrl,
            type: 'POST',
            data: { msg_id: selectedMsgId },
            success: function() {
                window.closeMsgModal();
                window.loadChat();
            }
        });
    }
};

window.uploadFile = (type) => {
    const fileInput = (type === 'image') ? document.getElementById('attach-image') : document.getElementById('attach-file');
    const receiverId = document.getElementById('receiver_id').value;
    if (!fileInput || !fileInput.files[0] || receiverId === "") return;

    let formData = new FormData();
    formData.append("file", fileInput.files[0]);
    formData.append("receiver_id", receiverId);
    formData.append("type", type);
    
    const replyId = document.getElementById('reply_id').value;
    if(replyId) formData.append("reply_id", replyId);

    const sendBtn = document.getElementById('send-btn');
    if(sendBtn) sendBtn.innerHTML = '<i class="fa-solid fa-spinner animate-spin"></i>';

    $.ajax({
        url: chatUploadUrl,
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        success: function(response) {
            if(sendBtn) sendBtn.innerHTML = '<i class="fa-solid fa-paper-plane text-sm"></i>';
            if (response.status === 'success') {
                window.cancelReply();
                isUserScrollingUp = false;
                window.loadChat();
                fileInput.value = ""; 
            }
        },
        error: function() {
            if(sendBtn) sendBtn.innerHTML = '<i class="fa-solid fa-paper-plane text-sm"></i>';
        }
    });
};

window.toggleEmojiPicker = () => {
    const picker = document.getElementById('emoji-picker');
    if (picker) {
        picker.classList.toggle('hidden');
        setTimeout(() => {
            const chatContainer = document.querySelector("#chat-container");
            if(chatContainer) chatContainer.scrollTop = chatContainer.scrollHeight;
        }, 50);
    }
};

window.addEmoji = (emoji) => {
    const input = document.getElementById('input-message');
    if(input) {
        input.value += emoji;
        input.focus();
    }
    const picker = document.getElementById('emoji-picker');
    if(picker) picker.classList.add('hidden');
};
