let signaturePads = [];

function disableInputs() {
	const inputs = document.querySelectorAll('input');
	inputs.forEach(input => {
		input.disabled = true;
	});
	const textareas = document.querySelectorAll('textarea');
	textareas.forEach(textarea => {
		textarea.disabled = true;
	});
	const selects = document.querySelectorAll('select');
	selects.forEach(select => {
		select.disabled = true;
	});
}

// Show Toast Message
function showToast(message, duration = 3000) {	
	let toast = document.createElement('div');
	toast.id = 'toast';
	toast.className = 'toast hidden';
	document.body.appendChild(toast);
	toast.textContent = message;
	toast.classList.remove('hidden');
	toast.classList.add('visible');

	setTimeout(() => {
		toast.classList.remove('visible');
		setTimeout(() => {
			toast.classList.add('hidden');
		}, 300);
	}, duration);
}

function hideLoadingSpinner() {
	document.getElementById('loading-spinner').style.display = 'none';
}

function showLoadingSpinner() {
	document.getElementById('loading-spinner').style.display = 'flex';
}

function toggleNonPrintableElements(show) {
    const displayStyle = show ? '' : 'none';
    const borderStyle = show ? '1px solid #000' : 'none';
    const textareaBorderStyle = show ? '1px solid #ccc' : 'none';

    const clearSignatureButton = document.getElementById('clear-signature');
    const floatingButtons = document.querySelectorAll('.floating-btn-pdf');
    const signaturePadElement = document.querySelector('.signature-pad');
    const dynamicTextareas = document.querySelectorAll('.dynamicTextarea');

    if (clearSignatureButton) {
        clearSignatureButton.style.display = displayStyle;
    }
    floatingButtons.forEach(button => {
        button.style.display = displayStyle;
    });
    if (signaturePadElement) {
        signaturePadElement.style.border = borderStyle;
    }
    dynamicTextareas.forEach(textarea => textarea.style.border = textareaBorderStyle);
}
function adjustCommentsFontSize() {
    const textarea = document.getElementById('comentarios');
    if (!textarea) return;
    
    // Reset font size to default
    textarea.style.fontSize = '14px';
    
    // Get the scrollHeight (total height of content)
    const scrollHeight = textarea.scrollHeight;
    const maxHeight = 190; // Fixed max height in pixels
    
    // If content exceeds max height, reduce font size
    if (scrollHeight > maxHeight) {
        // Calculate how much we need to reduce the font
        const ratio = maxHeight / scrollHeight;
        const newSize = Math.max(8, Math.floor(14 * ratio)); // Don't go below 8px
        textarea.style.fontSize = newSize + 'px';
        
        // Check if even with the smallest font we exceed max height
        if (newSize === 8 && textarea.scrollHeight > maxHeight) {
            // Set to 8px to check final height
            textarea.style.fontSize = '8px';
            // If still exceeds, we'll handle this in the input event
        }
    }
    
    // Ajustar la altura del textarea al contenido
    textarea.style.height = 'auto';
    textarea.style.height = Math.min(textarea.scrollHeight, maxHeight) + 'px';
}

function countLinesInTextarea(textarea) {
    // Create a mirror div with the same width and styling
    const mirror = document.createElement('div');
    mirror.style.position = 'absolute';
    mirror.style.left = '-9999px';
    mirror.style.width = textarea.clientWidth + 'px';
    mirror.style.font = window.getComputedStyle(textarea).font;
    mirror.style.lineHeight = window.getComputedStyle(textarea).lineHeight;
    mirror.style.whiteSpace = 'pre-wrap';
    mirror.style.wordBreak = 'break-word';
    document.body.appendChild(mirror);
    
    // Get text and replace newlines with <br>
    const text = textarea.value.replace(/\n/g, '<br>');
    mirror.innerHTML = text + '.'; // Add a period to account for a trailing empty line
    
    // Count the lines
    const lineHeight = parseInt(window.getComputedStyle(textarea).lineHeight);
    const lines = Math.ceil(mirror.clientHeight / lineHeight);
    
    // Clean up
    document.body.removeChild(mirror);
    
    return lines;
}

function generatePDF(callback = null) {
    // Return a Promise instead of using callback
    return new Promise((resolve, reject) => {
        try {
            // Mostrar spinner de carga
            document.getElementById('loading-spinner').style.display = 'flex';
            
            // Ocultar botones para la captura
            const saveBtn = document.getElementById('guardarAvance');
            const pdfBtn = document.getElementById('descargarPdf');
            
            if (saveBtn) saveBtn.style.display = 'none';
            if (pdfBtn) pdfBtn.style.display = 'none';
            
            // Hide non-printable elements before capturing
            toggleNonPrintableElements(false);
            
            // Use setTimeout to ensure DOM updates are complete before rendering
            setTimeout(() => {
                // Configuración mejorada para html2canvas
                const options = {
                    scale: 2, // Mayor escala para mejor calidad
                    useCORS: true, // Permitir cargar imágenes de otros dominios
                    allowTaint: true, // Permitir elementos "tainted" para mejor renderizado
                    backgroundColor: '#ffffff', // Fondo blanco
                    logging: false, // Deshabilitar logs para mejor rendimiento
                    onclone: function(clonedDoc) {
                        // Forzar estilos de impresión en el clon
                        const style = clonedDoc.createElement('style');
                        style.textContent = `
                            * {
                                -webkit-print-color-adjust: exact !important;
                                print-color-adjust: exact !important;
                                color-adjust: exact !important;
                            }
                            .cell.green, .text.green { background-color: rgba(0, 128, 0, 0.725) !important; }
                            .cell.yellow, .text.yellow { background-color: rgba(255, 255, 0, 0.816) !important; }
                            .cell.red, .text.red { background-color: rgba(255, 0, 0, 0.771) !important; }
                            .cell.blue, .text.blue { background-color: rgba(0, 0, 255, 0.682) !important; }
                            .section-title { background-color: gray !important; color: white !important; }
                        `;
                        clonedDoc.head.appendChild(style);
                        
                        // Fix textarea rendering in PDF
                        const originalTextarea = document.getElementById('comentarios');
                        if (originalTextarea) {
                            const clonedTextarea = clonedDoc.getElementById('comentarios');
                            if (clonedTextarea) {
                                // Create a div that will replace the textarea
                                const replacementDiv = clonedDoc.createElement('div');
                                
                                // Copy the styling from the textarea
                                const computedStyle = window.getComputedStyle(originalTextarea);
                                replacementDiv.style.width = computedStyle.width;
                                replacementDiv.style.height = computedStyle.height;
                                replacementDiv.style.padding = computedStyle.padding;
                                replacementDiv.style.margin = computedStyle.margin;
                                replacementDiv.style.border = computedStyle.border;
                                replacementDiv.style.fontSize = computedStyle.fontSize;
                                replacementDiv.style.fontFamily = computedStyle.fontFamily;
                                replacementDiv.style.backgroundColor = computedStyle.backgroundColor;
                                replacementDiv.style.color = computedStyle.color;
                                replacementDiv.style.boxSizing = computedStyle.boxSizing;
                                replacementDiv.style.overflowY = 'auto';
                                replacementDiv.style.lineHeight = computedStyle.lineHeight;
                                replacementDiv.style.whiteSpace = 'pre-wrap'; // Preserve line breaks
                                replacementDiv.style.wordWrap = 'break-word'; // Break words that would overflow
                                
                                // Set the content, preserving line breaks
                                replacementDiv.textContent = originalTextarea.value;
                                
                                // Replace the textarea with our div
                                clonedTextarea.parentNode.replaceChild(replacementDiv, clonedTextarea);
                            }
                        }
                    }
                };
                
                // Capturar el formulario con los estilos aplicados
                const container = document.querySelector('.container');
                
                html2canvas(container, options)
                    .then(canvas => {
                        try {
                            // Crear un PDF con mejor calidad y preservación de colores
                            const imgData = canvas.toDataURL('image/png', 1.0); // Máxima calidad
                            const pdf = new window.jspdf.jsPDF({
                                orientation: 'portrait',
                                unit: 'mm',
                                format: 'letter',
                                compress: false // Desactivar compresión para mejor calidad
                            });
                            
                            // Calcular dimensiones para ajustar al PDF correctamente
                            const imgWidth = 216; // Letter width in mm (portrait)
                            const pageHeight = 279; // Letter height in mm
                            const imgHeight = (canvas.height * imgWidth) / canvas.width;
                            let heightLeft = imgHeight;
                            let position = 0;
                            
                            // Añadir la primera página
                            pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight, '', 'FAST');
                            heightLeft -= pageHeight;
                            
                            // Añadir páginas adicionales si es necesario
                            while (heightLeft > 0) {
                                position = heightLeft - imgHeight;
                                pdf.addPage();
                                pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight, '', 'FAST');
                                heightLeft -= pageHeight;
                            }
                            
                            // Restore UI elements
                            toggleNonPrintableElements(true);
                            if (saveBtn) saveBtn.style.display = 'flex';
                            if (pdfBtn) pdfBtn.style.display = 'flex';
                            document.getElementById('loading-spinner').style.display = 'none';
                            
                            // Execute callback if provided
                            if (callback && typeof callback === 'function') {
                                callback(pdf);
                            }
                            
                            // Resolver la promesa con el PDF generado
                            resolve(pdf);
                        } catch (innerError) {
                            console.error('Error processing canvas to PDF:', innerError);
                            throw innerError;
                        }
                    })
                    .catch(error => {
                        console.error('Error al generar el PDF:', error);
                        // Restaurar botones y ocultar spinner en caso de error
                        toggleNonPrintableElements(true);
                        if (saveBtn) saveBtn.style.display = 'flex';
                        if (pdfBtn) pdfBtn.style.display = 'flex';
                        document.getElementById('loading-spinner').style.display = 'none';
                        
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'Ocurrió un error al generar el PDF'
                        });
                        
                        // Rechazar la promesa con el error
                        reject(error);
                    });
            }, 300); // Small delay to ensure DOM is ready
        } catch (error) {
            console.error('Error in generatePDF:', error);
            document.getElementById('loading-spinner').style.display = 'none';
            toggleNonPrintableElements(true);
            reject(error);
        }
    });
}

function sendPDFByEmail(pdf, emailAddress) {
    return new Promise((resolve, reject) => {
        try {
            const pdfBase64 = pdf.output('datauristring');
            document.getElementById('loading-spinner').style.display = 'flex';

            fetch(base_url + "index.php/servicio/multipuntos_email/", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    email: emailAddress,
                    pdfData: pdfBase64,
                    orderId: movid
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Error en la respuesta del servidor: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                document.getElementById('loading-spinner').style.display = 'none';
                if (data.estatus) {
                    resolve(data);
                } else {
                    reject(new Error(data.mensaje || 'Error desconocido'));
                }
            })
            .catch(error => {
                document.getElementById('loading-spinner').style.display = 'none';
                reject(error);
            });
        } catch (error) {
            document.getElementById('loading-spinner').style.display = 'none';
            reject(error);
        }
    });
}

function promptEmailAndSendPDF() {
    Swal.fire({
        title: 'Enviar formato inspección por email',
        html: `
            <div class="form-group">
                <label for="email-input">Dirección de correo electrónico:</label>
                <input type="email" id="email-input" class="swal2-input" placeholder="ejemplo@correo.com">
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Enviar',
        cancelButtonText: 'Cancelar',
        focusConfirm: false,
        preConfirm: () => {
            const email = document.getElementById('email-input').value;
            if (!email || !email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
                Swal.showValidationMessage('Por favor ingrese un email válido');
                return false;
            }
            return email;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const emailAddress = result.value;
            
            // Usar Promise API en lugar de callbacks
            generatePDF()
                .then(pdf => sendPDFByEmail(pdf, emailAddress))
                .then(data => {
                    Swal.fire(
                        '¡Enviado!',
                        'El PDF ha sido enviado por correo electrónico.',
                        'success'
                    );
                })
                .catch(error => {
                    console.error('Error en el proceso:', error);
                    Swal.fire(
                        'Error',
                        'No se pudo enviar el email: ' + (error.message || 'Error desconocido'),
                        'error'
                    );
                });
        }
    });
}

document.addEventListener("DOMContentLoaded", function() {
	disableInputs()
    if (answers !== null) {
        setCheckboxAndInputValues(answers);
    }
        // Initialize textarea font size adjustment
        const commentsTextarea = document.getElementById('comentarios');
        if (commentsTextarea) {
            // Asegurar que el textarea se ajuste al cargar la página
            setTimeout(() => {
                adjustCommentsFontSize(); // Run once for existing content
            }, 100); // Pequeño retraso para asegurar que el contenido está renderizado
            
            // Add event listener for input with improved control
            commentsTextarea.addEventListener('input', function(e) {
                const textarea = e.target;
                const maxHeight = 190; // Fixed max height in pixels
                
                // Store current caret position and text
                const caretPos = textarea.selectionStart;
                const previousValue = textarea.value;
                
                // Adjust font size first
                adjustCommentsFontSize();
                
                // Check if content still exceeds max height at minimum font size
                textarea.style.fontSize = '8px'; // Set to minimum to check
                if (textarea.scrollHeight > maxHeight) {
                    // Revert to previous value
                    textarea.value = previousValue;
                    // Prevent default doesn't work well here since input already happened
                    e.preventDefault();
                    // Flash the textarea to indicate it's at capacity
                    const originalBackground = textarea.style.backgroundColor;
                    textarea.style.backgroundColor = 'rgba(255,0,0,0.1)';
                    setTimeout(() => {
                        textarea.style.backgroundColor = originalBackground;
                    }, 200);
                }
                
                // Recalculate optimal font size and restore caret position
                adjustCommentsFontSize();
                if (textarea.value.length >= previousValue.length) {
                    textarea.setSelectionRange(caretPos, caretPos);
                }
            });
            
            // Ensure textarea doesn't grow beyond max height
            commentsTextarea.style.maxHeight = '190px';
            commentsTextarea.style.overflowY = 'hidden';
        }

    // Download PDF
    document.getElementById("descargarPdf").addEventListener("click", function () {
        generatePDF().then(pdf => {
            // Guardar el PDF con nombre basado en el número de orden
            pdf.save(`InspeccionMultipuntos_${movid}.pdf`);
        }).catch(error => {
            console.error("Error al descargar el PDF:", error);
        });
    });

    // ========================================================================================
    // Manejo del DOM de este archivo
    // ========================================================================================

    // Adjust Textarea Height for class dynamicTextarea
    document.querySelectorAll(".dynamicTextarea").forEach(textarea => {
        textarea.addEventListener("input", function () {
            this.style.height = "auto";
            this.style.height = this.scrollHeight + "px";
        });
    });

    // Set Checkbox and Input Values
    function setCheckboxAndInputValues(answers) {
        for (const [key, value] of Object.entries(answers)) {
            const checkboxContainer = document.querySelector(`input[name="${key}"]`).closest('.checkboxs');
            if (checkboxContainer) {
                const checkbox = checkboxContainer.querySelector(`.cell.${value} input[type="checkbox"]`);
                if (checkbox) {
                    checkbox.checked = true;
                }
            } else {
                const input = document.querySelector(`input[name="${key}"]`);
                if (input) {
                    input.value = value;
                }
            }
        }
    }

    // Checkbox Selection Handling
    document.querySelectorAll('.checkboxs input[type="checkbox"]').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            if (this.checked) {
                const checkboxes = this.closest('.checkboxs').querySelectorAll('input[type="checkbox"]');
                checkboxes.forEach(cb => {
                    if (cb !== this) {
                        cb.checked = false;
                    }
                });
            }
        });
    });

    // Email PDF functionality
    document.getElementById("enviarPdf").addEventListener("click", function() {
        promptEmailAndSendPDF();
    });
});
