/**
 * ZALO CONFIG MANAGEMENT
 * Handles modal open/close and form submission for Zalo configs
 */

(function() {
    'use strict';

    const modal = document.getElementById('zalo-modal');
    const form = document.getElementById('zalo-form');
    const modalTitle = document.getElementById('zalo-modal-title');
    const submitBtn = document.getElementById('zalo-submit');
    const actionInput = document.getElementById('zalo-action');
    const idInput = document.getElementById('zalo-id');

    if (!modal || !form) {
        return;
    }

    // Form fields
    const codeRow = document.getElementById('zalo-code-row');
    const codeInput = document.getElementById('zalo-code');
    const nameRow = document.getElementById('zalo-name-row');
    const nameInput = document.getElementById('zalo-name');
    const qrRow = document.getElementById('zalo-qr-row');
    const userNumberRow = document.getElementById('zalo-user-number-row');
    const userNumberInput = document.getElementById('zalo-user-number');
    const messageNumberRow = document.getElementById('zalo-message-number-row');
    const messageNumberInput = document.getElementById('zalo-message-number');
    const tokenInput = document.getElementById('zalo-token');
    const linkQrInput = document.getElementById('zalo-link-qr');
    
    // QR upload elements
    const qrFileInput = document.getElementById('qr-image-upload');
    const qrPathInput = document.getElementById('qr-image-path');
    const qrPreview = document.getElementById('qr-preview');

    /**
     * Open modal for creating new Zalo config
     */
    function openCreateModal() {
        form.reset();
        actionInput.value = 'create';
        idInput.value = '0';
        
        // Hide Mã Bot field for create, Tên Bot and QR Upload shown side by side (2 columns)
        if (codeRow) codeRow.style.display = 'none';
        if (nameRow) nameRow.classList.remove('full');
        if (qrRow) qrRow.style.display = 'block';
        
        // Hide Số User and Số Tin Nhắn for create, set default value to 0
        if (userNumberRow) userNumberRow.style.display = 'none';
        if (userNumberInput) userNumberInput.value = '0';
        if (messageNumberRow) messageNumberRow.style.display = 'none';
        if (messageNumberInput) messageNumberInput.value = '0';
        
        // Reset QR preview
        if (qrFileInput) qrFileInput.value = '';
        if (qrPathInput) qrPathInput.value = '';
        if (linkQrInput) linkQrInput.value = '';
        if (qrPreview) qrPreview.style.display = 'none';
        
        const labelSave = submitBtn.getAttribute('data-label-save') || 'Lưu';
        submitBtn.textContent = labelSave;
        
        // Set modal title
        const messages = window.__MESSAGES__ || {};
        modalTitle.textContent = messages['zalo_form_heading'] || 'THÊM MỚI / CẬP NHẬT ZALO';
        
        modal.classList.add('show');
        modal.setAttribute('aria-hidden', 'false');
        
        // Focus first input
        setTimeout(() => {
            if (nameInput) nameInput.focus();
        }, 100);
    }

    /**
     * Open modal for editing existing Zalo config
     */
    function openEditModal(button) {
        form.reset();
        actionInput.value = 'update';
        
        // Get data from button attributes
        const id = button.getAttribute('data-zalo-id') || '0';
        const name = button.getAttribute('data-zalo-name') || '';
        const userNumber = button.getAttribute('data-zalo-user-number') || '0';
        const messageNumber = button.getAttribute('data-zalo-message-number') || '0';
        const token = button.getAttribute('data-zalo-token') || '';
        const linkQr = button.getAttribute('data-zalo-link-qr') || '';
        
        // Populate form
        idInput.value = id;
        
        // Show and populate Mã Bot field, Tên stays in column with QR Upload
        if (codeRow && codeInput) {
            codeRow.style.display = 'block';
            codeInput.value = 'BOT-' + String(id).padStart(4, '0');
        }
        if (nameRow) nameRow.classList.remove('full');
        if (qrRow) qrRow.style.display = 'block';
        
        // Hide Số User for edit, show only Số Tin Nhắn
        if (userNumberRow) userNumberRow.style.display = 'none';
        if (messageNumberRow) messageNumberRow.style.display = 'block';
        
        // Reset QR preview
        if (qrFileInput) qrFileInput.value = '';
        if (qrPathInput) qrPathInput.value = '';
        if (qrPreview) qrPreview.style.display = 'none';
        
        if (nameInput) nameInput.value = name;
        if (userNumberInput) userNumberInput.value = userNumber;
        if (messageNumberInput) messageNumberInput.value = messageNumber;
        if (tokenInput) tokenInput.value = token;
        if (linkQrInput) linkQrInput.value = linkQr;
        
        const labelUpdate = submitBtn.getAttribute('data-label-update') || 'Cập Nhật';
        submitBtn.textContent = labelUpdate;
        
        // Set modal title
        const messages = window.__MESSAGES__ || {};
        modalTitle.textContent = messages['zalo_form_heading'] || 'THÊM MỚI / CẬP NHẬT ZALO';
        
        modal.classList.add('show');
        modal.setAttribute('aria-hidden', 'false');
        
        // Focus first input
        setTimeout(() => {
            if (nameInput) nameInput.focus();
        }, 100);
    }

    /**
     * Close modal
     */
    function closeModal() {
        // Remove focus from any focused element inside modal before hiding
        if (document.activeElement && modal.contains(document.activeElement)) {
            document.activeElement.blur();
        }
        
        // Hide modal immediately to prevent white box flash
        modal.style.display = 'none';
        modal.style.visibility = 'hidden';
        modal.style.opacity = '0';
        modal.classList.remove('show');
        modal.setAttribute('aria-hidden', 'true');
        // Force reflow to ensure styles are applied
        void modal.offsetHeight;
        form.reset();
        
        // Reset to initial state: hide Mã Bot
        if (codeRow) codeRow.style.display = 'none';
        if (nameRow) nameRow.classList.remove('full');
        if (qrRow) qrRow.style.display = 'block';
        
        // Show Số User and Số Tin Nhắn (default state)
        if (userNumberRow) userNumberRow.style.display = 'block';
        if (messageNumberRow) messageNumberRow.style.display = 'block';
        
        // Reset QR preview
        if (qrFileInput) qrFileInput.value = '';
        if (qrPathInput) qrPathInput.value = '';
        if (linkQrInput) linkQrInput.value = '';
        if (qrPreview) qrPreview.style.display = 'none';
    }

    // Event listeners for "Thêm mới" buttons
    document.querySelectorAll('[data-zalo-open="create"]').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            openCreateModal();
        });
    });

    // Event listeners for "Sửa" buttons
    document.querySelectorAll('[data-zalo-edit]').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            openEditModal(this);
        });
    });

    // Event listeners for close buttons
    modal.querySelectorAll('[data-modal-close]').forEach(button => {
        button.addEventListener('click', closeModal);
    });

    // Close modal with Escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && modal.classList.contains('show')) {
            closeModal();
        }
    });

    // Form validation and AJAX submit
    form.addEventListener('submit', function(e) {
        e.preventDefault(); // Always prevent default to use AJAX
        
        const messages = window.__MESSAGES__ || {};
        const errorTitle = messages['error_notification_title'] || 'THÔNG BÁO';
        const successTitle = messages['success_notification_title'] || 'THÔNG BÁO';
        
        const name = nameInput ? nameInput.value.trim() : '';
        const token = tokenInput ? tokenInput.value.trim() : '';
        const qrPath = qrPathInput ? qrPathInput.value.trim() : '';
        
        // Validate Tên Bot
        if (!name) {
            const errorMsg = messages['zalo_error_name_required'] || 'Tên Bot không được để trống';
            const errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
            
            if (window.showToast) {
                window.showToast('error', errorWithHeader);
            } else {
                alert(errorMsg);
            }
            
            if (nameInput) nameInput.focus();
            return false;
        }
        
        // Validate Token
        if (!token) {
            const errorMsg = messages['zalo_error_token_required'] || 'Token không được để trống';
            const errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
            
            if (window.showToast) {
                window.showToast('error', errorWithHeader);
            } else {
                alert(errorMsg);
            }
            
            if (tokenInput) tokenInput.focus();
            return false;
        }
        
        // Validate QR Code (only for create mode)
        if (actionInput.value === 'create' && !qrPath) {
            const errorMsg = messages['zalo_error_qr_required'] || 'Vui lòng upload QR Code';
            const errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
            
            if (window.showToast) {
                window.showToast('error', errorWithHeader);
            } else {
                alert(errorMsg);
            }
            
            return false;
        }
        
        // All validations passed, submit via AJAX
        submitBtn.disabled = true;
        submitBtn.textContent = 'Đang xử lý...';
        
        const formData = new FormData(form);
        const postUrl = form.getAttribute('action') || form.action;
        
        fetch(postUrl, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'fetch',
                'Accept': 'application/json'
            },
            body: formData
        })
        .then(response => response.text())
        .then(text => {
            let json = null;
            try {
                json = text ? JSON.parse(text) : null;
            } catch (err) {
                // Non-JSON response
            }
            
            if (!json) {
                if (window.showToast) {
                    const errorMsg = 'Lỗi kết nối mạng';
                    const errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
                    window.showToast('error', errorWithHeader);
                }
                submitBtn.disabled = false;
                const labelSave = submitBtn.getAttribute('data-label-save') || 'Lưu';
                const labelUpdate = submitBtn.getAttribute('data-label-update') || 'Cập Nhật';
                submitBtn.textContent = actionInput.value === 'create' ? labelSave : labelUpdate;
                return;
            }
            
            if (json && json.ok) {
                // Success - close modal and reload page
                closeModal();
                // Mark body as reloading and hide all elements immediately
                document.body.classList.add('reloading');
                var elementsToHide = document.querySelectorAll('.modal-backdrop, .modal-overlay, .user-actions-dropdown, .page-loader');
                elementsToHide.forEach(function(el) {
                    el.style.display = 'none';
                    el.style.visibility = 'hidden';
                    el.style.opacity = '0';
                    el.classList.remove('show');
                });
                // Force reflow to ensure styles are applied
                void document.body.offsetHeight;
                // Add critical CSS to prevent flash
                var style = document.createElement('style');
                style.id = 'reload-prevent-flash';
                style.textContent = '* { transition: none !important; animation: none !important; } .page-loader, .modal-backdrop, .modal-overlay { display: none !important; visibility: hidden !important; opacity: 0 !important; }';
                document.head.appendChild(style);
                // Use requestAnimationFrame to ensure DOM is updated before reload
                const msg = encodeURIComponent(json.message || '');
                requestAnimationFrame(function() {
                    requestAnimationFrame(function() {
                        location.href = 'index.php?zalo&success=' + msg;
                    });
                });
            } else {
                // Error - show message and keep modal open
                const err = (json && json.message) ? String(json.message) : 'Có lỗi xảy ra';
                const errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + err;
                
                if (window.showToast) {
                    window.showToast('error', errorWithHeader);
                }
                
                submitBtn.disabled = false;
                const labelSave = submitBtn.getAttribute('data-label-save') || 'Lưu';
                const labelUpdate = submitBtn.getAttribute('data-label-update') || 'Cập Nhật';
                submitBtn.textContent = actionInput.value === 'create' ? labelSave : labelUpdate;
            }
        })
        .catch(error => {
            if (window.showToast) {
                const errorMsg = 'Lỗi kết nối mạng';
                const errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
                window.showToast('error', errorWithHeader);
            }
            submitBtn.disabled = false;
            const labelSave = submitBtn.getAttribute('data-label-save') || 'Lưu';
            const labelUpdate = submitBtn.getAttribute('data-label-update') || 'Cập Nhật';
            submitBtn.textContent = actionInput.value === 'create' ? labelSave : labelUpdate;
        });
    });

})();

