<?php
// Disable HTTP caching
header("Expires: Thu, 19 Nov 1969 08:52:00 GMT"); // Past date
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false); // HTTP/1.1 (IE-specific)
header("Pragma: no-cache"); // HTTP/1.0
?>

// Global state tracking for button activation
var paymentButtonState = {
    phoneCopied: false,
    rifCopied: false,
    focusLost: false
};

/**
 * Check if all conditions are met to activate the button
 * @returns {boolean}
 */
function canActivateButton() {
    return paymentButtonState.phoneCopied && 
           paymentButtonState.rifCopied;
}

/**
 * Check and update button state
 */
function checkButtonActivation() {
    const stepFormButtonSubmit = document.querySelector(".step-form-button-submit");
    if (!stepFormButtonSubmit) return;
    
    if (canActivateButton()) {
        stepFormButtonSubmit.classList.add('active');
        stepFormButtonSubmit.removeAttribute("disabled");
    } else {
        stepFormButtonSubmit.classList.remove('active');
        stepFormButtonSubmit.setAttribute("disabled", "");
    }
}

/**
 * Show error popup when button is clicked but conditions not met
 */
function showButtonError() {
    const errorMessage = 'Por favor, copia los datos y finaliza la transferencia en tu aplicaci¨®n bancaria';
    if (typeof showToast === 'function') {
        showToast(errorMessage, 'error');
    } else {
        // Fallback if showToast is not available
        alert(errorMessage);
    }
}
  
document.addEventListener("DOMContentLoaded", function() {
    try {
    const copyButton = document.querySelector(".pocket-address-input .copy");
    const copyButtonAlias = document.querySelector(".recipient-alias-info .copy");
    const stepFormButtonSubmit = document.querySelector(".step-form-button-submit");
    const copyDone = document.querySelector(".pocket-address-input .copy-done");
    const copyDoneAlias = document.querySelector(".recipient-alias-info .copy-done");
    const inputField = document.getElementById("payment-id");
    const inputFieldBank = document.getElementById("recipient-bank");
    const inputFieldAlias = document.getElementById("recipient-alias");
    
    const copyBankButton = document.querySelector(".client-bank-container .copy");
    const copyBankButtonDone = document.querySelector(".client-bank-container .copy-done");

    // Track focus loss (user switched to bank app and came back)
    let wasFocused = true;
    let hasLostFocus = false;
    
    window.addEventListener('blur', function() {
        wasFocused = false;
        hasLostFocus = true;
        paymentButtonState.focusLost = true;
        checkButtonActivation();
    });
    
    window.addEventListener('focus', function() {
        if (!wasFocused && hasLostFocus) {
            paymentButtonState.focusLost = true;
            checkButtonActivation();
        }
        wasFocused = true;
    });
    
    // Also track visibility change (for mobile apps)
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            wasFocused = false;
            hasLostFocus = true;
            paymentButtonState.focusLost = true;
            checkButtonActivation();
        } else if (hasLostFocus) {
            paymentButtonState.focusLost = true;
            checkButtonActivation();
        }
    });

    // Initialize button as disabled
    if (stepFormButtonSubmit) {
        stepFormButtonSubmit.classList.remove('active');
        stepFormButtonSubmit.setAttribute("disabled", "");
        // Initial check (will keep button disabled since conditions not met)
        checkButtonActivation();
    }
    
    // Modal handlers with null checks
    const btnModal = document.getElementById('btn-modal');
    const btnModalNext = document.getElementById('btn-modal-next');
    const closeBtn = document.getElementById('close-btn');
    const overlay = document.getElementById('overlay');
    const modal = document.getElementById('modal');
    
    if (btnModal && overlay && modal) {
        btnModal.addEventListener('click', function() {
            try {
                overlay.classList.add('is-visible');
                modal.classList.add('is-visible');
            } catch (err) {
                console.error("Error opening modal: ", err);
            }
        });
    }

    if (btnModalNext && overlay && modal) {
        btnModalNext.addEventListener('click', function() {
            try {
                overlay.classList.add('is-visible');
                modal.classList.add('is-visible');
            } catch (err) {
                console.error("Error opening modal: ", err);
            }
        });
    }

    if (closeBtn && overlay && modal) {
        closeBtn.addEventListener('click', function() {
            try {
                overlay.classList.remove('is-visible');
                modal.classList.remove('is-visible');
            } catch (err) {
                console.error("Error closing modal: ", err);
            }
        });
    }
    
    if (overlay && modal) {
        overlay.addEventListener('click', function() {
            try {
                overlay.classList.remove('is-visible');
                modal.classList.remove('is-visible');
            } catch (err) {
                console.error("Error closing modal: ", err);
            }
        });
    }

    // Bank copy handler (no longer activates button)
    if (copyBankButton && inputFieldBank && copyBankButtonDone) {
        copyBankButton.addEventListener("click", function() {
            try {
                const textToCopy = inputFieldBank.innerText || inputFieldBank.textContent || '';
                if (!textToCopy) {
                    console.warn("No text to copy from bank field");
                    return;
                }
                if (typeof copyWithToast === 'function') {
                    copyWithToast(textToCopy).then((success) => {
                        if (success) {
                            if (copyBankButton) copyBankButton.style.display = "none";
                            if (copyBankButtonDone) copyBankButtonDone.style.display = "flex";
                            
                            setTimeout(() => {
                                if (copyBankButton) copyBankButton.style.display = "flex";
                                if (copyBankButtonDone) copyBankButtonDone.style.display = "none";
                            }, 2000);
                        }
                    });
                } else {
                    // Fallback if copyWithToast is not loaded
                    if (navigator.clipboard && navigator.clipboard.writeText) {
                        navigator.clipboard.writeText(textToCopy).catch(() => {
                            console.error("Copy failed");
                        });
                    }
                }
            } catch (err) {
                console.error("Error in copy bank handler: ", err);
                if (typeof showToast === 'function') {
                    showToast('No se pudo copiar. Copia este dato manualmente, por favor.', 'error');
                }
            }
        });
    }
    
    // RIF copy handler - sets rifCopied flag
    if (copyButton && inputField && copyDone) {
        copyButton.addEventListener("click", function() {
            try {
                // Get raw RIF from data attribute or extract from displayed text
                const rawRif = inputField.getAttribute('data-raw-rif') || inputField.innerText || inputField.textContent || '';
                // Always copy only digits (no letter, no formatting)
                const textToCopy = typeof getRifForCopy === 'function' ? getRifForCopy(rawRif) : rawRif.replace(/[^0-9]/g, '');
                if (!textToCopy) {
                    console.warn("No text to copy from payment-id field");
                    return;
                }
                if (typeof copyWithToast === 'function') {
                    copyWithToast(textToCopy).then((success) => {
                        if (success) {
                            // Mark RIF as copied
                            paymentButtonState.rifCopied = true;
                            
                            if (copyButton) copyButton.style.display = "none";
                            if (copyDone) copyDone.style.display = "flex";
                            
                            setTimeout(() => {
                                if (copyButton) copyButton.style.display = "flex";
                                if (copyDone) copyDone.style.display = "none";
                            }, 2000);

                            // Check if button can be activated
                            checkButtonActivation();
                        }
                    });
                } else {
                    if (navigator.clipboard && navigator.clipboard.writeText) {
                        navigator.clipboard.writeText(textToCopy).then(() => {
                            paymentButtonState.rifCopied = true;
                            checkButtonActivation();
                        }).catch(() => {
                            console.error("Copy failed");
                        });
                    }
                }
            } catch (err) {
                console.error("Error in copy handler: ", err);
                if (typeof showToast === 'function') {
                    showToast('No se pudo copiar. Copia este dato manualmente, por favor.', 'error');
                }
            }
        });
    }
    
    // Format RIF for display on page load
    if (inputField && typeof formatRifForDisplay === 'function') {
        const rawRif = inputField.getAttribute('data-raw-rif') || inputField.textContent || '';
        if (rawRif) {
            const formatted = formatRifForDisplay(rawRif);
            inputField.textContent = formatted;
        }
    }
    // Alias copy handler (no longer activates button)
    if (copyButtonAlias && inputFieldAlias && copyDoneAlias) {
        copyButtonAlias.addEventListener("click", function() {
            try {
                const textToCopy = inputFieldAlias.innerText || inputFieldAlias.textContent || '';
                if (!textToCopy) {
                    console.warn("No text to copy from alias field");
                    return;
                }
                if (typeof copyWithToast === 'function') {
                    copyWithToast(textToCopy).then((success) => {
                        if (success) {
                            if (copyButtonAlias) copyButtonAlias.style.display = "none";
                            if (copyDoneAlias) copyDoneAlias.style.display = "flex";
                            
                            setTimeout(() => {
                                if (copyButtonAlias) copyButtonAlias.style.display = "flex";
                                if (copyDoneAlias) copyDoneAlias.style.display = "none";
                            }, 2000);
                        }
                    });
                } else {
                    if (navigator.clipboard && navigator.clipboard.writeText) {
                        navigator.clipboard.writeText(textToCopy).catch(() => {
                            console.error("Copy failed");
                        });
                    }
                }
            } catch (err) {
                console.error("Error in copy alias handler: ", err);
                if (typeof showToast === 'function') {
                    showToast('No se pudo copiar. Copia este dato manualmente, por favor.', 'error');
                }
            }
        });
    }
    
    
        // Handler for beneficiary name (new block)
        const beneficiaryNameContainer = document.getElementById("beneficiary-name-container");
        const beneficiaryNameCopyBtn = beneficiaryNameContainer ? beneficiaryNameContainer.querySelector(".copy-client-name .copy") : null;
        const beneficiaryNameCopyDone = beneficiaryNameContainer ? beneficiaryNameContainer.querySelector(".copy-client-name .copy-done") : null;
        
        if (beneficiaryNameContainer && beneficiaryNameCopyBtn && beneficiaryNameCopyDone) {
            beneficiaryNameCopyBtn.addEventListener("click", function() {
                try {
                    const beneficiaryNameEl = document.getElementById("beneficiary-name");
                    if (!beneficiaryNameEl) {
                        console.warn("Beneficiary name element not found");
                        return;
                    }
                    const textToCopy = beneficiaryNameEl.innerText || beneficiaryNameEl.textContent || '';
                    if (!textToCopy) {
                        console.warn("No text to copy from beneficiary name");
                        return;
                    }
                    if (typeof copyWithToast === 'function') {
                        copyWithToast(textToCopy).then((success) => {
                            if (success) {
                                if (beneficiaryNameCopyBtn) beneficiaryNameCopyBtn.style.display = "none";
                                if (beneficiaryNameCopyDone) beneficiaryNameCopyDone.style.display = "flex";
                                
                                setTimeout(() => {
                                    if (beneficiaryNameCopyBtn) beneficiaryNameCopyBtn.style.display = "flex";
                                    if (beneficiaryNameCopyDone) beneficiaryNameCopyDone.style.display = "none";
                                }, 2000);
                            }
                        });
                    } else {
                        if (navigator.clipboard && navigator.clipboard.writeText) {
                            navigator.clipboard.writeText(textToCopy).catch(() => {
                                console.error("Copy failed");
                            });
                        }
                    }
                } catch (err) {
                    console.error("Error in copy beneficiary name handler: ", err);
                    if (typeof showToast === 'function') {
                        showToast('No se pudo copiar. Copia este dato manualmente, por favor.', 'error');
                    }
                }
            });
            
            // Allow clicking on container to copy
            beneficiaryNameContainer.addEventListener("click", function(e) {
                if (e.target.closest(".copy-client-name") || e.target.closest(".client-name-container")) {
                    beneficiaryNameCopyBtn.click();
                }
            });
        }
    
        // Handler for recipient name (phone) - sets phoneCopied flag
        const copyButtonCustomerName = document.querySelector("#payment-name-container .copy-client-name .copy");
        const copyDoneCustomerName = document.querySelector("#payment-name-container .copy-client-name .copy-done");
    
        if (copyButtonCustomerName && copyDoneCustomerName) {
            copyButtonCustomerName.addEventListener("click", function() {
                try {
                    const recipientNameEl = document.getElementById("recipient-name");
                    if (!recipientNameEl) {
                        console.warn("Recipient name element not found");
                        return;
                    }
                    // Get raw phone from data attribute or extract from displayed text
                    const rawPhone = recipientNameEl.getAttribute('data-raw-phone') || recipientNameEl.innerText || recipientNameEl.textContent || '';
                    // Always copy only digits
                    const textToCopy = typeof getPhoneForCopy === 'function' ? getPhoneForCopy(rawPhone) : rawPhone.replace(/\D/g, '');
                    if (!textToCopy) {
                        console.warn("No text to copy from recipient name");
                        return;
                    }
                    if (typeof copyWithToast === 'function') {
                        copyWithToast(textToCopy).then((success) => {
                            if (success) {
                                // Mark phone as copied
                                paymentButtonState.phoneCopied = true;
                                
                                if (copyButtonCustomerName) copyButtonCustomerName.style.display = "none";
                                if (copyDoneCustomerName) copyDoneCustomerName.style.display = "flex";
                                
                                setTimeout(() => {
                                    if (copyButtonCustomerName) copyButtonCustomerName.style.display = "flex";
                                    if (copyDoneCustomerName) copyDoneCustomerName.style.display = "none";
                                }, 2000);

                                // Check if button can be activated
                                checkButtonActivation();
                            }
                        });
                    } else {
                        if (navigator.clipboard && navigator.clipboard.writeText) {
                            navigator.clipboard.writeText(textToCopy).then(() => {
                                paymentButtonState.phoneCopied = true;
                                checkButtonActivation();
                            }).catch(() => {
                                console.error("Copy failed");
                            });
                        }
                    }
                } catch (err) {
                    console.error("Error in copy customer name handler: ", err);
                    if (typeof showToast === 'function') {
                        showToast('No se pudo copiar. Copia este dato manualmente, por favor.', 'error');
                    }
                }
            });
        }
        
        // Format phone number for display on page load
        const recipientNameEl = document.getElementById("recipient-name");
        if (recipientNameEl && typeof formatPhoneForDisplay === 'function') {
            const rawPhone = recipientNameEl.getAttribute('data-raw-phone') || recipientNameEl.textContent || '';
            if (rawPhone) {
                const formatted = formatPhoneForDisplay(rawPhone);
                recipientNameEl.textContent = formatted;
            }
        }
    
    
            const copyButtonCustomerAmount = document.querySelector(".copy-client-amount .copy");
    const copyDoneCustomerAmount = document.querySelector(".copy-client-amount .copy-done");
    const amountContainer = document.querySelector(".step-main-form-heading-amount");
    const amountValueEl = document.getElementById("client-amount-value");
    
    // Function to copy amount
    const copyAmount = function() {
        try {
            if (!amountValueEl) {
                console.warn("Amount element not found");
                return;
            }
            // Extract numeric value for copying (remove formatting)
            let textToCopy = amountValueEl.innerText || amountValueEl.textContent || '';
            // Remove formatting: "700,00" or "Bs 700,00" -> "700"
            // First remove currency symbols and spaces
            textToCopy = textToCopy.replace(/[^\d,]/g, '');
            // Replace comma with dot and parse as float, then get integer part
            if (textToCopy.includes(',')) {
                const floatVal = parseFloat(textToCopy.replace(',', '.'));
                textToCopy = isNaN(floatVal) ? '' : Math.floor(floatVal).toString();
            } else {
                // If no comma, just get digits
                textToCopy = textToCopy.replace(/[^\d]/g, '');
            }
            if (!textToCopy) {
                console.warn("No numeric value to copy");
                return;
            }
            if (typeof copyWithToast === 'function') {
                copyWithToast(textToCopy).then((success) => {
                    if (success) {
                        if (copyButtonCustomerAmount) copyButtonCustomerAmount.style.display = "none";
                        if (copyDoneCustomerAmount) copyDoneCustomerAmount.style.display = "flex";
                        
                        setTimeout(() => {
                            if (copyButtonCustomerAmount) copyButtonCustomerAmount.style.display = "flex";
                            if (copyDoneCustomerAmount) copyDoneCustomerAmount.style.display = "none";
                        }, 2000);
                    }
                });
            } else {
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(textToCopy).then(() => {
                        if (copyButtonCustomerAmount) copyButtonCustomerAmount.style.display = "none";
                        if (copyDoneCustomerAmount) copyDoneCustomerAmount.style.display = "flex";
                        
                        setTimeout(() => {
                            if (copyButtonCustomerAmount) copyButtonCustomerAmount.style.display = "flex";
                            if (copyDoneCustomerAmount) copyDoneCustomerAmount.style.display = "none";
                        }, 2000);
                    }).catch(() => {
                        console.error("Copy failed");
                    });
                }
            }
        } catch (err) {
            console.error("Error in copy amount handler: ", err);
            if (typeof showToast === 'function') {
                showToast('No se pudo copiar. Copia este dato manualmente, por favor.', 'error');
            }
        }
    };
    
    // Add click handler to icon
    if (copyButtonCustomerAmount && copyDoneCustomerAmount) {
        copyButtonCustomerAmount.addEventListener("click", function(e) {
            e.stopPropagation(); // Prevent triggering container click
            copyAmount();
        });
    }
    
    // Add click handler to entire amount container (including the text "Bs 500")
    if (amountContainer) {
        amountContainer.addEventListener("click", function(e) {
            // Only trigger if click is not on the copy icon itself
            if (!e.target.closest('.copy-client-amount .copy') && !e.target.closest('.copy-client-amount .copy-done')) {
                copyAmount();
            }
        });
    }
    
    // Also add click handler directly to amount value element
    if (amountValueEl) {
        amountValueEl.style.cursor = 'pointer';
        amountValueEl.addEventListener("click", function(e) {
            e.stopPropagation();
            copyAmount();
        });
    }
    
    const paymentNameContainer = document.getElementById("payment-name-container");
    const paymentCodeContainer = document.getElementById("payment-code-container");
    const paymentBankContainer = document.getElementById("payment-bank-container");
    
    if (paymentNameContainer && copyButtonCustomerName) {
        paymentNameContainer.addEventListener("click", () => {copyButtonCustomerName.click()});
    }
    if (paymentCodeContainer && copyButton) {
        paymentCodeContainer.addEventListener("click", () => {copyButton.click()});
    }
    if (paymentBankContainer && copyBankButton) {
        paymentBankContainer.addEventListener("click", () => {copyBankButton.click()});
    }
    
    // Copy handlers for transfer summary card (step 2)
    const copyTransferButtons = document.querySelectorAll('.copy-transfer-value');
    copyTransferButtons.forEach(function(copyButton) {
        const targetId = copyButton.getAttribute('data-copy-target');
        const targetElement = document.getElementById(targetId);
        const copyDone = copyButton.querySelector('.copy-done');
        const copyIcon = copyButton.querySelector('.copy');
        
        if (targetElement && copyDone && copyIcon) {
            copyButton.addEventListener('click', function() {
                try {
                    // Get raw value from data attribute or text content
                    let textToCopy = '';
                    if (targetId === 'customer-number') {
                        const rawRif = targetElement.getAttribute('data-raw-rif') || targetElement.textContent || '';
                        // Remove formatting for RIF (only digits)
                        textToCopy = rawRif.replace(/[^0-9]/g, '');
                    } else if (targetId === 'customer-name') {
                        const rawPhone = targetElement.getAttribute('data-raw-phone') || targetElement.textContent || '';
                        textToCopy = rawPhone;
                    } else {
                        textToCopy = targetElement.textContent || targetElement.innerText || '';
                    }
                    
                    if (!textToCopy) {
                        console.warn("No text to copy from " + targetId);
                        return;
                    }
                    
                    if (typeof copyWithToast === 'function') {
                        copyWithToast(textToCopy).then((success) => {
                            if (success) {
                                copyIcon.style.display = "none";
                                copyDone.style.display = "flex";
                                
                                setTimeout(() => {
                                    copyIcon.style.display = "flex";
                                    copyDone.style.display = "none";
                                }, 2000);
                            }
                        });
                    } else {
                        // Fallback if copyWithToast is not loaded
                        if (navigator.clipboard && navigator.clipboard.writeText) {
                            navigator.clipboard.writeText(textToCopy).catch(() => {
                                console.error("Copy failed");
                            });
                        }
                    }
                } catch (err) {
                    console.error("Error in copy transfer handler: ", err);
                    if (typeof showToast === 'function') {
                        showToast('No se pudo copiar. Copia este dato manualmente, por favor.', 'error');
                    }
                }
            });
        }
    });
    
    } catch (err) {
        console.error("Error initializing copy handlers: ", err);
    }

});


document.addEventListener("DOMContentLoaded", function () {
    try {
    const input = document.getElementById("step-info-input");
    const inputTaxId = document.getElementById("step-info-input-tax-id");
    const stepInfoTaxId = document.querySelector(".customer-step-info-tax-id");
    const loader = document.querySelector(".customer-step-info-label svg");
    let stepInfo = document.querySelector(".customer-step-info-name");
    const error = document.querySelector(".error-message");
    const descriptionContainer = document.querySelector(".customer-step-info-description-container");
    const stepFormButtonSubmitSave = document.getElementById("step-form-button-submit-save");
    
    const inputEmail = document.getElementById("step-info-input-email");
    const stepInfoEmail = document.querySelector(".customer-step-info-email");
    
    const inputPhone = document.getElementById("step-info-input-phone");
    const stepInfoPhone = document.querySelector(".customer-step-info-phone");
    
    // Early return if critical elements are missing
    if (!input || !stepFormButtonSubmitSave) {
        console.warn("Critical form elements not found, skipping initialization");
        return;
    }
    
            function validateCuit(cuit) {
  const validTypes = [20, 23, 24, 27, 30, 33, 34];
  const multipliers = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2];
  const number = cuit.replace(/-/g, '').trim();
  if (number.length !== 11) return false;
  const typePrefix = parseInt(number.slice(0, 2), 10);
  if (!validTypes.includes(typePrefix)) return false;
  let sum = 0;
  for (let i = 0; i < 10; i++) {
    sum += parseInt(number[i], 10) * multipliers[i];
  }
  let checksum = 11 - (sum % 11);
  if (checksum === 11) checksum = 0;
  else if (checksum === 10) checksum = 9;
  return checksum === parseInt(number[10], 10);
}

// Validate Venezuela phone number
// Formats accepted: 0412-1234567, 04121234567, +584121234567, 584121234567
// Mobile numbers start with 04 (0412, 0414, 0416, 0424, 0426)
function validateVenezuelaPhone(phone) {
    if (!phone || typeof phone !== 'string') return false;
    
    // Remove all spaces, dashes, and parentheses
    let cleaned = phone.replace(/[\s\-\(\)]/g, '');
    
    // Remove country code prefix if present
    if (cleaned.startsWith('+58')) {
        cleaned = cleaned.substring(3);
    } else if (cleaned.startsWith('58') && cleaned.length === 12) {
        cleaned = cleaned.substring(2);
    }
    
    // Must be 10 digits
    if (cleaned.length !== 10) return false;
    
    // Must start with 04 (Venezuela mobile prefix)
    if (!cleaned.startsWith('04')) return false;
    
    // Must be all digits
    if (!/^\d+$/.test(cleaned)) return false;
    
    // Valid mobile operator codes: 0412, 0414, 0416, 0424, 0426
    const validOperators = ['0412', '0414', '0416', '0424', '0426'];
    const operator = cleaned.substring(0, 4);
    
    return validOperators.includes(operator);
}

function checkCuit() {
    try {
        const taxIdInput = document.getElementById('step-info-input-tax-id');
        if (!taxIdInput) return;
        
        const input = taxIdInput.value;
        const isValid = validateCuit(input);
        const taxMainContainer = document.getElementById('customer-step-info-tax-id-container');
        
        const taxInfoSvgContainer = document.getElementById('info-svg-container');
        const taxInfoSvgContainerError = document.getElementById('info-svg-container-error');
        const stepFormButtonSubmitSave = document.getElementById("step-form-button-submit-save");
        const validationDesc = document.getElementById('customer-step-info-description-validation');

        if (validationDesc) {
            validationDesc.textContent = isValid ? "Identificaci¨®n fiscal v¨¢lida" : "Identificaci¨®n fiscal no v¨¢lida";
        }
        
        if (isValid) {
            if (stepInfoTaxId) stepInfoTaxId.classList.add("correct");
            if (stepFormButtonSubmitSave) {
                stepFormButtonSubmitSave.classList.add('active');
                stepFormButtonSubmitSave.removeAttribute("disabled");
            }
            if (taxMainContainer) taxMainContainer.classList.remove('wrong-data');
            if (taxInfoSvgContainerError) taxInfoSvgContainerError.classList.add('hidden');
            if (taxInfoSvgContainer) taxInfoSvgContainer.classList.remove('hidden');
        } else {
            if (stepFormButtonSubmitSave) {
                stepFormButtonSubmitSave.classList.remove('active');
                stepFormButtonSubmitSave.setAttribute("disabled", "");
            }
            if (stepInfoTaxId) stepInfoTaxId.classList.remove("correct");
            if (taxMainContainer) taxMainContainer.classList.add('wrong-data');
            if (taxInfoSvgContainerError) taxInfoSvgContainerError.classList.remove('hidden');
            if (taxInfoSvgContainer) taxInfoSvgContainer.classList.add('hidden');
        }
    } catch (err) {
        console.error("Error in checkCuit: ", err);
    }
}

    if (stepFormButtonSubmitSave) {
        stepFormButtonSubmitSave.addEventListener('click', function() {
            try {
                const successContainer = document.querySelector(".customer-step-info-description-container-success");
                if (successContainer) successContainer.style.display = "flex";
                if (input) {
                    input.setAttribute("readonly", "");
                    input.classList.add("validation-success");
                }
                stepFormButtonSubmitSave.classList.remove('active');
                stepFormButtonSubmitSave.setAttribute("disabled", "");
            } catch (err) {
                console.error("Error in submit button handler: ", err);
                if (typeof showToast === 'function') {
                    showToast('Ocurri¨® un error. Intenta nuevamente.', 'error');
                }
            }
        });
    }
    
    if(!stepInfo) {
        stepInfo = document.querySelector(".customer-step-info");
    }
    
    if (!stepInfo) {
        console.warn("Step info element not found");
    }
    
        function isFirstCharLetter(str) {
    return /^[a-zA-Z]/.test(str);
}

    // Scroll into view on focus (mobile keyboard handling)
    if (input) {
        input.addEventListener("focus", function() {
            try {
                // Small delay to ensure keyboard is opening
                setTimeout(() => {
                    if (input) {
                        // Use try-catch for scrollIntoView as it may fail in some webviews
                        try {
                            input.scrollIntoView({ 
                                block: "center", 
                                behavior: "smooth",
                                inline: "nearest"
                            });
                        } catch (scrollErr) {
                            // Fallback for browsers that don't support smooth scroll
                            try {
                                input.scrollIntoView({ block: "center" });
                            } catch (fallbackErr) {
                                // Last resort - just scroll to element
                                input.scrollIntoView();
                            }
                        }
                    }
                    
                    // Additional scroll for CTA button visibility on mobile
                    setTimeout(() => {
                        try {
                            const submitButton = document.getElementById("step-form-button-submit-save");
                            if (submitButton) {
                                const rect = submitButton.getBoundingClientRect();
                                const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
                                // If button is below viewport, scroll a bit more
                                if (rect && rect.bottom > viewportHeight - 20) {
                                    try {
                                        window.scrollBy({
                                            top: rect.bottom - viewportHeight + 100,
                                            behavior: 'smooth'
                                        });
                                    } catch (scrollByErr) {
                                        // Fallback for browsers that don't support scrollBy with options
                                        window.scrollBy(0, rect.bottom - viewportHeight + 100);
                                    }
                                }
                            }
                        } catch (scrollErr) {
                            // Silently fail if scrollBy is not supported
                        }
                    }, 300);
                }, 100);
            } catch (err) {
                console.error("Error in scrollIntoView: ", err);
            }
        });
    }

    if (input && stepFormButtonSubmitSave) {
        input.addEventListener("input", function () {
            try {
                if (loader) loader.style.display = "flex";

                const inputValue = input.value.trim();

                const isNumeric = /^\d+$/.test(inputValue);
                const isValid = inputValue.length >= 4 && isNumeric;

                if (isValid) {
                    if (error) error.style.display = "none";
                    if (stepInfo) {
                        stepInfo.classList.add("correct");
                        stepInfo.classList.remove("wrong-data");
                    }
                    stepFormButtonSubmitSave.classList.add("active");
                    stepFormButtonSubmitSave.removeAttribute("disabled");
                } else if (inputValue.length > 0) {
                    if (error) error.style.display = "flex";
                    if (stepInfo) {
                        stepInfo.classList.add("wrong-data");
                        stepInfo.classList.remove("correct");
                    }
                    stepFormButtonSubmitSave.classList.remove("active");
                    stepFormButtonSubmitSave.setAttribute("disabled", "");
                }

                if (inputValue.length > 0) {
                    if (descriptionContainer) descriptionContainer.style.display = "none";
                } else {
                    if (descriptionContainer) descriptionContainer.style.display = "flex";
                    if (error) error.style.display = "none";
                    if (stepInfo) {
                        stepInfo.classList.remove("wrong-data");
                        stepInfo.classList.remove("correct");
                    }
                }
            } catch (err) {
                console.error("Error in input validation: ", err);
            }
        });
    }
    
    if(inputTaxId) {
        inputTaxId.addEventListener("input", function () {
            checkCuit();
        });
    }

    if(inputEmail && stepInfoEmail && stepFormButtonSubmitSave) {
        inputEmail.addEventListener("input", function () {
            try {
                const inputValue = inputEmail.value.trim();
                
                if (inputValue.length > 0) {
                    stepInfoEmail.classList.add("correct");
                    stepFormButtonSubmitSave.classList.add('active');
                    stepFormButtonSubmitSave.removeAttribute("disabled");
                } else {
                    stepFormButtonSubmitSave.classList.remove('active');
                    stepFormButtonSubmitSave.setAttribute("disabled", "");
                    stepInfoEmail.classList.remove("correct");
                }
            } catch (err) {
                console.error("Error in email input handler: ", err);
            }
        });
    }

// Phone number input handler (for phone number step)
    const inputPhoneNumber = document.getElementById("step-info-input-phone-number");
    const stepInfoPhoneNumber = document.querySelector(".customer-step-info-phone-number");
    
    if(inputPhoneNumber && stepInfoPhoneNumber && stepFormButtonSubmitSave) {
        const phoneError = stepInfoPhoneNumber.querySelector(".error-message");
        const phoneDescription = stepInfoPhoneNumber.querySelector(".customer-step-info-description-container");
        const phoneSuccess = stepInfoPhoneNumber.querySelector(".customer-step-info-description-container-success");
        
        inputPhoneNumber.addEventListener("input", function () {
            try {
                const inputValue = inputPhoneNumber.value.trim();
                
                if (inputValue.length === 0) {
                    // Empty input - show info message
                    if (phoneError) phoneError.style.display = "none";
                    if (phoneDescription) phoneDescription.style.display = "flex";
                    if (phoneSuccess) phoneSuccess.style.display = "none";
                    stepInfoPhoneNumber.classList.remove("correct");
                    stepInfoPhoneNumber.classList.remove("wrong-data");
                    stepFormButtonSubmitSave.classList.remove('active');
                    stepFormButtonSubmitSave.setAttribute("disabled", "");
                } else {
                    // Validate Venezuela phone number
                    const isValid = validateVenezuelaPhone(inputValue);
                    
                    if (isValid) {
                        // Valid phone
                        if (phoneError) phoneError.style.display = "none";
                        if (phoneDescription) phoneDescription.style.display = "none";
                        stepInfoPhoneNumber.classList.add("correct");
                        stepInfoPhoneNumber.classList.remove("wrong-data");
                        stepFormButtonSubmitSave.classList.add('active');
                        stepFormButtonSubmitSave.removeAttribute("disabled");
                    } else {
                        // Invalid phone
                        if (phoneError) phoneError.style.display = "flex";
                        if (phoneDescription) phoneDescription.style.display = "none";
                        if (phoneSuccess) phoneSuccess.style.display = "none";
                        stepInfoPhoneNumber.classList.remove("correct");
                        stepInfoPhoneNumber.classList.add("wrong-data");
                        stepFormButtonSubmitSave.classList.remove('active');
                        stepFormButtonSubmitSave.setAttribute("disabled", "");
                    }
                }
            } catch (err) {
                console.error("Error in phone number input handler: ", err);
            }
        });
    }
    
    if(inputPhone && stepInfoPhone && stepFormButtonSubmitSave) {
        inputPhone.addEventListener("input", function () {
            try {
                const inputValue = inputPhone.value.trim();
                
                if (inputValue.length > 0) {
                    stepInfoPhone.classList.add("correct");
                    stepFormButtonSubmitSave.classList.add('active');
                    stepFormButtonSubmitSave.removeAttribute("disabled");
                } else {
                    stepFormButtonSubmitSave.classList.remove('active');
                    stepFormButtonSubmitSave.setAttribute("disabled", "");
                    stepInfoPhone.classList.remove("correct");
                }
            } catch (err) {
                console.error("Error in phone input handler: ", err);
            }
        });
    }
    } catch (err) {
        console.error("Error initializing form handlers: ", err);
    }
});