// Wizard Modal Variables
let currentStep = 1;
let selectedCommentType = '';
let commentData = {}

// Show result modal
function showResultModal(activity) {
    const modal = document.getElementById('resultModal');
    
    // Update modal content
    document.getElementById('resultSubject').textContent = activity.subject;
    document.getElementById('resultDescription').textContent = activity.description;
    document.getElementById('resultType').textContent = activity.type;
    document.getElementById('resultDate').textContent = activity.activity_date;
    
    // Show modal
    modal.classList.add('show');
}

// Close result modal
function closeResultModal() {
    const modal = document.getElementById('resultModal');
    modal.classList.remove('show');
}

// Event listeners for result modal
document.addEventListener('DOMContentLoaded', function() {
    const resultModal = document.getElementById('resultModal');
    const closeBtn = document.querySelector('.result-close-btn');
    const okBtn = document.querySelector('.result-btn-primary');
    
    if (closeBtn) {
        closeBtn.addEventListener('click', closeResultModal);
    }
    
    if (okBtn) {
        okBtn.addEventListener('click', closeResultModal);
    }
    
    // Close modal when clicking outside
    if (resultModal) {
        resultModal.addEventListener('click', function(e) {
            if (e.target === resultModal) {
                closeResultModal();
            }
        });
    }
});;

// Open Comment Wizard
function openCommentWizard() {
    const modal = document.getElementById('commentWizardModal');
    
    // Reset wizard state
    currentStep = 1;
    selectedCommentType = '';
    commentData = {};
    
    // Reset UI
    resetWizardSteps();
    updateProgressSteps();
    updateNavigationButtons();
    
    // Set current date/time
    const now = new Date();
    const localDateTime = now.toISOString().slice(0, 16);
    document.getElementById('commentDate').value = localDateTime;
    
    // Show modal with animation
    modal.style.display = 'flex';
    setTimeout(() => {
        modal.classList.add('show');
    }, 10);
}

// Close Comment Wizard
function closeCommentWizard() {
    const modal = document.getElementById('commentWizardModal');
    modal.classList.remove('show');
    
    setTimeout(() => {
        modal.style.display = 'none';
        resetWizardSteps();
    }, 300);
}

// Reset wizard to initial state
function resetWizardSteps() {
    // Reset steps
    document.querySelectorAll('.wizard-step').forEach(step => {
        step.classList.remove('active');
    });
    document.querySelector('.wizard-step[data-step="1"]').classList.add('active');
    
    // Reset progress
    document.querySelectorAll('.progress-step').forEach(step => {
        step.classList.remove('active', 'completed');
    });
    document.querySelector('.progress-step[data-step="1"]').classList.add('active');
    
    // Reset form
    document.getElementById('commentForm').reset();
    
    // Reset selected type
    document.querySelectorAll('.comment-type-card').forEach(card => {
        card.classList.remove('selected');
    });
    
    currentStep = 1;
    selectedCommentType = '';
}

// Update progress steps visual state
function updateProgressSteps() {
    document.querySelectorAll('.progress-step').forEach(step => {
        const stepNumber = parseInt(step.dataset.step);
        
        step.classList.remove('active', 'completed');
        
        if (stepNumber < currentStep) {
            step.classList.add('completed');
        } else if (stepNumber === currentStep) {
            step.classList.add('active');
        }
    });
}

// Update navigation buttons
function updateNavigationButtons() {
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');
    const saveBtn = document.getElementById('saveBtn');
    
    // Previous button
    if (currentStep === 1) {
        prevBtn.style.display = 'none';
    } else {
        prevBtn.style.display = 'block';
    }
    
    // Next/Save buttons
    if (currentStep === 3) {
        nextBtn.style.display = 'none';
        saveBtn.style.display = 'block';
    } else {
        nextBtn.style.display = 'block';
        saveBtn.style.display = 'none';
    }
    
    // Enable/disable next button based on step validation
    nextBtn.disabled = !validateCurrentStep();
}

// Validate current step
function validateCurrentStep() {
    switch (currentStep) {
        case 1:
            return selectedCommentType !== '';
        case 2:
            const subject = document.getElementById('commentSubject').value.trim();
            const description = document.getElementById('commentDescription').value.trim();
            return subject !== '' && description !== '';
        case 3:
            return true;
        default:
            return false;
    }
}

// Next step
function nextStep() {
    if (!validateCurrentStep()) {
        return;
    }
    
    if (currentStep < 3) {
        // Save current step data
        saveStepData();
        
        // Move to next step
        currentStep++;
        showStep(currentStep);
        updateProgressSteps();
        updateNavigationButtons();
        
        // Update preview if on step 3
        if (currentStep === 3) {
            updatePreview();
        }
    }
}

// Previous step
function previousStep() {
    if (currentStep > 1) {
        currentStep--;
        showStep(currentStep);
        updateProgressSteps();
        updateNavigationButtons();
    }
}

// Show specific step
function showStep(stepNumber) {
    document.querySelectorAll('.wizard-step').forEach(step => {
        step.classList.remove('active');
    });
    
    document.querySelector(`.wizard-step[data-step="${stepNumber}"]`).classList.add('active');
}

// Save current step data
function saveStepData() {
    switch (currentStep) {
        case 1:
            commentData.type = selectedCommentType;
            break;
        case 2:
            commentData.subject = document.getElementById('commentSubject').value.trim();
            commentData.description = document.getElementById('commentDescription').value.trim();
            commentData.date = document.getElementById('commentDate').value;
            break;
    }
}

// Update preview in step 3
function updatePreview() {
    const typeNames = {
        'call': '📞 Llamada',
        'email': '📧 Email',
        'meeting': '🤝 Reunión',
        'note': '📝 Nota'
    };
    
    document.getElementById('previewType').textContent = typeNames[commentData.type] || '';
    document.getElementById('previewSubject').textContent = commentData.subject || '';
    document.getElementById('previewDescription').textContent = commentData.description || '';
    
    // Format date
    if (commentData.date) {
        const date = new Date(commentData.date);
        const formattedDate = date.toLocaleString('es-ES', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
        document.getElementById('previewDate').textContent = formattedDate;
    }
}

// Save comment to database
async function saveComment() {
    const saveBtn = document.getElementById('saveBtn');
    
    // Show loading state
    saveBtn.classList.add('loading');
    saveBtn.disabled = true;
    
    try {
        // Validate required data
        if (!window.leadData || !window.leadData.id) {
            throw new Error('ID del lead no disponible');
        }
        
        if (!commentData.type || !commentData.subject || !commentData.description) {
            throw new Error('Faltan datos requeridos del comentario');
        }
        
        // Prepare data for API
        const formData = {
            lead_id: window.leadData.id,
            type: commentData.type,
            subject: commentData.subject,
            description: commentData.description,
            activity_date: commentData.date
            // Nota: no enviar created_by; el backend usa la sesión del usuario
        };
        
        console.log('Enviando datos:', formData);
        
        // Send to server with correct module path
        const response = await fetch('modules/leads/add_note.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify(formData)
        });
        
        console.log('Response status:', response.status);
        
        if (response.ok) {
            // Obtener el texto crudo primero para debugging
            const responseText = await response.text();
            console.log('Response text:', responseText);
            
            try {
                const result = JSON.parse(responseText);
                console.log('Response data:', result);
                
                if (result.success) {
                    // Show result modal instead of adding to timeline
                    showResultModal(result.activity);
                    
                    // Close wizard
                    closeCommentWizard();
                    
                    // Agregar la nueva actividad al timeline en tiempo real
                    if (result.activity) {
                        addActivityToTimeline(result.activity);
                    }
                    // Actualizar el contador de actividades si existe
                    try {
                        const newTotal = (window.leadData?.totalActivities || 0) + 1;
                        window.leadData = Object.assign({}, window.leadData, { totalActivities: newTotal });
                        updateActivityCount(newTotal);
                    } catch (e) {}
                } else {
                    throw new Error(result.message || 'Error al guardar el comentario');
                }
            } catch (jsonError) {
                console.error('Error al parsear JSON:', jsonError);
                console.error('Texto de respuesta:', responseText);
                throw new Error(`Error al procesar la respuesta del servidor: ${jsonError.message}. Respuesta cruda: ${responseText.substring(0, 200)}`);
            }
        } else {
            const errorText = await response.text();
            console.error('Server error response:', errorText);
            throw new Error(`Error del servidor (${response.status}): ${errorText}`);
        }
        
    } catch (error) {
        console.error('Error completo:', error);
        showNotification('❌ Error al agregar el comentario: ' + error.message, 'error');
    } finally {
        // Reset button state
        saveBtn.classList.remove('loading');
        saveBtn.disabled = false;
    }
}

// Add activity to timeline (enhanced version)
function addActivityToTimeline(activityData) {
    const timeline = document.getElementById('activityTimeline');
    
    if (!timeline) {
        console.warn('Timeline element not found');
        return;
    }
    
    // Create timeline header if it doesn't exist
    if (!timeline.querySelector('.timeline-header')) {
        const header = document.createElement('div');
        header.className = 'timeline-header';
        header.innerHTML = `
            <div class="timeline-column">Fecha de Creación</div>
            <div class="timeline-column">Actividad</div>
            <div class="timeline-column">Comentario</div>
            <div class="timeline-column">Creado Por</div>
        `;
        timeline.appendChild(header);
    }
    
    // Create new activity row
    const activityRow = document.createElement('div');
    activityRow.className = 'timeline-row new-activity';
    
    // Format date
    const activityDate = activityData.activity_date ? 
        new Date(activityData.activity_date).toLocaleString('es-ES', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        }) : 
        new Date().toLocaleString('es-ES', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    
    // Activity type icons
    const typeIcons = {
        'call': '📞',
        'email': '📧',
        'meeting': '🤝',
        'note': '📝'
    };
    
    const typeNames = {
        'call': 'Llamada',
        'email': 'Email',
        'meeting': 'Reunión',
        'note': 'Nota'
    };
    
    activityRow.innerHTML = `
        <div class="timeline-column">
            <span class="activity-date">${activityDate}</span>
        </div>
        <div class="timeline-column">
            <div class="activity-type">
                <span class="activity-icon">${typeIcons[activityData.type] || '📝'}</span>
                <span class="activity-name">${typeNames[activityData.type] || 'Actividad'}</span>
            </div>
        </div>
        <div class="timeline-column">
            <div class="activity-description">${activityData.description}</div>
        </div>
        <div class="timeline-column">
            <span class="activity-user">${activityData.creator_name || activityData.creator_username || window.currentUserName || 'Usuario'}</span>
        </div>
    `;
    
    // Insert at the beginning (after header)
    const header = timeline.querySelector('.timeline-header');
    if (header && header.nextSibling) {
        timeline.insertBefore(activityRow, header.nextSibling);
    } else {
        timeline.appendChild(activityRow);
    }

    // Aplicar clamp y toggle al nuevo comentario
    try {
        const desc = activityRow.querySelector('.activity-description');
        if (desc) {
            desc.classList.add('clamped');
            const textLen = (desc.textContent || '').trim().length;
            if (textLen > 160) {
                const toggle = document.createElement('button');
                toggle.className = 'description-toggle';
                toggle.type = 'button';
                toggle.textContent = 'Ver más';
                toggle.addEventListener('click', () => {
                    const expanded = desc.classList.toggle('expanded');
                    if (expanded) {
                        desc.classList.remove('clamped');
                        toggle.textContent = 'Ver menos';
                    } else {
                        desc.classList.add('clamped');
                        toggle.textContent = 'Ver más';
                    }
                    // Recalcular altura del panel para evitar cortes
                    recalculateActivityPanelHeight();
                });
                desc.insertAdjacentElement('afterend', toggle);
                desc.dataset.toggleBound = '1';
            }
        }
    } catch (e) { console.warn('Clamp toggle failed:', e); }

    // Mantener sólo 5 actividades visibles en la página actual
    try {
        const rows = timeline.querySelectorAll('.timeline-row');
        if (rows.length > 5) {
            const last = rows[rows.length - 1];
            if (last) last.remove();
        }
    } catch (e) {}
    
    // Add animation
    setTimeout(() => {
        activityRow.classList.add('animate-in');
    }, 100);
    
    // Remove new-activity class after animation
    setTimeout(() => {
        activityRow.classList.remove('new-activity');
    }, 1000);

    // Recalcular altura del panel tras insertar el nuevo elemento
    recalculateActivityPanelHeight();

    // Refrescar paginación tras añadir una actividad (mantener página activa)
    try {
        // Incrementar contador en memoria si existe
        if (window.leadData) {
            const perPage = window.leadData.per_page || 5;
            const current = Number(window.leadData.totalActivities) || 0;
            window.leadData.totalActivities = current + 1;
            window.leadData.totalPages = Math.max(1, Math.ceil(window.leadData.totalActivities / perPage));
        }
        // Recargar controles desde servidor para mantener HTML y estado correctos
        const currentPage = window.leadData?.currentPage || 1;
        setTimeout(() => loadActivitiesPage(currentPage), 350);
    } catch (e) { /* noop */ }

    // Actualizar encabezado "Última actividad" en tiempo real
    try {
        const lastActivityEl = document.getElementById('lastActivityValue');
        if (lastActivityEl && activityDate) {
            lastActivityEl.textContent = activityDate;
        }
    } catch (e) { /* noop */ }
}

// Show notification
function showNotification(message, type = 'info') {
    // Remove existing notifications
    document.querySelectorAll('.notification').forEach(n => n.remove());
    
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    // Style the notification
    Object.assign(notification.style, {
        position: 'fixed',
        top: '20px',
        right: '20px',
        padding: '16px 24px',
        borderRadius: '8px',
        color: 'white',
        fontWeight: '600',
        zIndex: '10000',
        transform: 'translateX(100%)',
        transition: 'transform 0.3s ease',
        maxWidth: '400px',
        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.2)'
    });
    
    // Set background color based on type
    const colors = {
        'success': '#28a745',
        'error': '#dc3545',
        'info': '#007bff',
        'warning': '#ffc107'
    };
    
    notification.style.background = colors[type] || colors.info;
    
    document.body.appendChild(notification);
    
    // Animate in
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // Auto remove after 5 seconds
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 5000);
}

// Event Listeners
document.addEventListener('DOMContentLoaded', function() {
    // Comment type selection
    document.querySelectorAll('.comment-type-card').forEach(card => {
        card.addEventListener('click', function() {
            // Remove previous selection
            document.querySelectorAll('.comment-type-card').forEach(c => {
                c.classList.remove('selected');
            });
            
            // Select current card
            this.classList.add('selected');
            selectedCommentType = this.dataset.type;
            
            // Update navigation
            updateNavigationButtons();
        });
    });
    
    // Form input validation (guard when elements are not present yet)
    const subjectEl = document.getElementById('commentSubject');
    if (subjectEl) {
        subjectEl.addEventListener('input', updateNavigationButtons);
    }
    const descriptionEl = document.getElementById('commentDescription');
    if (descriptionEl) {
        descriptionEl.addEventListener('input', updateNavigationButtons);
    }

    // Prevent form submission
    const commentFormEl = document.getElementById('commentForm');
    if (commentFormEl) {
        commentFormEl.addEventListener('submit', function(e) {
            e.preventDefault();
        });
    }

    // Close modal on outside click
    const commentWizardModalEl = document.getElementById('commentWizardModal');
    if (commentWizardModalEl) {
        commentWizardModalEl.addEventListener('click', function(e) {
            if (e.target === this) {
                closeCommentWizard();
            }
        });
    }
    
    // Escape key to close modal
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const modal = document.getElementById('commentWizardModal');
            if (modal && modal.classList.contains('show')) {
                closeCommentWizard();
            }
        }
    });
});

// Update quick action cards to use new wizard
document.addEventListener('DOMContentLoaded', function() {
    // Update "Agregar Notas" card
    const addNotesCard = document.querySelector('[onclick*="openNoteModal"]');
    if (addNotesCard) {
        addNotesCard.setAttribute('onclick', 'openCommentWizard()');
    }
    
    // Update other activity cards if they exist
    const activityCards = document.querySelectorAll('[onclick*="openActivityModal"]');
    activityCards.forEach(card => {
        card.setAttribute('onclick', 'openCommentWizard()');
    });
});

// Global variables for lead data
// Note: These should be set by PHP in the main view file
window.currentUserId = window.currentUserId || 1;
window.currentUserName = window.currentUserName || 'Usuario';

// Función para cargar actividades con AJAX
function loadActivitiesPage(page) {
    const leadId = window.leadData?.id;
    if (!leadId) return;
    
    // Mostrar indicador de carga
    const timeline = document.getElementById('activityTimeline');
    if (timeline) {
        timeline.innerHTML = '<div class="loading-activities">Cargando actividades...</div>';
    }
    
    fetch(`modules/leads/load_activities_ajax.php?lead_id=${leadId}&page=${page}`, {
        method: 'GET',
        credentials: 'same-origin', // Incluir cookies de sesión
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Actualizar el contenido del timeline
                if (timeline) {
                    timeline.innerHTML = data.html;
                }
                
                // Sincronizar estado de paginación en memoria
                if (!window.leadData) window.leadData = {};
                window.leadData.currentPage = Number(data.current_page) || Number(page) || 1;
                window.leadData.totalPages = Number(data.total_pages) || window.leadData.totalPages || 1;
                window.leadData.totalActivities = Number(data.total_activities) || window.leadData.totalActivities || 0;
                window.leadData.per_page = window.leadData.per_page || 5;

                // Asegurar y refrescar controles de paginación
                refreshPaginationControls(data.pagination_html, window.leadData.currentPage, window.leadData.totalPages);
                
                // Actualizar el contador si existe
                updateActivityCount(data.total_activities);

                // Inicializar toggles de descripción tras carga AJAX
                initializeDescriptionToggles();

                // Recalcular altura del panel tras recargar contenido
                recalculateActivityPanelHeight();
            } else {
                showNotification(data.message || 'Error al cargar actividades', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('Error al cargar actividades', 'error');
        });
}

// Función para actualizar el contador de actividades
function updateActivityCount(count) {
    // Buscar elementos que puedan mostrar el contador de actividades
    const statCards = document.querySelectorAll('.stat-card');
    statCards.forEach(card => {
        const label = card.querySelector('.stat-label');
        if (label && (label.textContent.includes('Actividades') || label.textContent.includes('Actividad'))) {
            const number = card.querySelector('.stat-number');
            if (number) {
                number.textContent = count || '0';
            }
        }
    });
}

// Agregar estilos CSS para la paginación y carga
const ajaxStyles = document.createElement('style');
ajaxStyles.textContent = `
    .loading-activities {
        text-align: center;
        padding: 40px;
        color: #666;
        font-size: 16px;
    }
    
    .pagination-container {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 8px;
        margin-top: 20px;
        flex-wrap: wrap;
    }
    
    .pagination-btn {
        padding: 8px 12px;
        border: 1px solid #ddd;
        background: white;
        color: #333;
        border-radius: 6px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.2s ease;
        min-width: 40px;
    }
    
    .pagination-btn:hover {
        background-color: #f8f9fa;
        border-color: #007bff;
        color: #007bff;
    }
    
    .pagination-btn.pagination-active {
        background-color: #007bff;
        color: white;
        border-color: #007bff;
    }
    
    .pagination-btn.pagination-active:hover {
        background-color: #0056b3;
        border-color: #0056b3;
    }
    
    .pagination-btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }
    
    .pagination-dots {
        padding: 8px 4px;
        color: #666;
        font-size: 14px;
    }
    
    .pagination-prev, .pagination-next {
        font-weight: 500;
        padding: 8px 16px;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .new-activity {
        animation: fadeIn 0.5s ease-in;
    }
`;
document.head.appendChild(ajaxStyles);

// Helpers de paginación
function ensurePaginationContainer() {
    let container = document.querySelector('.pagination-controls');
    if (!container) {
        const timelineEl = document.getElementById('activityTimeline');
        if (timelineEl) {
            container = document.createElement('div');
            container.className = 'pagination-controls pagination-container';
            timelineEl.insertAdjacentElement('afterend', container);
        }
    }
    return container;
}

function refreshPaginationControls(paginationHtml, currentPage, totalPages) {
    const container = ensurePaginationContainer();
    if (!container) return;
    if (paginationHtml) {
        container.innerHTML = paginationHtml;
    }
    // En caso de que el HTML no incluya estado, dejamos el manejo al servidor
    // y a los onclick ya presentes en los botones.
}

// Status Update Functionality
document.addEventListener('DOMContentLoaded', function() {
    // Inicializar toggles de descripción en carga inicial
    initializeDescriptionToggles();

    const statusSelect = document.getElementById('lead-status-select');
    
    if (statusSelect) {
        statusSelect.addEventListener('change', function() {
            const leadId = this.getAttribute('data-lead-id');
            const newStatus = this.value;
            const originalStatus = this.getAttribute('data-original-status') || window.leadData?.status;
            
            // Store original status if not already stored
            if (!this.getAttribute('data-original-status')) {
                this.setAttribute('data-original-status', originalStatus);
            }
            
            updateLeadStatus(leadId, newStatus, originalStatus, this);
        });
    }
});

// Inicializador de toggles para descripciones largas en timeline
function initializeDescriptionToggles() {
    try {
        const timeline = document.getElementById('activityTimeline');
        if (!timeline) return;

        const descriptions = timeline.querySelectorAll('.activity-description');
        descriptions.forEach(desc => {
            if (!desc) return;
            // Evitar duplicar
            if (desc.dataset.toggleBound === '1') return;

            // Aplicar modo clamped por defecto
            desc.classList.add('clamped');

            // Decidir si necesita toggle (más de 160 caracteres)
            const textLen = (desc.textContent || '').trim().length;
            const needsToggle = textLen > 160;

            if (needsToggle) {
                const toggle = document.createElement('button');
                toggle.className = 'description-toggle';
                toggle.type = 'button';
                toggle.textContent = 'Ver más';
                toggle.addEventListener('click', () => {
                    const expanded = desc.classList.toggle('expanded');
                    if (expanded) {
                        desc.classList.remove('clamped');
                        toggle.textContent = 'Ver menos';
                    } else {
                        desc.classList.add('clamped');
                        toggle.textContent = 'Ver más';
                    }
                    // Recalcular altura del panel al expandir/contraer
                    recalculateActivityPanelHeight();
                });
                // Insertar justo después del texto
                desc.insertAdjacentElement('afterend', toggle);
                desc.dataset.toggleBound = '1';
            }
        });
    } catch (e) {
        console.warn('initializeDescriptionToggles error:', e);
    }
}

// Utilidad: recalcular la altura del panel de actividades para evitar recortes
function recalculateActivityPanelHeight() {
    try {
        const panel = document.getElementById('activity-panel');
        if (!panel) return;
        const content = panel.querySelector('.collapsible-content');
        if (!content) return;

        // Si el panel está abierto, ajustar su maxHeight al contenido actual
        const isOpen = panel.classList.contains('is-open');
        if (isOpen) {
            content.style.maxHeight = content.scrollHeight + 'px';
            content.style.opacity = '1';
        }
    } catch (e) {
        console.warn('No se pudo recalcular la altura del panel:', e);
    }
}

// Function to update lead status via AJAX
async function updateLeadStatus(leadId, newStatus, originalStatus, selectElement) {
    // Show loading state
    selectElement.disabled = true;
    selectElement.style.opacity = '0.6';
    
    // Create loading indicator
    const loadingIndicator = document.createElement('div');
    loadingIndicator.className = 'status-loading';
    loadingIndicator.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Actualizando...';
    loadingIndicator.style.cssText = `
        position: absolute;
        background: rgba(255, 255, 255, 0.9);
        padding: 5px 10px;
        border-radius: 4px;
        font-size: 12px;
        color: #666;
        border: 1px solid #ddd;
        z-index: 1000;
        margin-top: 5px;
    `;
    selectElement.parentNode.appendChild(loadingIndicator);
    
    try {
        const formData = new FormData();
        formData.append('lead_id', leadId);
        formData.append('status', newStatus);
        
        const response = await fetch('modules/leads/update_status.php', {
            method: 'POST',
            body: formData,
            credentials: 'same-origin',
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        
        const result = await response.json();
        
        if (result.success) {
            // Update successful
            showStatusUpdateSuccess(newStatus, originalStatus);
            
            // Update the original status to the new one
            selectElement.setAttribute('data-original-status', newStatus);
            
            // Update window.leadData if it exists
            if (window.leadData) {
                window.leadData.status = newStatus;
            }
            
            // Update any status badges or indicators on the page
            updateStatusIndicators(newStatus);
            
            // Log success
            if (window.errorLogger) {
                window.errorLogger.log(`Status actualizado: ${originalStatus} → ${newStatus}`, 'Status Update');
            }
            
        } else {
            // Update failed
            showStatusUpdateError(result.message || 'Error desconocido');
            
            // Revert select to original status
            selectElement.value = originalStatus;
            
            // Log error
            if (window.errorLogger) {
                window.errorLogger.log(`Error actualizando status: ${result.message}`, 'Status Error');
            }
        }
        
    } catch (error) {
        // Network or other error
        showStatusUpdateError('Error de conexión: ' + error.message);
        
        // Revert select to original status
        selectElement.value = originalStatus;
        
        // Log error
        if (window.errorLogger) {
            window.errorLogger.log(`Error de red actualizando status: ${error.message}`, 'Network Error');
        }
        
    } finally {
        // Remove loading state
        selectElement.disabled = false;
        selectElement.style.opacity = '1';
        
        // Remove loading indicator
        if (loadingIndicator && loadingIndicator.parentNode) {
            loadingIndicator.parentNode.removeChild(loadingIndicator);
        }
    }
}

// Show success notification
function showStatusUpdateSuccess(newStatus, oldStatus) {
    const notification = document.createElement('div');
    notification.className = 'status-notification success';
    notification.innerHTML = `
        <i class="fas fa-check-circle"></i>
        <span>Estado actualizado: <strong>${formatStatusName(oldStatus)}</strong> → <strong>${formatStatusName(newStatus)}</strong></span>
    `;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
        border-radius: 8px;
        padding: 12px 16px;
        font-size: 14px;
        z-index: 10000;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        animation: slideInRight 0.3s ease-out;
    `;
    
    document.body.appendChild(notification);
    
    // Auto remove after 3 seconds
    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.3s ease-in';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

// Show error notification
function showStatusUpdateError(message) {
    const notification = document.createElement('div');
    notification.className = 'status-notification error';
    notification.innerHTML = `
        <i class="fas fa-exclamation-circle"></i>
        <span>Error: ${message}</span>
    `;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
        border-radius: 8px;
        padding: 12px 16px;
        font-size: 14px;
        z-index: 10000;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        animation: slideInRight 0.3s ease-out;
    `;
    
    document.body.appendChild(notification);
    
    // Auto remove after 5 seconds
    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.3s ease-in';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 5000);
}

// Format status name for display
function formatStatusName(status) {
    if (!status) return '';
    return status.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
}

// Update status indicators throughout the page
function updateStatusIndicators(newStatus) {
    // Update any status badges
    const statusBadges = document.querySelectorAll('.status-badge, .lead-status');
    statusBadges.forEach(badge => {
        if (badge.textContent && badge.textContent.trim()) {
            badge.textContent = formatStatusName(newStatus);
            
            // Update badge classes if they exist
            const statusClasses = {
                'new': 'bg-blue-100 text-blue-800',
                'contacted': 'bg-yellow-100 text-yellow-800',
                'qualified': 'bg-green-100 text-green-800',
                'demo_scheduled': 'bg-purple-100 text-purple-800',
                'demo_completed': 'bg-indigo-100 text-indigo-800',
                'deposit_pending': 'bg-orange-100 text-orange-800',
                'deposited': 'bg-emerald-100 text-emerald-800',
                'active_trader': 'bg-teal-100 text-teal-800',
                'inactive': 'bg-gray-100 text-gray-800',
                'closed_lost': 'bg-red-100 text-red-800'
            };
            
            // Remove old status classes
            Object.values(statusClasses).forEach(cls => {
                badge.classList.remove(...cls.split(' '));
            });
            
            // Add new status class
            const newClasses = statusClasses[newStatus] || statusClasses['new'];
            badge.classList.add(...newClasses.split(' '));
        }
    });
}

// Add CSS animations
const statusAnimationCSS = `
@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes slideOutRight {
    from {
        transform: translateX(0);
        opacity: 1;
    }
    to {
        transform: translateX(100%);
        opacity: 0;
    }
}

.status-notification {
    display: flex;
    align-items: center;
    gap: 8px;
}

.status-notification i {
    font-size: 16px;
}

.status-loading {
    display: flex;
    align-items: center;
    gap: 5px;
}
`;

// Inject CSS
const statusStyleSheet = document.createElement('style');
statusStyleSheet.textContent = statusAnimationCSS;
document.head.appendChild(statusStyleSheet);