// Registration Form JavaScript
class RegistrationForm {
    constructor() {
        this.currentStep = 1;
        this.totalSteps = 5;
        this.formData = {
            delegateType: '',
            delegateCount: 1,
            delegates: [],
            delegateProducts: [],
            tables: [],
            sponsorships: [],
            otherSponsorships: [],
            contact: {},
            accessCode: null // Special access link code
        };
        this.config = null;
        this.countdownInterval = null;
        this.stripe = null;
        this.accessCode = null; // Store access code at class level
        
        // Check for special access link parameter
        const urlParams = new URLSearchParams(window.location.search);
        this.accessCode = urlParams.get('access');
        if (this.accessCode) {
            // Store in form data for submission
            this.formData.accessCode = this.accessCode;
            // Store in sessionStorage to persist across page refreshes
            sessionStorage.setItem('xchange_access_code', this.accessCode);
        } else {
            // Check if we have it in sessionStorage (from previous page load)
            const storedAccessCode = sessionStorage.getItem('xchange_access_code');
            if (storedAccessCode) {
                this.accessCode = storedAccessCode;
                this.formData.accessCode = storedAccessCode;
            }
        }
        
        this.loadConfig().then(() => {
            this.initStripe();
            this.init();
            // Render dynamic categories after config is loaded
            if (this.config && this.config.frontend) {
                this.renderDynamicCategories(this.config.frontend);
            }
            // Bind events after dynamic content is rendered
            this.bindTableEvents();
            
            // Check for saved form data AFTER dynamic content is rendered
            this.checkForSavedData();
            
            // Start countdown timers for all pricing tiers
            this.startCountdownTimer();
            
            // Make form instance globally accessible for testing
            window.registrationForm = this;
        });
    }

    async initStripe() {
        try {
            // Get Stripe publishable key from backend
            const response = await fetch('api.php?action=get_stripe_key');
            const result = await response.json();
            
            if (result.success && result.publishable_key) {
                this.stripe = Stripe(result.publishable_key);
            } else {
                console.warn('Stripe not configured, using fallback payment method');
            }
        } catch (error) {
            console.error('Failed to initialize Stripe:', error);
        }
    }

    async loadConfig() {
        try {
            // Load configuration from database via API
            // Include access code parameter if present for special access links
            let apiUrl = 'api.php?action=get_config';
            if (this.accessCode) {
                apiUrl += '&access=' + encodeURIComponent(this.accessCode);
            }
            
            const response = await fetch(apiUrl);
            if (!response.ok) {
                throw new Error('Failed to fetch configuration from API');
            }
            this.config = await response.json();
            
            // Show special access indicator if access code was used
            if (this.accessCode) {
                this.showSpecialAccessIndicator();
            }
        } catch (error) {
            console.error('Failed to load config from database:', error);
            this.showConfigError();
            this.disableForm();
            return; // Exit early, don't set any config
        }
    }

    init() {
        // Only initialize if config was loaded successfully
        if (!this.config) {
            return; // Exit early if no config available
        }
        
        this.setupPricingOptions();
        this.populateCountries();
        this.bindEvents();
        this.updateSummary();
        this.generateDelegateDetails();
        this.startCountdown();
        
        // Note: checkForSavedData() is now called after renderDynamicCategories() 
        // in the constructor's loadConfig().then() block to ensure form elements exist
    }
    
    checkForSavedData() {
        // Check if user wants to start fresh (from cancel page)
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('new') === '1') {
            this.clearSavedFormData();
            return;
        }
        
        const savedData = localStorage.getItem('xchange_registration_data');
        const retryData = localStorage.getItem('xchange_payment_retry');
        
        if (retryData) {
            // Show payment retry option (modal for incomplete payment)
            this.showPaymentRetryOption();
        } else if (savedData) {
            // Auto-restore saved form data without prompting user
            this.loadSavedFormData();
        }
    }
    
    showPaymentRetryOption() {
        const retryData = this.getPaymentRetryData();
        if (!retryData) return;
        
        const modal = document.createElement('div');
        modal.className = 'recovery-modal';
        modal.innerHTML = `
            <div class="recovery-modal-content">
                <div class="recovery-icon">💳</div>
                <h3>Payment Incomplete</h3>
                <p>We found an incomplete payment for your registration:</p>
                
                <div class="transaction-details">
                    <div class="detail-row">
                        <span class="detail-label">Registration:</span>
                        <span class="detail-value">${retryData.registrationNumber}</span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Amount:</span>
                        <span class="detail-value">USD $${retryData.totalAmount}</span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Delegates:</span>
                        <span class="detail-value">${retryData.formData.delegateCount} ${retryData.formData.delegateCount === 1 ? 'delegate' : 'delegates'}</span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Contact:</span>
                        <span class="detail-value">${retryData.formData.contact?.fullName || 'Not specified'}</span>
                    </div>
                </div>
                
                <p class="retry-question">Would you like to complete the payment or start a new registration?</p>
                <div class="recovery-actions">
                    <button class="btn btn-primary" id="retryPaymentBtn">Complete Payment</button>
                    <button class="btn btn-ghost" id="startNewRegBtn">Start New Registration</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        
        // Store reference to this instance for the event handlers
        const formInstance = this;
        
        // Add event listeners after modal is added to DOM
        document.getElementById('retryPaymentBtn').addEventListener('click', function() {
            formInstance.retryPayment();
        });
        
        document.getElementById('startNewRegBtn').addEventListener('click', function() {
            formInstance.startNewRegistration();
        });
    }
    
    showDataRecoveryOption() {
        const modal = document.createElement('div');
        modal.className = 'recovery-modal';
        modal.innerHTML = `
            <div class="recovery-modal-content">
                <div class="recovery-icon">💾</div>
                <h3>Restore Previous Data?</h3>
                <p>We found a previous registration that wasn't completed. Would you like to continue where you left off?</p>
                <div class="recovery-actions">
                    <button class="btn btn-primary" id="restoreDataBtn">Continue Registration</button>
                    <button class="btn btn-ghost" id="startFreshBtn">Start Fresh</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        
        // Store reference to this instance for the event handlers
        const formInstance = this;
        
        // Add event listeners after modal is added to DOM
        document.getElementById('restoreDataBtn').addEventListener('click', function() {
            formInstance.restoreSavedData();
        });
        
        document.getElementById('startFreshBtn').addEventListener('click', function() {
            formInstance.startFresh();
        });
    }
    
    retryPayment() {
        const retryData = this.getPaymentRetryData();
        if (!retryData) {
            alert('Payment retry data not found. Please start a new registration.');
            this.startNewRegistration();
            return;
        }
        
        // Restore form data
        this.formData = retryData.formData;
        this.restoreFormFields();
        
        // Temporarily remove required attributes to avoid validation issues when jumping to Step 5
        this.temporarilyDisableValidation();
        
        // Set payment retry mode flag
        this.isPaymentRetry = true;
        
        // Go directly to payment step
        this.currentStep = 5;
        this.showStep(5);
        this.populateReview();
        
        // Update payment summary using data directly from formData (not DOM elements)
        this.updatePaymentSummaryFromData();
        
        // Hide back button during payment retry
        this.hideBackButtonForRetry();
        
        // Close modal
        document.querySelector('.recovery-modal').remove();
        
        // Show retry message
        this.showRetryMessage(retryData);
    }
    
    temporarilyDisableValidation() {
        // Store original required attributes and temporarily remove them
        const requiredFields = document.querySelectorAll('input[required], select[required]');
        requiredFields.forEach(field => {
            if (!field.closest('#step5')) { // Don't affect payment step fields
                field.setAttribute('data-was-required', 'true');
                field.removeAttribute('required');
            }
        });
    }
    
    hideBackButtonForRetry() {
        // Hide the back button in payment step during retry
        const paymentStepBackBtn = document.querySelector('#step5 .btn.btn-ghost');
        if (paymentStepBackBtn && paymentStepBackBtn.textContent.includes('Back')) {
            paymentStepBackBtn.style.display = 'none';
            paymentStepBackBtn.setAttribute('data-hidden-for-retry', 'true');
        }
    }
    
    showBackButton() {
        // Restore the back button visibility
        const paymentStepBackBtn = document.querySelector('#step5 .btn.btn-ghost[data-hidden-for-retry]');
        if (paymentStepBackBtn) {
            paymentStepBackBtn.style.display = '';
            paymentStepBackBtn.removeAttribute('data-hidden-for-retry');
        }
        this.isPaymentRetry = false;
    }
    
    restoreValidation() {
        // Restore required attributes
        const fieldsToRestore = document.querySelectorAll('[data-was-required="true"]');
        fieldsToRestore.forEach(field => {
            field.setAttribute('required', '');
            field.removeAttribute('data-was-required');
        });
    }
    
    showRetryMessage(retryData) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'retry-message';
        messageDiv.innerHTML = `
            <div class="alert alert-info">
                <div class="retry-header">
                    <strong>Payment Retry</strong>
                    <small>Complete your payment to finalize registration</small>
                </div>
                <div class="retry-details">
                    <div class="retry-detail-row">
                        <span>Registration:</span>
                        <strong>${retryData.registrationNumber}</strong>
                    </div>
                    <div class="retry-detail-row">
                        <span>Amount:</span>
                        <strong>USD $${retryData.totalAmount}</strong>
                    </div>
                    <div class="retry-detail-row">
                        <span>Delegates:</span>
                        <strong>${retryData.formData.delegateCount} ${retryData.formData.delegateCount === 1 ? 'delegate' : 'delegates'}</strong>
                    </div>
                    <div class="retry-detail-row">
                        <span>Contact:</span>
                        <strong>${retryData.formData.contact?.fullName || 'Not specified'}</strong>
                    </div>
                </div>
            </div>
        `;
        
        const paymentStep = document.getElementById('step5');
        paymentStep.insertBefore(messageDiv, paymentStep.firstChild);
    }
    
    restoreSavedData() {
        if (this.loadSavedFormData()) {
            // Go to the saved step
            this.goToStep(this.currentStep);
            document.querySelector('.recovery-modal').remove();
            
            // Show restoration message
            const messageDiv = document.createElement('div');
            messageDiv.className = 'alert alert-success';
            messageDiv.innerHTML = '<strong>Data Restored!</strong> Your previous registration data has been restored.';
            document.querySelector('.container').insertBefore(messageDiv, document.querySelector('.registration-form'));
            
            setTimeout(() => messageDiv.remove(), 5000);
        } else {
            alert('Failed to restore data. Starting fresh.');
            this.startFresh();
        }
    }
    
    startFresh() {
        this.clearSavedFormData();
        document.querySelector('.recovery-modal').remove();
    }
    
    startNewRegistration() {
        this.showBackButton(); // Restore back button visibility
        this.clearSavedFormData();
        document.querySelector('.recovery-modal').remove();
        location.reload();
    }


    setupPricingOptions() {
        const earlyBirdOption = document.getElementById('earlyBirdOption');
        const standardOption = document.getElementById('standardOption');
        const earlyBirdRadio = document.getElementById('earlyBird');
        const standardRadio = document.getElementById('standard');
        const standardLabel = standardRadio.nextElementSibling;
        
        // Check database setting for early bird status (not deadline-based)
        if (this.config.pricing.earlyBirdActive) {
            // Early bird is enabled in database
            earlyBirdRadio.disabled = false;
            earlyBirdRadio.checked = true;
            standardRadio.disabled = true;
            standardLabel.classList.add('disabled');
            this.formData.delegateType = 'earlyBird';
            
            // Show countdown timer if early bird is active
            const countdownTimer = document.getElementById('countdownTimer');
            if (countdownTimer) {
                countdownTimer.style.display = 'block';
            }
        } else {
            // Early bird is disabled in database, use standard pricing
            earlyBirdRadio.disabled = true;
            earlyBirdRadio.checked = false;
            standardRadio.disabled = false;
            standardRadio.checked = true;
            standardLabel.classList.remove('disabled');
            this.formData.delegateType = 'standard';
            
            // Hide countdown timer when early bird is disabled
            const countdownTimer = document.getElementById('countdownTimer');
            if (countdownTimer) {
                countdownTimer.style.display = 'none';
            }
        }
    }

    startCountdown() {
        // Only show countdown if early bird is active in database
        if (!this.config.pricing.earlyBirdActive) {
            return;
        }
        
        const deadline = new Date(this.config.pricing.earlyBirdDeadline);
        const timerDisplay = document.getElementById('timerDisplay');
        
        if (!timerDisplay) return;
        
        this.countdownInterval = setInterval(() => {
            const now = new Date();
            const timeLeft = deadline - now;
            
            if (timeLeft <= 0) {
                // Deadline reached - just show expired message, don't change pricing
                clearInterval(this.countdownInterval);
                timerDisplay.textContent = 'Deadline passed';
                return;
            }
            
            const days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
            const hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);
            
            timerDisplay.textContent = `${days}d ${hours}h ${minutes}m ${seconds}s`;
        }, 1000);
    }



    bindEvents() {
        // Set up real-time validation error clearing
        this.setupRealtimeValidation();

        // Table selections
        document.querySelectorAll('input[name="tableType"]').forEach(radio => {
            radio.addEventListener('change', () => {
                this.updateTableSelections();
                this.updateSummary();
            });
        });

        // Table count
        const tableCountInput = document.getElementById('tableCount');
        if (tableCountInput) {
            tableCountInput.addEventListener('input', (e) => {
                this.updateTableSelections();
                this.updateSummary();
            });
        }
        
        // Sponsorship selections
        document.querySelectorAll('input[name="sponsorshipType"]').forEach(radio => {
            radio.addEventListener('change', () => {
                this.updateSponsorshipSelections();
                this.updateSummary();
            });
        });
        
        // Sponsorship count
        const sponsorshipCountInput = document.getElementById('sponsorshipCount');
        if (sponsorshipCountInput) {
            sponsorshipCountInput.addEventListener('input', (e) => {
                this.updateSponsorshipSelections();
                this.updateSummary();
            });
        }
        
        // Other Sponsorship selections
        document.querySelectorAll('input[name="otherSponsorshipType"]').forEach(radio => {
            radio.addEventListener('change', () => {
                this.updateOtherSponsorshipSelections();
                this.updateSummary();
            });
        });
        
        // Other Sponsorship count
        const otherSponsorshipCountInput = document.getElementById('otherSponsorshipCount');
        if (otherSponsorshipCountInput) {
            otherSponsorshipCountInput.addEventListener('input', (e) => {
                this.updateOtherSponsorshipSelections();
                this.updateSummary();
            });
        }

        // Form submission
        document.getElementById('registrationForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.submitForm();
        });
    }

    setupRealtimeValidation() {
        // Add input event listeners to all required fields to clear errors in real-time
        const formElement = document.getElementById('registrationForm');
        
        formElement.addEventListener('input', (e) => {
            const input = e.target;
            
            // Only process required inputs
            if (!input.required && !input.hasAttribute('required')) return;
            
            // If the field now has a value, clear the error
            if (input.value.trim()) {
                input.classList.remove('error');
                const errorMsg = input.parentNode.querySelector('.error-message');
                if (errorMsg) errorMsg.remove();
            }
        }, true);
        
        // Add change event listener for select dropdowns
        formElement.addEventListener('change', (e) => {
            const input = e.target;
            
            // Only process required inputs
            if (!input.required && !input.hasAttribute('required')) return;
            
            // If the field now has a value, clear the error
            if (input.value && input.value.trim()) {
                input.classList.remove('error');
                const errorMsg = input.parentNode.querySelector('.error-message');
                if (errorMsg) errorMsg.remove();
            }
        }, true);
    }

    bindTableEvents() {
        // Use event delegation on the form container
        const form = document.getElementById('registrationForm');
        if (form) {
            form.addEventListener('click', (e) => {
                // Check if clicked element is a table label or contains a table radio
                const label = e.target.closest('.table-label');
                if (label) {
                    const radioId = label.getAttribute('for');
                    const radio = document.getElementById(radioId);
                    if (radio && radio.name === 'tableType') {
                        // Ensure radio is selected
                        radio.checked = true;
                        // Trigger update
                        setTimeout(() => {
                            this.updateTableSelections();
                            this.updateSummary();
                        }, 10);
                    }
                }
            });
        }
    }

    renderDynamicCategories(frontendConfig) {
        if (!frontendConfig) return;
        
        // Store frontend config for use in other methods
        this.frontendConfig = frontendConfig;
        
        // Render delegate passes section
        this.renderDelegatePassesSection(frontendConfig);
        
        // Render table presentations section
        this.renderTablePresentationsSection(frontendConfig);
        
        // Render sponsorship section
        this.renderSponsorshipSection(frontendConfig);
        
        // Render other sponsorship section
        this.renderOtherSponsorshipSection(frontendConfig);
        
        // Start live countdown updates
        this.startCountdownTimer();
        
        // Immediately update all countdown displays
        this.updateCountdownDisplays();
        
        // Update summary with initial selection (with slight delay to ensure DOM is ready)
        setTimeout(() => {
            this.updateSummary();
        }, 100);
    }

    // Start live countdown timer
    startCountdownTimer() {
        // Clear any existing timer
        if (this.countdownInterval) {
            clearInterval(this.countdownInterval);
        }
        
        // Update countdown every second
        this.countdownInterval = setInterval(() => {
            this.updateCountdownDisplays();
        }, 1000);
    }

    // Update all countdown displays
    updateCountdownDisplays() {
        const countdownElements = document.querySelectorAll('.current-tier-badge.countdown, .tier-status.countdown');
        let needsRefresh = false;
        
        countdownElements.forEach(element => {
            const endDate = element.dataset.endDate;
            if (endDate) {
                const timeDiff = new Date(endDate) - new Date();
                if (timeDiff > 0) {
                    // Update the countdown text without "Ends in" prefix
                    element.textContent = this.formatCountdown(timeDiff);
                } else {
                    // Time expired - mark for refresh
                    needsRefresh = true;
                    
                    // Update the text to show expired
                    if (element.closest('.tier-dates')) {
                        // For tier dates, show "Expired"
                        const dateInfo = element.previousElementSibling;
                        if (dateInfo && dateInfo.classList.contains('date-info')) {
                            dateInfo.textContent = 'Expired';
                        }
                        element.textContent = new Date(endDate).toLocaleDateString('en-US', { 
                            month: 'short', 
                            day: 'numeric', 
                            year: 'numeric' 
                        });
                        element.classList.remove('countdown');
                    } else {
                        // For other countdown elements
                        element.textContent = 'Expired';
                    }
                }
            }
        });
        
        // If any timer expired, schedule a refresh after showing the expired state briefly
        if (needsRefresh) {
            setTimeout(() => {
                location.reload();
            }, 3000); // Wait 3 seconds before refreshing to show the expired state
        }
    }
        
    renderDelegatePassesSection(frontendConfig) {
        const delegateSection = document.querySelector('.pass-section:first-child');
        if (!delegateSection) return;
        
        const delegateConfig = frontendConfig.delegatePasses;
        
        if (!delegateConfig.products || delegateConfig.products.length === 0) {
            delegateSection.style.display = 'none';
            return;
        }
        
        // Update section description
        const description = delegateSection.querySelector('p.muted');
        if (description) {
            const sectionDescription = delegateConfig.description;
            description.textContent = sectionDescription;
        }
        
        // Find the pricing options container
        const pricingOptions = delegateSection.querySelector('.pricing-options');
        if (!pricingOptions) return;
        
        // Clear existing options
        pricingOptions.innerHTML = '';
        
        // Render each product as a pricing option
        delegateConfig.products.forEach((product, index) => {
            const isFirst = index === 0;
            const optionHtml = this.createDelegateOptionHTML(product, isFirst);
            pricingOptions.innerHTML += optionHtml;
        });
        
        // Add event listeners to the dynamically created delegate options
        const delegateInputs = pricingOptions.querySelectorAll('input[name="delegateType"]');
        delegateInputs.forEach(input => {
            input.addEventListener('change', () => {
                this.updateDelegateSelections();
                this.updateSummary();
            });
        });

        // Add event listeners to quantity inputs
        const delegateQuantityInputs = pricingOptions.querySelectorAll('.quantity-input');
        delegateQuantityInputs.forEach(input => {
            input.addEventListener('input', (e) => {
                this.updateQuantityTotal(e.target);
                this.updateDelegateSelections();
                this.updateSummary();
            });
        });
        
        delegateSection.style.display = 'block';
    }

    renderTablePresentationsSection(frontendConfig) {
        const tableSection = document.querySelector('.pass-section:nth-child(2)');
        if (!tableSection) return;
        
        const tableConfig = frontendConfig.tablePresentations;
        
        if (!tableConfig || !tableConfig.products || tableConfig.products.length === 0) {
            tableSection.style.display = 'none';
            return;
        }
        
        // Update section description
        const description = tableSection.querySelector('p.muted');
        if (description) {
            const sectionDescription = tableConfig.description;
            description.textContent = sectionDescription;
        }
        
        // Find the table options container
        const tableOptions = tableSection.querySelector('.table-options');
        if (!tableOptions) return;
        
        // Clear existing options
        tableOptions.innerHTML = '';
        
        // Render each product as a table option
        tableConfig.products.forEach(product => {
            const optionHtml = this.createTableOptionHTML(product);
            tableOptions.innerHTML += optionHtml;
        });
        
        // Add event listeners to the dynamically created table options
        const tableInputs = tableOptions.querySelectorAll('input[name="tableType"]');
        tableInputs.forEach(input => {
            input.addEventListener('change', () => {
                this.updateTableSelections();
                this.updateSummary();
            });
        });

        // Add event listeners to quantity inputs
        const tableQuantityInputs = tableOptions.querySelectorAll('.quantity-input');
        tableQuantityInputs.forEach(input => {
            input.addEventListener('input', (e) => {
                this.updateQuantityTotal(e.target);
                this.updateTableSelections();
                this.updateSummary();
            });
        });
        
        tableSection.style.display = 'block';
    }
    
    renderSponsorshipSection(frontendConfig) {
        // Use a more specific selector that targets the section by its heading text
        const sponsorshipSection = Array.from(document.querySelectorAll('.pass-section'))
            .find(section => section.querySelector('.card-header h3')?.textContent.trim() === 'Sponsorship');
        if (!sponsorshipSection) return;
        
        const sponsorshipConfig = frontendConfig.sponsorship;
        
        if (!sponsorshipConfig || !sponsorshipConfig.products || sponsorshipConfig.products.length === 0) {
            sponsorshipSection.style.display = 'none';
            return;
        }
        
        // Update section description
        const description = sponsorshipSection.querySelector('p.muted');
        if (description) {
            const sectionDescription = sponsorshipConfig.description;
            description.textContent = sectionDescription;
        }
        
        // Find the sponsorship options container
        const sponsorshipOptions = sponsorshipSection.querySelector('.sponsorship-options');
        if (!sponsorshipOptions) return;
        
        // Clear existing options
        sponsorshipOptions.innerHTML = '';
        
        // Render each product as a sponsorship option
        sponsorshipConfig.products.forEach(product => {
            const optionHtml = this.createSponsorshipOptionHTML(product);
            sponsorshipOptions.innerHTML += optionHtml;
        });
        
        // Add event listeners to the dynamically created sponsorship options
        const sponsorshipInputs = sponsorshipOptions.querySelectorAll('input[name="sponsorshipType"]');
        sponsorshipInputs.forEach(input => {
            input.addEventListener('change', () => {
                this.updateSponsorshipSelections();
                this.updateSummary();
            });
        });

        // Add event listeners to quantity inputs
        const quantityInputs = sponsorshipOptions.querySelectorAll('.quantity-input');
        quantityInputs.forEach(input => {
            input.addEventListener('input', (e) => {
                this.updateQuantityTotal(e.target);
                this.updateSponsorshipSelections();
                this.updateSummary();
            });
        });
        
        sponsorshipSection.style.display = 'block';
    }
    
    renderOtherSponsorshipSection(frontendConfig) {
        // Use a more specific selector that targets the section by its heading text
        const otherSponsorshipSection = Array.from(document.querySelectorAll('.pass-section'))
            .find(section => section.querySelector('.card-header h3')?.textContent.trim() === 'Other Sponsorship');
        if (!otherSponsorshipSection) return;
        
        const otherSponsorshipConfig = frontendConfig.otherSponsorship;
        
        if (!otherSponsorshipConfig || !otherSponsorshipConfig.products || otherSponsorshipConfig.products.length === 0) {
            otherSponsorshipSection.style.display = 'none';
            return;
        }
        
        // Update section description
        const description = otherSponsorshipSection.querySelector('p.muted');
        if (description) {
            const sectionDescription = otherSponsorshipConfig.description;
            description.textContent = sectionDescription;
        }
        
        // Find the other sponsorship options container
        const otherSponsorshipOptions = otherSponsorshipSection.querySelector('.other-sponsorship-options');
        if (!otherSponsorshipOptions) return;
        
        // Clear existing options
        otherSponsorshipOptions.innerHTML = '';
        
        // Render each product as an other sponsorship option
        otherSponsorshipConfig.products.forEach(product => {
            const optionHtml = this.createOtherSponsorshipOptionHTML(product);
            otherSponsorshipOptions.innerHTML += optionHtml;
        });
        
        // Add event listeners to the dynamically created other sponsorship options
        const otherSponsorshipInputs = otherSponsorshipOptions.querySelectorAll('input[name="otherSponsorshipType"]');
        otherSponsorshipInputs.forEach(input => {
            input.addEventListener('change', () => {
                this.updateOtherSponsorshipSelections();
                this.updateSummary();
            });
        });

        // Add event listeners to quantity inputs
        const otherQuantityInputs = otherSponsorshipOptions.querySelectorAll('.quantity-input');
        otherQuantityInputs.forEach(input => {
            input.addEventListener('input', (e) => {
                this.updateQuantityTotal(e.target);
                this.updateOtherSponsorshipSelections();
                this.updateSummary();
            });
        });
        
        otherSponsorshipSection.style.display = 'block';
    }

    // Helper method to create delegate pass option HTML with pricing tiers
    createDelegateOptionHTML(product, isDefault = false) {
        const optionId = `delegate_${product.id}`;
        const quantityId = `delegate_qty_${product.id}`;
        
        // Find current active tier or use base price
        const activeTier = product.pricing_tiers?.find(tier => tier.is_current);
        const currentPrice = activeTier ? activeTier.price : product.base_price;
        
        // Check if this pricing option should be disabled (only upcoming/expired tiers available)
        const hasCurrentActiveTier = activeTier && activeTier.is_current;
        const basePriceIsActive = !activeTier; // When no active tier, base price is current
        const onlyUpcomingTiers = product.pricing_tiers?.length > 0 && product.pricing_tiers.every(tier => tier.status === 'upcoming' || tier.status === 'expired');
        const isDisabled = !hasCurrentActiveTier && !basePriceIsActive && onlyUpcomingTiers;
        
        // Calculate current tier name and countdown
        let currentTierName = '';
        let currentTierCountdown = '';
        
        if (!activeTier) {
            // Base price is current - no countdown for default tier
            // Just use the default tier name from database
            currentTierName = product.default_tier_name || '';
        } else {
            // Use tier name from database with no fallback
            currentTierName = activeTier.tier_name || '';
            
            // Only show countdown for active tiers
            if (activeTier.status === 'active' && activeTier.valid_until) {
                const endDate = new Date(activeTier.valid_until);
                const now = new Date();
                const timeDiff = endDate - now;
                
                if (timeDiff > 0) {
                    currentTierCountdown = this.formatCountdown(timeDiff);
                }
            }
        }
        
        // Use tier name as display name, countdown will be shown separately
        const displayTierName = currentTierName;
        
        // Calculate end date for data attribute
        let endDateForCountdown = '';
        if (!activeTier) {
            const nextTier = this.getNextUpcomingTier(product.pricing_tiers);
            if (nextTier && nextTier.valid_from) {
                endDateForCountdown = nextTier.valid_from;
            }
        } else if (activeTier.valid_until) {
            endDateForCountdown = activeTier.valid_until;
        }
        
        // Generate pricing tiers display (always show base price if no tiers)
        const countdownInfo = currentTierCountdown ? {
            countdown: currentTierCountdown,
            endDate: endDateForCountdown
        } : null;
        
        // Generate pricing tiers HTML
        const pricingTiersHTML = this.generatePricingTiersDisplay(
            product.pricing_tiers,
            product.base_price,
            product.currency || 'USD',
            countdownInfo,
            product.default_tier_name
        );
        
        return `
            <div class="pricing-option">
                <input type="checkbox" id="${optionId}" name="delegateType" value="${product.product_code}" ${isDisabled ? 'disabled' : ''} ${isDefault ? 'checked' : ''}
                       onchange="this.closest('.pricing-option').querySelector('.quantity-control').style.display = this.checked ? 'flex' : 'none'; registrationForm.updateDelegateSelections(); registrationForm.updateSummary();">
                <label for="${optionId}" class="pricing-label enhanced-label">
                    <div class="pricing-header">
                        <div class="pricing-details">
                            <strong>${product.name}</strong>
                            ${product.description && product.description.trim() && product.description.replace(/<br\s*\/?>/gi, '').trim() ? `<div class="pricing-note">${product.description}</div>` : ''}
                        </div>
                    </div>
                    ${pricingTiersHTML}
                    <div class="quantity-control" style="display: ${isDefault ? 'flex' : 'none'};">
                        <label for="${quantityId}" class="quantity-label">No. of Delegates:</label>
                        <div class="delegate-quantity-controls">
                            <button type="button" class="qty-btn" onclick="registrationForm.adjustProductQuantity('${quantityId}', -1)">−</button>
                            <input type="number" id="${quantityId}" name="delegate_quantity_${product.product_code}" 
                                   min="1" max="99" value="1" class="delegate-qty-input"
                                   onchange="registrationForm.updateDelegateSelections(); registrationForm.updateSummary();">
                            <button type="button" class="qty-btn" onclick="registrationForm.adjustProductQuantity('${quantityId}', 1)">+</button>
                        </div>
                        <span class="total-price" id="total_${optionId}">${product.currency || 'USD'} $${currentPrice}</span>
                    </div>
                </label>
            </div>
        `;
    }

    // Helper method to get the next upcoming tier
    getNextUpcomingTier(pricingTiers) {
        if (!pricingTiers || pricingTiers.length === 0) return null;
        
        const upcomingTiers = pricingTiers
            .filter(tier => tier.status === 'upcoming' && tier.valid_from)
            .sort((a, b) => new Date(a.valid_from) - new Date(b.valid_from));
        
        return upcomingTiers.length > 0 ? upcomingTiers[0] : null;
    }

    // Helper method to generate pricing tiers display
    generatePricingTiersDisplay(pricingTiers, basePrice, currency, countdownInfo = null, defaultTierName = null) {
        // If no pricing tiers exist, return empty string - will use table-style layout
        if (!pricingTiers || pricingTiers.length === 0) {
            return '';
        }
        
        let tiersHTML = '<div class="pricing-tiers-container">';
        
        // Add base price as default tier if no active tier
        const hasActiveTier = pricingTiers.some(tier => tier.is_current);
        if (!hasActiveTier) {
            // Create countdown badge for default tier
            let countdownBadge = '';
            
            if (countdownInfo && countdownInfo.countdown) {
                // Show countdown with data attribute for live updates
                countdownBadge = `<div class="tier-status countdown" data-end-date="${countdownInfo.endDate}">${countdownInfo.countdown}</div>`;
            } else {
                // No countdown info available - show simple active status
                countdownBadge = '<div class="tier-status active"></div>';
            }
            
            // Use default tier name from database, or empty if not available (following user's no-fallback rule)
            const tierName = defaultTierName || '';
            
            tiersHTML += `
                <div class="pricing-tier current active-tier">
                    <div class="tier-info">
                        <span class="tier-name">${tierName}</span>
                        <span class="tier-price">${currency} $${basePrice}</span>
                    </div>
                    ${countdownBadge}
                </div>
            `;
        }
        
        // Add all pricing tiers
        pricingTiers.forEach(tier => {
            const statusClass = tier.status;
            const statusText = this.getTierStatusText(tier);
            const isCurrentClass = tier.is_current ? 'active-tier' : '';
            const isDisabled = tier.status === 'upcoming' || tier.status === 'expired';
            
            tiersHTML += `
                <div class="pricing-tier ${statusClass} ${isCurrentClass} ${isDisabled ? 'disabled' : ''}">
                    <div class="tier-info">
                        <span class="tier-name">${tier.tier_name}</span>
                        <span class="tier-price">${currency} $${tier.price}</span>
                    </div>
                    <div class="tier-status ${statusClass}">${statusText}</div>
                    ${tier.valid_from || tier.valid_until ? this.getTierDateInfo(tier) : ''}
                </div>
            `;
        });
        
        tiersHTML += '</div>';
        return tiersHTML;
    }

    // Helper method to get tier status text (no labels for individual tiers)
    getTierStatusText(tier) {
        // Return empty string - no status labels needed in individual tiers
        return '';
    }

    // Helper method to format countdown with full time display
    formatCountdown(timeDiff) {
        const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
        const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);
        
        // Show countdown without "Ends in" text, just the time values
        if (days > 0) {
            return `${days}d ${hours}h ${minutes}m ${seconds}s`;
        } else if (hours > 0) {
            return `${hours}h ${minutes}m ${seconds}s`;
        } else if (minutes > 0) {
            return `${minutes}m ${seconds}s`;
        } else {
            return `${seconds}s`;
        }
    }

    // Helper method to get tier date information with countdown timers only for active tiers
    getTierDateInfo(tier) {
        const formatDate = (dateStr) => {
            if (!dateStr) return '';
            const date = new Date(dateStr);
            return date.toLocaleDateString('en-US', { 
                month: 'short', 
                day: 'numeric', 
                year: 'numeric' 
            });
        };

        let dateInfo = '<div class="tier-dates">';
        
        if (tier.status === 'upcoming' && tier.valid_from) {
            // For upcoming tiers, show static date (as before)
            dateInfo += `<span class="date-info">Available from ${formatDate(tier.valid_from)}</span>`;
        } else if (tier.status === 'active') {
            if (tier.valid_until) {
                // For active tiers, show countdown to end date without "Ends in" text
                const endDate = new Date(tier.valid_until);
                const now = new Date();
                const timeLeft = endDate - now;
                
                if (timeLeft > 0) {
                    // Show countdown to tier end without any prefix text
                    dateInfo += `<span class="tier-status countdown" data-end-date="${tier.valid_until}">${this.formatCountdown(timeLeft)}</span>`;
                } else {
                    // Fallback to static date if calculation fails
                    dateInfo += `<span class="date-info">Until ${formatDate(tier.valid_until)}</span>`;
                }
            }
        } else if (tier.status === 'expired' && tier.valid_until) {
            // For expired tiers, show static expired date
            dateInfo += `<span class="date-info">Expired ${formatDate(tier.valid_until)}</span>`;
        }
        
        dateInfo += '</div>';
        return dateInfo;
    }

    // Helper method to create table presentation option HTML
    createTableOptionHTML(product) {
        const optionId = `table_${product.id}`;
        const quantityId = `table_qty_${product.id}`;
        const price = product.base_price;
        
        return `
            <div class="pricing-option">
                <input type="checkbox" id="${optionId}" name="tableType" value="${product.product_code}"
                       onchange="this.closest('.pricing-option').querySelector('.quantity-control').style.display = this.checked ? 'flex' : 'none'; registrationForm.updateTableSelections(); registrationForm.updateSummary();">
                <label for="${optionId}" class="pricing-label">
                    <div class="pricing-details">
                        <strong>${product.name}</strong>
                        <span class="price">${product.currency} $${price}</span>
                    </div>
                    ${product.description ? `<div class="pricing-note">${product.description}</div>` : ''}
                    <div class="quantity-control" style="display: none;">
                        <label for="${quantityId}" class="quantity-label">Qty:</label>
                        <div class="delegate-quantity-controls">
                            <button type="button" class="qty-btn" onclick="registrationForm.adjustProductQuantity('${quantityId}', -1)">−</button>
                            <input type="number" id="${quantityId}" name="table_quantity_${product.product_code}" 
                                   min="1" max="99" value="1" class="delegate-qty-input"
                                   onchange="registrationForm.updateTableSelections(); registrationForm.updateSummary();">
                            <button type="button" class="qty-btn" onclick="registrationForm.adjustProductQuantity('${quantityId}', 1)">+</button>
                        </div>
                        <span class="total-price" id="total_${optionId}">${product.currency} $${price}</span>
                    </div>
                </label>
            </div>
        `;
    }
    
    // Helper method to create sponsorship option HTML
    createSponsorshipOptionHTML(product) {
        const optionId = `sponsorship_${product.id}`;
        const quantityId = `sponsorship_qty_${product.id}`;
        const price = product.base_price;
        
        return `
            <div class="pricing-option">
                <input type="checkbox" id="${optionId}" name="sponsorshipType" value="${product.product_code}" 
                       onchange="this.closest('.pricing-option').querySelector('.quantity-control').style.display = this.checked ? 'flex' : 'none'; registrationForm.updateSponsorshipSelections(); registrationForm.updateSummary();">
                <label for="${optionId}" class="pricing-label">
                    <div class="pricing-details">
                        <strong>${product.name}</strong>
                        <span class="price">${product.currency} $${price}</span>
                    </div>
                    ${product.description ? `<div class="pricing-note">${product.description}</div>` : ''}
                    <div class="quantity-control" style="display: none;">
                        <label for="${quantityId}" class="quantity-label">Qty:</label>
                        <div class="delegate-quantity-controls">
                            <button type="button" class="qty-btn" onclick="registrationForm.adjustProductQuantity('${quantityId}', -1)">−</button>
                            <input type="number" id="${quantityId}" name="sponsorship_quantity_${product.product_code}" 
                                   min="1" max="99" value="1" class="delegate-qty-input"
                                   onchange="registrationForm.updateSponsorshipSelections(); registrationForm.updateSummary();">
                            <button type="button" class="qty-btn" onclick="registrationForm.adjustProductQuantity('${quantityId}', 1)">+</button>
                        </div>
                        <span class="total-price" id="total_${optionId}">${product.currency} $${price}</span>
                    </div>
                </label>
            </div>
        `;
    }
    
    // Helper method to create other sponsorship option HTML
    createOtherSponsorshipOptionHTML(product) {
        const optionId = `other_sponsorship_${product.id}`;
        const quantityId = `other_sponsorship_qty_${product.id}`;
        const price = product.base_price;
        
        return `
            <div class="pricing-option">
                <input type="checkbox" id="${optionId}" name="otherSponsorshipType" value="${product.product_code}"
                       onchange="this.closest('.pricing-option').querySelector('.quantity-control').style.display = this.checked ? 'flex' : 'none'; registrationForm.updateOtherSponsorshipSelections(); registrationForm.updateSummary();">
                <label for="${optionId}" class="pricing-label">
                    <div class="pricing-details">
                        <strong>${product.name}</strong>
                        <span class="price">${product.currency} $${price}</span>
                    </div>
                    ${product.description ? `<div class="pricing-note">${product.description}</div>` : ''}
                    <div class="quantity-control" style="display: none;">
                        <label for="${quantityId}" class="quantity-label">Qty:</label>
                        <div class="delegate-quantity-controls">
                            <button type="button" class="qty-btn" onclick="registrationForm.adjustProductQuantity('${quantityId}', -1)">−</button>
                            <input type="number" id="${quantityId}" name="other_sponsorship_quantity_${product.product_code}" 
                                   min="1" max="99" value="1" class="delegate-qty-input"
                                   onchange="registrationForm.updateOtherSponsorshipSelections(); registrationForm.updateSummary();">
                            <button type="button" class="qty-btn" onclick="registrationForm.adjustProductQuantity('${quantityId}', 1)">+</button>
                        </div>
                        <span class="total-price" id="total_${optionId}">${product.currency} $${price}</span>
                    </div>
                </label>
            </div>
        `;
    }

    // Helper method to adjust product quantity using +/- buttons
    adjustProductQuantity(inputId, change) {
        const input = document.getElementById(inputId);
        if (!input) return;
        
        const currentValue = parseInt(input.value) || 1;
        const newValue = Math.max(1, Math.min(99, currentValue + change));
        
        if (newValue !== currentValue) {
            input.value = newValue;
            
            // Trigger change event to update totals and summary
            const changeEvent = new Event('change', { bubbles: true });
            input.dispatchEvent(changeEvent);
            
            // Update the total price display for this specific product
            this.updateQuantityTotal(input);
        }
    }

    // Helper method to update quantity total display
    updateQuantityTotal(quantityInput) {
        const pricingOption = quantityInput.closest('.pricing-option');
        const totalPriceSpan = pricingOption.querySelector('.total-price');
        let unitPriceText = '';
        let unitPrice = 0;
        let currency = 'USD';
        
        // Check if this is a delegate product with pricing tiers
        const activeTierPrice = pricingOption.querySelector('.pricing-tier.active .tier-price');
        if (activeTierPrice) {
            // For delegate products with pricing tiers
            unitPriceText = activeTierPrice.textContent;
        } else {
            // For other products with simple price display
            const priceElement = pricingOption.querySelector('.price');
            if (priceElement) {
                unitPriceText = priceElement.textContent;
            }
        }
        
        if (unitPriceText) {
            // Extract unit price from text like "USD $500"
            const unitPriceMatch = unitPriceText.match(/\$(\d+(?:,\d{3})*(?:\.\d{2})?)/);
            if (unitPriceMatch) {
                unitPrice = parseFloat(unitPriceMatch[1].replace(/,/g, ''));
                const quantity = parseInt(quantityInput.value) || 1;
                const total = unitPrice * quantity;
                
                // Extract currency (USD)
                const currencyMatch = unitPriceText.match(/^([A-Z]{3})/);
                if (currencyMatch) {
                    currency = currencyMatch[1];
                }
                
                // Update total price display
                totalPriceSpan.textContent = `${currency} $${total.toLocaleString()}`;
            }
        }
    }

    updateDelegateSelections() {
        this.formData.delegateProducts = [];
        const selectedDelegates = document.querySelectorAll('input[name="delegateType"]:checked');
        
        selectedDelegates.forEach(selectedDelegate => {
            if (selectedDelegate) {
                // Find the quantity input for this specific delegate option
                const pricingOption = selectedDelegate.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const quantity = parseInt(quantityInput?.value) || 1;
                
                this.formData.delegateProducts.push({
                    type: selectedDelegate.value,
                    count: quantity
                });
            }
        });
        
        // Update total delegate count for backward compatibility
        this.formData.delegateCount = this.formData.delegateProducts ? 
            this.formData.delegateProducts.reduce((total, delegate) => total + delegate.count, 0) : 0;
        
        // Update the delegate count input to reflect the total
        const delegateCountInput = document.getElementById('delegateCount');
        if (delegateCountInput) {
            delegateCountInput.value = this.formData.delegateCount;
        }
    }

    updateTableSelections() {
        this.formData.tables = [];
        const selectedTables = document.querySelectorAll('input[name="tableType"]:checked');
        
        selectedTables.forEach(selectedTable => {
            if (selectedTable) {
                // Find the quantity input for this specific table option
                const pricingOption = selectedTable.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const quantity = parseInt(quantityInput?.value) || 1;
                
                this.formData.tables.push({
                    type: selectedTable.value,
                    count: quantity
                });
            }
        });
    }
    
    updateSponsorshipSelections() {
        this.formData.sponsorships = [];
        const selectedSponsorships = document.querySelectorAll('input[name="sponsorshipType"]:checked');
        
        selectedSponsorships.forEach(selectedSponsorship => {
            if (selectedSponsorship) {
                // Find the quantity input for this specific sponsorship option
                const pricingOption = selectedSponsorship.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const quantity = parseInt(quantityInput?.value) || 1;
                
                this.formData.sponsorships.push({
                    type: selectedSponsorship.value,
                    count: quantity
                });
            }
        });
    }
    
    updateOtherSponsorshipSelections() {
        this.formData.otherSponsorships = [];
        const selectedOtherSponsorships = document.querySelectorAll('input[name="otherSponsorshipType"]:checked');
        
        selectedOtherSponsorships.forEach(selectedOtherSponsorship => {
            if (selectedOtherSponsorship) {
                // Find the quantity input for this specific other sponsorship option
                const pricingOption = selectedOtherSponsorship.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const quantity = parseInt(quantityInput?.value) || 1;
                
                this.formData.otherSponsorships.push({
                    type: selectedOtherSponsorship.value,
                    count: quantity
                });
            }
        });
    }

    updateSummary() {
        // Update delegate summary
        const delegateSummary = document.getElementById('delegateSummary');
        let delegateTotal = 0;
        let delegateHtml = '';

        const selectedDelegates = document.querySelectorAll('input[name="delegateType"]:checked');
        
        selectedDelegates.forEach(selectedDelegate => {
            if (selectedDelegate && this.frontendConfig) {
                // Get individual quantity for this delegate option
                const pricingOption = selectedDelegate.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const delegateCount = parseInt(quantityInput?.value) || 1;
                
                const selectedDelegateCode = selectedDelegate.value;
                const delegateProducts = this.frontendConfig.delegatePasses?.products || [];
                const selectedDelegateProduct = delegateProducts.find(p => p.product_code === selectedDelegateCode);
                
                if (selectedDelegateProduct) {
                    // Find current active tier or use base price
                    const activeTier = selectedDelegateProduct.pricing_tiers?.find(tier => tier.is_current);
                    const delegatePrice = activeTier ? activeTier.price : selectedDelegateProduct.base_price;
                    const itemTotal = delegatePrice * delegateCount;
                    delegateTotal += itemTotal;
                    delegateHtml += `
                        <div class="summary-line">
                            <span>${selectedDelegateProduct.name} × ${delegateCount}</span>
                            <span class="price">USD $${itemTotal.toLocaleString()}</span>
                        </div>
                    `;
                }
            }
        });

        if (delegateTotal > 0 && delegateSummary) {
            delegateSummary.style.display = 'block';
            delegateSummary.innerHTML = delegateHtml;
        } else if (delegateSummary) {
            delegateSummary.style.display = 'none';
        }

        // Update table summary
        const tableSummary = document.getElementById('tableSummary');
        let tableTotal = 0;
        let tableHtml = '';

        const selectedTables = document.querySelectorAll('input[name="tableType"]:checked');
        
        selectedTables.forEach(selectedTable => {
            if (selectedTable && this.frontendConfig) {
                // Get individual quantity for this table option
                const pricingOption = selectedTable.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const tableCount = parseInt(quantityInput?.value) || 1;
                
                const selectedTableCode = selectedTable.value;
                const tableProducts = this.frontendConfig.tablePresentations?.products || [];
                const selectedTableProduct = tableProducts.find(p => p.product_code === selectedTableCode);
                
                if (selectedTableProduct) {
                    const itemTotal = selectedTableProduct.base_price * tableCount;
                    tableTotal += itemTotal;
                    tableHtml += `
                        <div class="summary-line">
                            <span>${selectedTableProduct.name} × ${tableCount}</span>
                            <span class="price">USD $${itemTotal.toLocaleString()}</span>
                        </div>
                    `;
                }
            }
        });

        if (tableTotal > 0 && tableSummary) {
            tableSummary.style.display = 'block';
            tableSummary.innerHTML = tableHtml;
        } else if (tableSummary) {
            tableSummary.style.display = 'none';
        }
        
        // Update sponsorship summary
        const sponsorshipSummary = document.getElementById('sponsorshipSummary');
        let sponsorshipTotal = 0;
        let sponsorshipHtml = '';

        const selectedSponsorships = document.querySelectorAll('input[name="sponsorshipType"]:checked');
        
        selectedSponsorships.forEach(selectedSponsorship => {
            if (selectedSponsorship && this.frontendConfig) {
                // Get individual quantity for this sponsorship option
                const pricingOption = selectedSponsorship.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const sponsorshipCount = parseInt(quantityInput?.value) || 1;
                
                const selectedSponsorshipCode = selectedSponsorship.value;
                const sponsorshipProducts = this.frontendConfig.sponsorship?.products || [];
                const selectedSponsorshipProduct = sponsorshipProducts.find(p => p.product_code === selectedSponsorshipCode);
                
                if (selectedSponsorshipProduct) {
                    const itemTotal = selectedSponsorshipProduct.base_price * sponsorshipCount;
                    sponsorshipTotal += itemTotal;
                    sponsorshipHtml += `
                        <div class="summary-line">
                            <span>${selectedSponsorshipProduct.name} × ${sponsorshipCount}</span>
                            <span class="price">USD $${itemTotal.toLocaleString()}</span>
                        </div>
                    `;
                }
            }
        });

        if (sponsorshipTotal > 0 && sponsorshipSummary) {
            sponsorshipSummary.style.display = 'block';
            sponsorshipSummary.innerHTML = sponsorshipHtml;
        } else if (sponsorshipSummary) {
            sponsorshipSummary.style.display = 'none';
        }
        
        // Update other sponsorship summary
        const otherSponsorshipSummary = document.getElementById('otherSponsorshipSummary');
        let otherSponsorshipTotal = 0;
        let otherSponsorshipHtml = '';

        const selectedOtherSponsorships = document.querySelectorAll('input[name="otherSponsorshipType"]:checked');
        
        selectedOtherSponsorships.forEach(selectedOtherSponsorship => {
            if (selectedOtherSponsorship && this.frontendConfig) {
                // Get individual quantity for this other sponsorship option
                const pricingOption = selectedOtherSponsorship.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const otherSponsorshipCount = parseInt(quantityInput?.value) || 1;
                
                const selectedOtherSponsorshipCode = selectedOtherSponsorship.value;
                const otherSponsorshipProducts = this.frontendConfig.otherSponsorship?.products || [];
                const selectedOtherSponsorshipProduct = otherSponsorshipProducts.find(p => p.product_code === selectedOtherSponsorshipCode);
                
                if (selectedOtherSponsorshipProduct) {
                    const itemTotal = selectedOtherSponsorshipProduct.base_price * otherSponsorshipCount;
                    otherSponsorshipTotal += itemTotal;
                    otherSponsorshipHtml += `
                        <div class="summary-line">
                            <span>${selectedOtherSponsorshipProduct.name} × ${otherSponsorshipCount}</span>
                            <span class="price">USD $${itemTotal.toLocaleString()}</span>
                        </div>
                    `;
                }
            }
        });

        if (otherSponsorshipTotal > 0 && otherSponsorshipSummary) {
            otherSponsorshipSummary.style.display = 'block';
            otherSponsorshipSummary.innerHTML = otherSponsorshipHtml;
        } else if (otherSponsorshipSummary) {
            otherSponsorshipSummary.style.display = 'none';
        }

        // Update total
        const total = delegateTotal + tableTotal + sponsorshipTotal + otherSponsorshipTotal;
        document.getElementById('totalPrice').textContent = `USD $${total.toLocaleString()}`;
    }

    generateDietaryOptions() {
        return this.config.dietaryOptions.map(option => {
            // Handle both string array format and object format
            if (typeof option === 'string') {
                // Convert string to lowercase for value, keep original for display
                const value = option === 'None' ? '' : option.toLowerCase().replace(/\s+/g, '-');
                return `<option value="${value}">${option}</option>`;
            } else {
                // Handle object format {value: "...", label: "..."}
                return `<option value="${option.value}">${option.label}</option>`;
            }
        }).join('');
    }

    populateCountries() {
        const countrySelect = document.getElementById('country');
        if (!countrySelect) return;

        // Comprehensive list of countries
        const countries = [
            'Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua and Barbuda',
            'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain',
            'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan',
            'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria',
            'Burkina Faso', 'Burundi', 'Cabo Verde', 'Cambodia', 'Cameroon', 'Canada',
            'Central African Republic', 'Chad', 'Chile', 'China', 'Colombia', 'Comoros',
            'Congo', 'Costa Rica', 'Croatia', 'Cuba', 'Cyprus', 'Czech Republic',
            'Democratic Republic of the Congo', 'Denmark', 'Djibouti', 'Dominica',
            'Dominican Republic', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea',
            'Eritrea', 'Estonia', 'Eswatini', 'Ethiopia', 'Fiji', 'Finland', 'France',
            'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada',
            'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Honduras',
            'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland',
            'Israel', 'Italy', 'Ivory Coast', 'Jamaica', 'Japan', 'Jordan', 'Kazakhstan',
            'Kenya', 'Kiribati', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon',
            'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg',
            'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta',
            'Marshall Islands', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia',
            'Moldova', 'Monaco', 'Mongolia', 'Montenegro', 'Morocco', 'Mozambique',
            'Myanmar', 'Namibia', 'Nauru', 'Nepal', 'Netherlands', 'New Zealand',
            'Nicaragua', 'Niger', 'Nigeria', 'North Korea', 'North Macedonia', 'Norway',
            'Oman', 'Pakistan', 'Palau', 'Palestine', 'Panama', 'Papua New Guinea',
            'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Qatar', 'Romania',
            'Russia', 'Rwanda', 'Saint Kitts and Nevis', 'Saint Lucia',
            'Saint Vincent and the Grenadines', 'Samoa', 'San Marino',
            'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia', 'Seychelles',
            'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands',
            'Somalia', 'South Africa', 'South Korea', 'South Sudan', 'Spain', 'Sri Lanka',
            'Sudan', 'Suriname', 'Sweden', 'Switzerland', 'Syria', 'Taiwan', 'Tajikistan',
            'Tanzania', 'Thailand', 'Timor-Leste', 'Togo', 'Tonga', 'Trinidad and Tobago',
            'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu', 'Uganda', 'Ukraine',
            'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay',
            'Uzbekistan', 'Vanuatu', 'Vatican City', 'Venezuela', 'Vietnam', 'Yemen',
            'Zambia', 'Zimbabwe'
        ];

        // Add countries to select dropdown
        countries.forEach(country => {
            const option = document.createElement('option');
            option.value = country;
            option.textContent = country;
            countrySelect.appendChild(option);
        });
    }

    generateDelegateDetails() {
        const container = document.getElementById('delegateDetailsContainer');
        container.innerHTML = '';

        // Check if delegateProducts exists and is an array
        if (!this.formData.delegateProducts || !Array.isArray(this.formData.delegateProducts)) {
            return; // Exit early if no delegate products are selected
        }

        // Generate delegate cards based on total count from all selected delegate products
        let delegateNumber = 1;
        this.formData.delegateProducts.forEach(delegateSelection => {
            for (let i = 0; i < delegateSelection.count; i++) {
                const delegateCard = this.createDelegateCard(delegateNumber, delegateSelection.type);
                container.appendChild(delegateCard);
                delegateNumber++;
            }
        });
    }

    createDelegateCard(delegateNumber, delegateType = '') {
        const card = document.createElement('div');
        card.className = 'card delegate-card';
        
        // Get product name for display
        let productName = '';
        if (delegateType && this.frontendConfig) {
            const delegateProducts = this.frontendConfig.delegatePasses?.products || [];
            const product = delegateProducts.find(p => p.product_code === delegateType);
            if (product) {
                productName = ` (${product.name})`;
            }
        }
        
        card.innerHTML = `
            <div class="delegate-card-header">
                <h3 class="text-lg" id="delegate${delegateNumber}Header">Delegate ${delegateNumber}${productName}</h3>
            </div>
            <div class="form-grid">
                <div class="form-group">
                    <label for="delegate${delegateNumber}FullName" class="form-label">Full Name *</label>
                    <input type="text" id="delegate${delegateNumber}FullName" name="delegate${delegateNumber}FullName" class="form-input" required>
                </div>
                <div class="form-group">
                    <label for="delegate${delegateNumber}BadgeName" class="form-label">Preferred Short Name on Badge *</label>
                    <input type="text" id="delegate${delegateNumber}BadgeName" name="delegate${delegateNumber}BadgeName" class="form-input" required>
                </div>
                <div class="form-group">
                    <label for="delegate${delegateNumber}Designation" class="form-label">Designation *</label>
                    <input type="text" id="delegate${delegateNumber}Designation" name="delegate${delegateNumber}Designation" class="form-input" placeholder="e.g., Professor, Student, Manager" required>
                </div>
                <div class="form-group">
                    <label for="delegate${delegateNumber}Email" class="form-label">Email Address</label>
                    <input type="email" id="delegate${delegateNumber}Email" name="delegate${delegateNumber}Email" class="form-input" placeholder="delegate@university.edu">
                    <span class="form-help" style="font-size: 12px; color: #64748b; margin-top: 4px; display: block;">Optional - for pass collection notifications</span>
                </div>
                <div class="form-group">
                    <label for="delegate${delegateNumber}Dietary" class="form-label">Dietary Requirements</label>
                    <select id="delegate${delegateNumber}Dietary" name="delegate${delegateNumber}Dietary" class="form-input">
                        ${this.generateDietaryOptions()}
                    </select>
                </div>
                <div class="form-group">
                    <label for="delegate${delegateNumber}Assistance" class="form-label">Special Assistance</label>
                    <input type="text" id="delegate${delegateNumber}Assistance" name="delegate${delegateNumber}Assistance" class="form-input" placeholder="Describe any special requirements...">
                </div>
            </div>
        `;
        
        // Add event listener to update header when full name changes
        const fullNameInput = card.querySelector(`#delegate${delegateNumber}FullName`);
        const headerElement = card.querySelector(`#delegate${delegateNumber}Header`);
        
        fullNameInput.addEventListener('input', function() {
            const fullName = this.value.trim();
            if (fullName) {
                headerElement.textContent = `Delegate ${delegateNumber}${productName} - ${fullName}`;
            } else {
                headerElement.textContent = `Delegate ${delegateNumber}${productName}`;
            }
        });
        
        return card;
    }

    nextStep() {
        if (this.validateCurrentStep()) {
            if (this.currentStep < this.totalSteps) {
                this.saveCurrentStepData();
                this.currentStep++;
                this.showStep(this.currentStep);
                
                // Auto-save form data to localStorage for page refresh protection
                this.saveFormDataToStorage();
                
                if (this.currentStep === 4) {
                    this.populateReview();
                } else if (this.currentStep === 5) {
                    this.populatePaymentSummary();
                }
            }
        }
    }

    prevStep() {
        if (this.currentStep > 1) {
            // Save current step data before going back
            this.saveCurrentStepData();
            
            this.currentStep--;
            this.showStep(this.currentStep);
            
            // Auto-save form data to localStorage for page refresh protection
            this.saveFormDataToStorage();
        }
    }

    showStep(stepNumber) {
        // Hide all steps
        document.querySelectorAll('.form-step').forEach(step => {
            step.classList.remove('active');
        });

        // Show current step
        document.getElementById(`step${stepNumber}`).classList.add('active');

        // Update progress indicator
        document.querySelectorAll('.progress-step').forEach((step, index) => {
            step.classList.remove('active', 'completed');
            if (index + 1 === stepNumber) {
                step.classList.add('active');
            } else if (index + 1 < stepNumber) {
                step.classList.add('completed');
            }
        });

        // Scroll to top
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    validateCurrentStep() {
        const currentStepElement = document.getElementById(`step${this.currentStep}`);
        const requiredInputs = currentStepElement.querySelectorAll('input[required], select[required]');
        let isValid = true;

        requiredInputs.forEach(input => {
            input.classList.remove('error');
            const errorMsg = input.parentNode.querySelector('.error-message');
            if (errorMsg) errorMsg.remove();

            if (!input.value.trim()) {
                input.classList.add('error');
                const error = document.createElement('div');
                error.className = 'error-message';
                error.textContent = 'This field is required';
                input.parentNode.appendChild(error);
                isValid = false;
            }
        });

        // Additional validation for step 1
        if (this.currentStep === 1) {
            // Check if at least one delegate is selected
            const selectedDelegates = document.querySelectorAll('input[name="delegateType"]:checked');
            if (selectedDelegates.length === 0) {
                isValid = false;
                alert('Please select at least one delegate pass');
            }
        }

        // Additional validation for step 3 (Contact Information)
        if (this.currentStep === 3) {
            // Validate email format
            const emailInput = document.getElementById('email');
            if (emailInput && emailInput.value) {
                if (!this.validateEmail(emailInput.value)) {
                    emailInput.classList.add('error');
                    let errorMsg = emailInput.parentNode.querySelector('.error-message');
                    if (!errorMsg) {
                        errorMsg = document.createElement('div');
                        errorMsg.className = 'error-message';
                        emailInput.parentNode.appendChild(errorMsg);
                    }
                    errorMsg.textContent = 'Please enter a valid email address';
                    isValid = false;
                }
            }

            // Validate phone number format
            const mobileInput = document.getElementById('mobile');
            if (mobileInput && mobileInput.value) {
                if (!this.validatePhone(mobileInput.value)) {
                    mobileInput.classList.add('error');
                    let errorMsg = mobileInput.parentNode.querySelector('.error-message');
                    if (!errorMsg) {
                        errorMsg = document.createElement('div');
                        errorMsg.className = 'error-message';
                        mobileInput.parentNode.appendChild(errorMsg);
                    }
                    errorMsg.textContent = 'Please enter a valid international phone number (e.g., +60123456789)';
                    isValid = false;
                }
            }
        }

        return isValid;
    }

    saveCurrentStepData() {
        if (this.currentStep === 1) {
            this.updateDelegateSelections();
            this.updateTableSelections();
            this.updateSponsorshipSelections();
            this.updateOtherSponsorshipSelections();
            this.generateDelegateDetails(); // Regenerate delegate details when selections change
            
            // Restore previously saved delegate data into the regenerated forms
            if (this.formData.delegates && this.formData.delegates.length > 0) {
                this.formData.delegates.forEach((delegate, index) => {
                    const delegateNumber = index + 1;
                    const fieldMap = {
                        fullName: 'FullName',
                        badgeName: 'BadgeName',
                        designation: 'Designation',
                        email: 'Email',
                        dietary: 'Dietary',
                        assistance: 'Assistance'
                    };
                    
                    Object.keys(fieldMap).forEach(field => {
                        const elementId = `delegate${delegateNumber}${fieldMap[field]}`;
                        const input = document.getElementById(elementId);
                        
                        // Check if the field exists in delegate object (not just if it's truthy)
                        // This allows empty strings, 0, false, etc. to be restored
                        if (input && field in delegate) {
                            const value = delegate[field];
                            input.value = value !== null && value !== undefined ? value : '';
                        }
                    });
                });
            }
        } else if (this.currentStep === 2) {
            this.formData.delegates = [];
            for (let i = 1; i <= this.formData.delegateCount; i++) {
                const delegate = {
                    fullName: document.getElementById(`delegate${i}FullName`).value,
                    badgeName: document.getElementById(`delegate${i}BadgeName`).value,
                    designation: document.getElementById(`delegate${i}Designation`).value,
                    email: document.getElementById(`delegate${i}Email`).value,
                    dietary: document.getElementById(`delegate${i}Dietary`).value,
                    assistance: document.getElementById(`delegate${i}Assistance`).value
                };
                this.formData.delegates.push(delegate);
            }
        } else if (this.currentStep === 3) {
            this.formData.contact = {
                salutation: document.getElementById('salutation').value,
                fullName: document.getElementById('contactFullName').value,
                designation: document.getElementById('contactDesignation').value,
                department: document.getElementById('department').value,
                email: document.getElementById('email').value,
                mobile: document.getElementById('mobile').value,
                university: document.getElementById('university').value,
                country: document.getElementById('country').value
            };
            
            // Also map to the expected API field names
            this.formData.contactFullName = document.getElementById('contactFullName').value;
            this.formData.contactDesignation = document.getElementById('contactDesignation').value;
            this.formData.contactDepartment = document.getElementById('department').value;
            this.formData.contactEmail = document.getElementById('email').value;
            this.formData.contactMobile = document.getElementById('mobile').value;
            this.formData.universityName = document.getElementById('university').value;
        }
    }

    populateReview() {
        // Pass Selection Review
        const passReview = document.getElementById('passReview');
        
        // Get delegate price from selected product (same logic as updateSummary)
        const selectedDelegateInput = document.querySelector('input[name="delegateType"]:checked');
        let delegatePrice = 0;
        let productName = 'Delegate Pass';
        
        if (selectedDelegateInput && this.frontendConfig) {
            const selectedProductCode = selectedDelegateInput.value;
            const delegateProducts = this.frontendConfig.delegatePasses?.products || [];
            const selectedProduct = delegateProducts.find(p => p.product_code === selectedProductCode);
            
            if (selectedProduct) {
                // Find current active tier or use base price
                const activeTier = selectedProduct.pricing_tiers?.find(tier => tier.is_current);
                delegatePrice = activeTier ? activeTier.price : selectedProduct.base_price;
                productName = selectedProduct.name;
            }
        }
        
        const delegateTotal = delegatePrice * this.formData.delegateCount;
        
        let passHtml = `
            <div class="review-item">
                <span>Delegate Passes (${productName}) × ${this.formData.delegateCount}</span>
                <span class="price">USD $${delegateTotal.toLocaleString()}</span>
            </div>
        `;

        // Get table pricing from selected products (same logic as updateSummary)
        let tableTotal = 0;
        const selectedTables = document.querySelectorAll('input[name="tableType"]:checked');
        
        selectedTables.forEach(selectedTable => {
            if (selectedTable && this.frontendConfig) {
                // Get individual quantity for this table option
                const pricingOption = selectedTable.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const tableCount = parseInt(quantityInput?.value) || 1;
                
                const selectedTableCode = selectedTable.value;
                const tableProducts = this.frontendConfig.tablePresentations?.products || [];
                const selectedTableProduct = tableProducts.find(p => p.product_code === selectedTableCode);
                
                if (selectedTableProduct) {
                    const itemTotal = selectedTableProduct.base_price * tableCount;
                    tableTotal += itemTotal;
                    passHtml += `
                        <div class="review-item">
                            <span>${selectedTableProduct.name} × ${tableCount}</span>
                            <span class="price">USD $${itemTotal.toLocaleString()}</span>
                        </div>
                    `;
                }
            }
        });
        
        // Get sponsorship pricing from selected products
        let sponsorshipTotal = 0;
        const selectedSponsorships = document.querySelectorAll('input[name="sponsorshipType"]:checked');
        
        selectedSponsorships.forEach(selectedSponsorship => {
            if (selectedSponsorship && this.frontendConfig) {
                // Get individual quantity for this sponsorship option
                const pricingOption = selectedSponsorship.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const sponsorshipCount = parseInt(quantityInput?.value) || 1;
                
                const selectedSponsorshipCode = selectedSponsorship.value;
                const sponsorshipProducts = this.frontendConfig.sponsorship?.products || [];
                const selectedSponsorshipProduct = sponsorshipProducts.find(p => p.product_code === selectedSponsorshipCode);
                
                if (selectedSponsorshipProduct) {
                    const itemTotal = selectedSponsorshipProduct.base_price * sponsorshipCount;
                    sponsorshipTotal += itemTotal;
                    passHtml += `
                        <div class="review-item">
                            <span>${selectedSponsorshipProduct.name} × ${sponsorshipCount}</span>
                            <span class="price">USD $${itemTotal.toLocaleString()}</span>
                        </div>
                    `;
                }
            }
        });
        
        // Get other sponsorship pricing from selected products
        let otherSponsorshipTotal = 0;
        const selectedOtherSponsorships = document.querySelectorAll('input[name="otherSponsorshipType"]:checked');
        
        selectedOtherSponsorships.forEach(selectedOtherSponsorship => {
            if (selectedOtherSponsorship && this.frontendConfig) {
                // Get individual quantity for this other sponsorship option
                const pricingOption = selectedOtherSponsorship.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const otherSponsorshipCount = parseInt(quantityInput?.value) || 1;
                
                const selectedOtherSponsorshipCode = selectedOtherSponsorship.value;
                const otherSponsorshipProducts = this.frontendConfig.otherSponsorship?.products || [];
                const selectedOtherSponsorshipProduct = otherSponsorshipProducts.find(p => p.product_code === selectedOtherSponsorshipCode);
                
                if (selectedOtherSponsorshipProduct) {
                    const itemTotal = selectedOtherSponsorshipProduct.base_price * otherSponsorshipCount;
                    otherSponsorshipTotal += itemTotal;
                    passHtml += `
                        <div class="review-item">
                            <span>${selectedOtherSponsorshipProduct.name} × ${otherSponsorshipCount}</span>
                            <span class="price">USD $${itemTotal.toLocaleString()}</span>
                        </div>
                    `;
                }
            }
        });

        passReview.innerHTML = passHtml;

        // Delegates Review
        const delegatesReview = document.getElementById('delegatesReview');
        let delegatesHtml = '';
        this.formData.delegates.forEach((delegate, index) => {
            delegatesHtml += `
                <div class="review-item" style="flex-direction: column; align-items: flex-start; padding: 12px 0;">
                    <div style="display: flex; justify-content: space-between; width: 100%; margin-bottom: 8px;">
                        <strong>Delegate ${index + 1}: ${delegate.fullName}</strong>
                        <span class="muted">${delegate.designation}</span>
                    </div>
                    <div style="font-size: 14px; color: var(--slate-600);">
                        Badge: ${delegate.badgeName}
                        ${delegate.email ? ` • Email: ${delegate.email}` : ''}
                        ${delegate.dietary ? ` • Dietary: ${delegate.dietary}` : ''}
                        ${delegate.assistance ? ` • Special Assistance Required` : ''}
                    </div>
                </div>
            `;
        });
        delegatesReview.innerHTML = delegatesHtml;

        // Contact Review
        const contactReview = document.getElementById('contactReview');
        const contact = this.formData.contact;
        contactReview.innerHTML = `
            <div class="review-item">
                <span>Primary Contact</span>
                <span>${contact.salutation} ${contact.fullName}</span>
            </div>
            <div class="review-item">
                <span>Email</span>
                <span>${contact.email}</span>
            </div>
            <div class="review-item">
                <span>Mobile</span>
                <span>${contact.mobile}</span>
            </div>
            <div class="review-item">
                <span>University</span>
                <span>${contact.university}</span>
            </div>
            <div class="review-item">
                <span>Department</span>
                <span>${contact.department}</span>
            </div>
            <div class="review-item">
                <span>Country</span>
                <span>${contact.country}</span>
            </div>
        `;

        // Update final total
        const finalTotal = delegateTotal + tableTotal + sponsorshipTotal + otherSponsorshipTotal;
        document.getElementById('finalTotal').textContent = `USD $${finalTotal.toLocaleString()}`;
    }

    populatePaymentSummary() {
        // Get delegate prices from ALL selected products (handles both checkboxes and radio buttons)
        // This is critical for special access links where multiple delegate types can be selected
        let delegateTotal = 0;
        const selectedDelegates = document.querySelectorAll('input[name="delegateType"]:checked');
        
        selectedDelegates.forEach(selectedDelegate => {
            if (selectedDelegate && this.frontendConfig) {
                // Get individual quantity for this delegate option
                const pricingOption = selectedDelegate.closest('.pricing-option');
                const quantityInput = pricingOption?.querySelector('.delegate-qty-input');
                const delegateCount = parseInt(quantityInput?.value) || 1;
                
                const selectedProductCode = selectedDelegate.value;
                const delegateProducts = this.frontendConfig.delegatePasses?.products || [];
                const selectedProduct = delegateProducts.find(p => p.product_code === selectedProductCode);
                
                if (selectedProduct) {
                    // Find current active tier or use base price
                    const activeTier = selectedProduct.pricing_tiers?.find(tier => tier.is_current);
                    const delegatePrice = activeTier ? activeTier.price : selectedProduct.base_price;
                    delegateTotal += delegatePrice * delegateCount;
                }
            }
        });
        
        // Get table pricing from selected products
        let tableTotal = 0;
        const selectedTables = document.querySelectorAll('input[name="tableType"]:checked');
        
        selectedTables.forEach(selectedTable => {
            if (selectedTable && this.frontendConfig) {
                const pricingOption = selectedTable.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const tableCount = parseInt(quantityInput?.value) || 1;
                
                const selectedTableCode = selectedTable.value;
                const tableProducts = this.frontendConfig.tablePresentations?.products || [];
                const selectedTableProduct = tableProducts.find(p => p.product_code === selectedTableCode);
                
                if (selectedTableProduct) {
                    tableTotal += selectedTableProduct.base_price * tableCount;
                }
            }
        });
        
        // Get sponsorship pricing from selected products
        let sponsorshipTotal = 0;
        const selectedSponsorships = document.querySelectorAll('input[name="sponsorshipType"]:checked');
        
        selectedSponsorships.forEach(selectedSponsorship => {
            if (selectedSponsorship && this.frontendConfig) {
                const pricingOption = selectedSponsorship.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const sponsorshipCount = parseInt(quantityInput?.value) || 1;
                
                const selectedSponsorshipCode = selectedSponsorship.value;
                const sponsorshipProducts = this.frontendConfig.sponsorship?.products || [];
                const selectedSponsorshipProduct = sponsorshipProducts.find(p => p.product_code === selectedSponsorshipCode);
                
                if (selectedSponsorshipProduct) {
                    sponsorshipTotal += selectedSponsorshipProduct.base_price * sponsorshipCount;
                }
            }
        });
        
        // Get other sponsorship pricing from selected products
        let otherSponsorshipTotal = 0;
        const selectedOtherSponsorships = document.querySelectorAll('input[name="otherSponsorshipType"]:checked');
        
        selectedOtherSponsorships.forEach(selectedOtherSponsorship => {
            if (selectedOtherSponsorship && this.frontendConfig) {
                const pricingOption = selectedOtherSponsorship.closest('.pricing-option');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                const otherSponsorshipCount = parseInt(quantityInput?.value) || 1;
                
                const selectedOtherSponsorshipCode = selectedOtherSponsorship.value;
                const otherSponsorshipProducts = this.frontendConfig.otherSponsorship?.products || [];
                const selectedOtherSponsorshipProduct = otherSponsorshipProducts.find(p => p.product_code === selectedOtherSponsorshipCode);
                
                if (selectedOtherSponsorshipProduct) {
                    otherSponsorshipTotal += selectedOtherSponsorshipProduct.base_price * otherSponsorshipCount;
                }
            }
        });
        
        const total = delegateTotal + tableTotal + sponsorshipTotal + otherSponsorshipTotal;
        const paymentTotalEl = document.getElementById('paymentTotal');
        if (paymentTotalEl) paymentTotalEl.textContent = `USD $${total.toLocaleString()}`;

        // Hide payment options when total is zero
        const paymentOptionsSection = document.getElementById('paymentOptionsSection') || document.querySelector('.payment-methods');
        const step5Header = document.querySelector('#step5 .form-step-header h2');
        const step5Sub = document.querySelector('#step5 .form-step-header p');
        const completeBtn = document.querySelector('button[type="submit"]');
        if (paymentOptionsSection) {
            if (total <= 0) {
                paymentOptionsSection.style.display = 'none';
                // Deselect any previously selected payment method
                const checked = document.querySelector('input[name="paymentMethod"]:checked');
                if (checked) checked.checked = false;
                if (completeBtn) completeBtn.textContent = 'Complete Registration';
                if (step5Header) step5Header.textContent = 'No Payment Required';
                if (step5Sub) step5Sub.textContent = 'This registration is complimentary. Click Complete Registration to finish.';
            } else {
                paymentOptionsSection.style.display = '';
                if (completeBtn) completeBtn.textContent = 'Proceed to Payment';
                if (step5Header) step5Header.textContent = 'Payment Options';
                if (step5Sub) step5Sub.textContent = 'Choose your preferred payment method';
            }
        }
    }

    updatePaymentSummaryFromData() {
        // Get the total amount from retry data for payment retry scenarios
        const retryData = this.getPaymentRetryData();
        if (retryData && retryData.totalAmount) {
            const paymentTotalElement = document.getElementById('paymentTotal');
            if (paymentTotalElement) {
                paymentTotalElement.textContent = `USD $${parseFloat(retryData.totalAmount).toLocaleString()}`;
            }
            // Also hide/show payment options based on total in retry state
            const total = parseFloat(retryData.totalAmount) || 0;
            const paymentOptionsSection = document.getElementById('paymentOptionsSection') || document.querySelector('.payment-methods');
            const step5Header = document.querySelector('#step5 .form-step-header h2');
            const step5Sub = document.querySelector('#step5 .form-step-header p');
            const completeBtn = document.querySelector('button[type="submit"]');
            if (paymentOptionsSection) {
                if (total <= 0) {
                    paymentOptionsSection.style.display = 'none';
                    const checked = document.querySelector('input[name="paymentMethod"]:checked');
                    if (checked) checked.checked = false;
                    if (completeBtn) completeBtn.textContent = 'Complete Registration';
                    if (step5Header) step5Header.textContent = 'No Payment Required';
                    if (step5Sub) step5Sub.textContent = 'This registration is complimentary. Click Complete Registration to finish.';
                } else {
                    paymentOptionsSection.style.display = '';
                    if (completeBtn) completeBtn.textContent = 'Proceed to Payment';
                    if (step5Header) step5Header.textContent = 'Payment Options';
                    if (step5Sub) step5Sub.textContent = 'Choose your preferred payment method';
                }
            }
        }
    }

    async submitForm() {
        const submitBtn = document.querySelector('button[type="submit"]');
        submitBtn.classList.add('loading');
        submitBtn.textContent = 'Processing...';

        try {
            // Save all form data including payment method
            this.saveCurrentStepData();
            
            // Get selected payment method if any (allow zero-amount auto-complete)
            const checkedMethod = document.querySelector('input[name="paymentMethod"]:checked');
            const paymentMethod = checkedMethod ? checkedMethod.value : null;
            this.formData.paymentMethod = paymentMethod;
            
            // Keep tables data in original format for registration API
            // The registration API expects array of objects with type and count
            
            // Save form data to localStorage before payment processing
            this.saveFormDataToStorage();
            
            // Submit to API - include both delegate products and individual delegate details
            const submissionData = {
                ...this.formData,
                delegateProducts: this.formData.delegateProducts || [],
                delegates: this.formData.delegates || [] // Individual delegate details from step 2
            };
            
            const response = await fetch('api.php?action=register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(submissionData)
            });
            
            // Get response text first for debugging
            const responseText = await response.text();
            
            // Check for non-JSON response (PHP errors)
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                console.error('Non-JSON response from server:', responseText);
                throw new Error('Server returned an invalid response: ' + responseText.substring(0, 200));
            }
            
            // Try to parse JSON
            let result;
            try {
                result = JSON.parse(responseText);
            } catch (parseError) {
                console.error('JSON parse error:', parseError);
                console.error('Response text that failed to parse:', responseText);
                throw new Error('Invalid JSON response from server: ' + responseText.substring(0, 200));
            }
            
            if (!response.ok || result.error) {
                throw new Error(result.error || 'Registration failed');
            }
            
            // Store registration details
            const registrationData = {
                registrationNumber: result.registrationNumber,
                paymentReference: result.paymentReference,
                totalAmount: result.totalAmount,
                paymentDeadline: result.paymentDeadline
            };
            
            if (result.isFree === true || Number(registrationData.totalAmount) <= 0) {
                // Free registration: show success and return immediately
                this.clearSavedFormData();
                const successDiv = document.getElementById('successMessage');
                const successContent = successDiv.querySelector('.success-content');
                successContent.innerHTML = `
                    <div class="success-icon">✓</div>
                    <h2 class="text-2xl fw-800">Registration Completed</h2>
                    <p class="mt-3">Thank you for registering. No payment was required for this special access package.</p>
                    <div class="registration-details mt-4">
                        <div class="detail-card">
                            <h3>Registration Details</h3>
                            <p><strong>Registration Number:</strong> ${registrationData.registrationNumber}</p>
                            <p><strong>Total Amount:</strong> USD $0</p>
                        </div>
                    </div>
                    <div class="mt-4">
                        <button type="button" class="btn btn-primary" onclick="returnToEventPage()">Return to Event Page</button>
                    </div>
                `;
                successDiv.style.display = 'flex';
                return; // Exit function after showing free registration success
            }

            // Handle paid registrations
            if (paymentMethod === 'gateway') {
                // Save registration data for payment retry
                this.saveRegistrationDataForRetry(registrationData);
                
                // Process Stripe payment - this will redirect to Stripe checkout
                await this.processStripePayment(registrationData, result);
                // Note: If redirect succeeds, code below won't execute
                // If redirect fails, error will be thrown and caught
                return; // Explicit return after payment processing
                
            } else if (paymentMethod === 'tt') {
                // Clear saved data on successful bank transfer selection
                this.clearSavedFormData();
                
                // Show bank transfer instructions with real data
                this.showBankTransferInstructions(registrationData);
                return; // Exit function after showing bank transfer instructions
            }
            
            
        } catch (error) {
            alert('There was an error submitting your registration. Please try again.\n\nError: ' + error.message);
            console.error('Submission error:', error);
        } finally {
            submitBtn.classList.remove('loading');
            submitBtn.textContent = 'Complete Registration';
        }
    }

    showBankTransferInstructions(registrationData) {
        // Show success message with bank transfer details
        const successDiv = document.getElementById('successMessage');
        const successContent = successDiv.querySelector('.success-content');
        
        successContent.innerHTML = `
            <div class="success-icon">✓</div>
            <h2 class="text-2xl fw-800">Registration Submitted!</h2>
            <p class="mt-3">Thank you for registering for AppliedHE Xchange 2025.</p>
            
            <div class="registration-details mt-4">
                <div class="detail-card">
                    <h3>Registration Details</h3>
                    <p><strong>Registration Number:</strong> ${registrationData.registrationNumber}</p>
                    <p><strong>Payment Reference:</strong> ${registrationData.paymentReference}</p>
                    <p><strong>Total Amount:</strong> USD $${registrationData.totalAmount}</p>
                    <p><strong>Payment Deadline:</strong> ${new Date(registrationData.paymentDeadline).toLocaleDateString()}</p>
                </div>
                
                <div class="detail-card mt-4">
                    <h3>Bank Transfer Instructions</h3>
                    <p><strong>Bank Name:</strong> ${this.config.payment.bankName}</p>
                    <p><strong>Account Name:</strong> ${this.config.payment.accountName}</p>
                    <p><strong>Account Number:</strong> ${this.config.payment.accountNumber}</p>
                    <p><strong>SWIFT Code:</strong> ${this.config.payment.swiftCode}</p>
                    <p class="mt-3 text-sm"><strong>Important:</strong> Please include your payment reference <strong>${registrationData.paymentReference}</strong> in the transfer description.</p>
                </div>
            </div>
            
            <div class="mt-4">
                <button type="button" class="btn btn-primary" onclick="returnToEventPage()">Return to Event Page</button>
            </div>
        `;
        
        successDiv.style.display = 'flex';
        
        // Clear all saved data since registration is complete
        this.clearSavedFormData();
    }

    generateReferenceNumber() {
        const timestamp = Date.now().toString().slice(-6);
        const random = Math.random().toString(36).substring(2, 5).toUpperCase();
        return `${this.config.payment.referencePrefix}-${timestamp}${random}`;
    }

    async processStripePayment(registrationData, apiResult) {
        try {
            if (!this.stripe) {
                throw new Error('Stripe not initialized. Please check configuration.');
            }

            // Show processing message
            document.getElementById('gatewayMessage').style.display = 'flex';
            
            // Create payload for Stripe session
            const payload = {
                registrationNumber: registrationData.registrationNumber,
                totalAmount: registrationData.totalAmount,
                delegates: Array.isArray(this.formData.delegateProducts) ? this.formData.delegateProducts : [],
                contactEmail: this.formData.contact.email,
                university: this.formData.contact.university,
                sponsorships: Array.isArray(this.formData.sponsorships) ? this.formData.sponsorships : [],
                otherSponsorships: Array.isArray(this.formData.otherSponsorships) ? this.formData.otherSponsorships : [],
                accessCode: this.accessCode || null // Include access code for special access links
            };

            
            // Keep all product data in grouped format for consistency
            payload.tables = Array.isArray(this.formData.tables) ? this.formData.tables : [];
            
            // Debug: Log complete Stripe payload
            
            // Create Stripe checkout session using the registration data
            const response = await fetch('api.php?action=create_stripe_session', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload)
            });
            
            // Check for non-JSON response (PHP errors)
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                const errorText = await response.text();
                console.error('Non-JSON response from Stripe session creation:', errorText);
                throw new Error('Server returned an invalid response when creating payment session.');
            }
            
            const result = await response.json();
            
            // Debug: Log Stripe response
            if (result.error) {
                console.error('Stripe error:', result.error);
            }
            
            if (!result.success) {
                throw new Error(result.error || 'Failed to create payment session');
            }
            
            // Redirect to Stripe Checkout
            const { error } = await this.stripe.redirectToCheckout({
                sessionId: result.session_id
            });
            
            if (error) {
                throw new Error(error.message);
            }
            
        } catch (error) {
            document.getElementById('gatewayMessage').style.display = 'none';
            throw error;
        }
    }

    showBankTransferInstructions(registrationData) {
        // Populate bank details from config and registration data
        document.getElementById('bankName').textContent = this.config.payment.bankName;
        document.getElementById('accountName').textContent = this.config.payment.accountName;
        document.getElementById('accountNumber').textContent = this.config.payment.accountNumber;
        document.getElementById('swiftCode').textContent = this.config.payment.swiftCode;
        document.getElementById('transferReference').textContent = registrationData.paymentReference;
        document.getElementById('transferAmount').textContent = `USD $${registrationData.totalAmount.toLocaleString()}`;
        
        // Show the bank transfer message
        document.getElementById('bankTransferMessage').style.display = 'flex';
    }

    showSpecialAccessIndicator() {
        // Show a badge or indicator that the user is accessing via special link
        const heroSection = document.querySelector('.hero-section');
        if (heroSection) {
            // Get custom message from config
            const customMessage = this.config?.frontend?.specialAccess?.customMessage || 
                                'You have exclusive access to additional registration options';
            
            const indicator = document.createElement('div');
            indicator.className = 'special-access-indicator';
            indicator.innerHTML = `
                <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                            color: white; 
                            padding: 12px 24px; 
                            border-radius: 8px; 
                            text-align: center; 
                            margin: 16px auto; 
                            max-width: 600px;
                            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                            font-size: 14px;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            gap: 8px;">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                    </svg>
                    <strong>Special Access:</strong> ${this.escapeHtml(customMessage)}
                </div>
            `;
            heroSection.appendChild(indicator);
        }
    }
    
    // Helper to escape HTML
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// Utility functions
function adjustQuantity(inputId, change) {
    const input = document.getElementById(inputId);
    const currentValue = parseInt(input.value) || (inputId === 'tableCount' ? 0 : 1);
    
    let minValue, maxValue;
    if (inputId === 'tableCount') {
        minValue = 0;
        maxValue = 10;
    } else {
        minValue = 1;
        maxValue = 50;
    }
    
    const newValue = Math.max(minValue, Math.min(maxValue, currentValue + change));
    input.value = newValue;
    input.dispatchEvent(new Event('input'));
}

function nextStep() {
    registrationForm.nextStep();
}

function prevStep() {
    registrationForm.prevStep();
}

// Initialize the form when DOM is loaded
let registrationForm;
document.addEventListener('DOMContentLoaded', () => {
    registrationForm = new RegistrationForm();
}, true);

// Fallback validation functions for compatibility
function validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

function validatePhone(phone) {
    // Remove all non-digit characters except + at the start
    const cleanPhone = phone.replace(/[^\d+]/g, '');
    
    // International phone number validation
    // Must start with + or digit, be 7-15 digits total
    const phoneRegex = /^\+?[1-9]\d{6,14}$/;
    
    return phoneRegex.test(cleanPhone);
}

// Auto-populate badge name functionality removed per user request

// Data persistence methods for payment retry functionality
RegistrationForm.prototype.saveFormDataToStorage = function() {
    try {
        const dataToSave = {
            formData: this.formData,
            currentStep: this.currentStep,
            timestamp: Date.now(),
            version: '1.0'
        };
        localStorage.setItem('xchange_registration_data', JSON.stringify(dataToSave));
    } catch (error) {
        console.error('Failed to save form data to localStorage:', error);
    }
};

RegistrationForm.prototype.saveRegistrationDataForRetry = function(registrationData) {
    try {
        const retryData = {
            ...registrationData,
            formData: this.formData,
            timestamp: Date.now()
        };
        localStorage.setItem('xchange_payment_retry', JSON.stringify(retryData));
    } catch (error) {
        console.error('Failed to save registration data for retry:', error);
    }
};

RegistrationForm.prototype.loadSavedFormData = function() {
    try {
        const savedData = localStorage.getItem('xchange_registration_data');
        if (savedData) {
            const parsedData = JSON.parse(savedData);
            
            // No expiration check - data persists until successful submission
            this.formData = parsedData.formData;
            this.currentStep = parsedData.currentStep;
            this.restoreFormFields();
            
            // Show the correct step in the UI
            this.showStep(this.currentStep);
            
            return true;
        }
    } catch (error) {
        console.error('Failed to load saved form data:', error);
        this.clearSavedFormData();
    }
    return false;
};

RegistrationForm.prototype.restoreFormFields = function() {
    // Restore Step 1 data - delegate selections with quantities
    if (this.formData.delegateProducts && Array.isArray(this.formData.delegateProducts)) {
        // Restore each delegate product selection and quantity
        this.formData.delegateProducts.forEach(delegateProduct => {
            const checkbox = document.querySelector(`input[name="delegateType"][value="${delegateProduct.type}"]`);
            if (checkbox) {
                checkbox.checked = true;
                
                // Find and set the quantity input for this delegate
                const pricingOption = checkbox.closest('.pricing-option');
                if (pricingOption) {
                    const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                    const quantityControl = pricingOption.querySelector('.quantity-control');
                    
                    if (quantityInput) {
                        quantityInput.value = delegateProduct.count;
                        // Update the total price display
                        this.updateQuantityTotal(quantityInput);
                    }
                    
                    // Show the quantity control since checkbox is checked
                    if (quantityControl) {
                        quantityControl.style.display = 'flex';
                    }
                }
            }
        });
    } else if (this.formData.delegateType) {
        // Fallback for old format (single delegate type)
        const delegateTypeRadio = document.querySelector(`input[name="delegateType"][value="${this.formData.delegateType}"]`);
        if (delegateTypeRadio) {
            delegateTypeRadio.checked = true;
            
            // Show quantity control for fallback too
            const pricingOption = delegateTypeRadio.closest('.pricing-option');
            if (pricingOption) {
                const quantityControl = pricingOption.querySelector('.quantity-control');
                const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                
                if (quantityControl) {
                    quantityControl.style.display = 'flex';
                }
                
                if (quantityInput) {
                    // Update the total price display
                    this.updateQuantityTotal(quantityInput);
                }
            }
        }
    }
    
    if (this.formData.delegateCount) {
        const delegateCountInput = document.getElementById('delegateCount');
        if (delegateCountInput) delegateCountInput.value = this.formData.delegateCount;
    }
    
    // Restore table selections with quantities
    if (this.formData.tables && Array.isArray(this.formData.tables)) {
        this.formData.tables.forEach(table => {
            const checkbox = document.querySelector(`input[name="tableType"][value="${table.type}"]`);
            if (checkbox) {
                checkbox.checked = true;
                
                // Find and set the quantity input for this table
                const pricingOption = checkbox.closest('.pricing-option');
                if (pricingOption) {
                    const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                    const quantityControl = pricingOption.querySelector('.quantity-control');
                    
                    if (quantityInput) {
                        quantityInput.value = table.count;
                        // Update the total price display
                        this.updateQuantityTotal(quantityInput);
                    }
                    
                    // Show the quantity control since checkbox is checked
                    if (quantityControl) {
                        quantityControl.style.display = 'flex';
                    }
                }
            }
        });
    }
    
    // Restore sponsorship selections with quantities
    if (this.formData.sponsorships && Array.isArray(this.formData.sponsorships)) {
        // If there are sponsorships, expand the sponsorship section
        if (this.formData.sponsorships.length > 0) {
            const sponsorshipContent = document.getElementById('sponsorship-content');
            const sponsorshipIcon = document.getElementById('sponsorship-icon');
            if (sponsorshipContent) {
                sponsorshipContent.classList.add('expanded');
                sponsorshipContent.style.display = 'block';
            }
            if (sponsorshipIcon) {
                sponsorshipIcon.classList.add('expanded');
            }
        }
        
        this.formData.sponsorships.forEach(sponsorship => {
            const checkbox = document.querySelector(`input[name="sponsorshipType"][value="${sponsorship.type}"]`);
            if (checkbox) {
                checkbox.checked = true;
                
                // Find and set the quantity input for this sponsorship
                const pricingOption = checkbox.closest('.pricing-option');
                if (pricingOption) {
                    const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                    const quantityControl = pricingOption.querySelector('.quantity-control');
                    
                    if (quantityInput) {
                        quantityInput.value = sponsorship.count;
                        // Update the total price display
                        this.updateQuantityTotal(quantityInput);
                    }
                    
                    // Show the quantity control since checkbox is checked
                    if (quantityControl) {
                        quantityControl.style.display = 'flex';
                    }
                }
            }
        });
    }
    
    // Restore other sponsorship selections with quantities
    if (this.formData.otherSponsorships && Array.isArray(this.formData.otherSponsorships)) {
        // If there are other sponsorships, expand the other sponsorship section
        if (this.formData.otherSponsorships.length > 0) {
            const otherSponsorshipContent = document.getElementById('otherSponsorship-content');
            const otherSponsorshipIcon = document.getElementById('otherSponsorship-icon');
            if (otherSponsorshipContent) {
                otherSponsorshipContent.classList.add('expanded');
                otherSponsorshipContent.style.display = 'block';
            }
            if (otherSponsorshipIcon) {
                otherSponsorshipIcon.classList.add('expanded');
            }
        }
        
        this.formData.otherSponsorships.forEach(otherSponsorship => {
            const checkbox = document.querySelector(`input[name="otherSponsorshipType"][value="${otherSponsorship.type}"]`);
            if (checkbox) {
                checkbox.checked = true;
                
                // Find and set the quantity input for this other sponsorship
                const pricingOption = checkbox.closest('.pricing-option');
                if (pricingOption) {
                    const quantityInput = pricingOption.querySelector('.delegate-qty-input');
                    const quantityControl = pricingOption.querySelector('.quantity-control');
                    
                    if (quantityInput) {
                        quantityInput.value = otherSponsorship.count;
                        // Update the total price display
                        this.updateQuantityTotal(quantityInput);
                    }
                    
                    // Show the quantity control since checkbox is checked
                    if (quantityControl) {
                        quantityControl.style.display = 'flex';
                    }
                }
            }
        });
    }
    
    // Regenerate delegate detail forms before restoring their values
    this.generateDelegateDetails();
    
    // Update pricing summary based on restored selections
    this.updateSummary();
    
    // Use setTimeout to ensure DOM is fully ready before restoring delegate data
    // This prevents race conditions where restoration happens before elements are fully initialized
    setTimeout(() => {
    // Restore Step 2 data (delegates)
    if (this.formData.delegates && this.formData.delegates.length > 0) {
        this.formData.delegates.forEach((delegate, index) => {
            const delegateNumber = index + 1;
            // Map saved field names to DOM element IDs
            const fieldMap = {
                fullName: 'FullName',
                badgeName: 'BadgeName',
                designation: 'Designation',
                email: 'Email',
                dietary: 'Dietary',
                assistance: 'Assistance'
            };
            
            Object.keys(fieldMap).forEach(field => {
                const elementId = `delegate${delegateNumber}${fieldMap[field]}`;
                const input = document.getElementById(elementId);
                
                // Check if the field exists in delegate object (not just if it's truthy)
                // This allows empty strings, 0, false, etc. to be restored
                if (input && field in delegate) {
                    const value = delegate[field];
                    input.value = value !== null && value !== undefined ? value : '';
                }
            });
            
            // Update header if full name exists
            if (delegate.fullName) {
                const headerElement = document.getElementById(`delegate${delegateNumber}Header`);
                if (headerElement) {
                    // Get the current product name from the header
                    const currentText = headerElement.textContent;
                    const productName = currentText.replace(`Delegate ${delegateNumber}`, '').replace(` - ${delegate.fullName}`, '');
                    headerElement.textContent = `Delegate ${delegateNumber}${productName} - ${delegate.fullName}`;
                }
            }
        });
    }
    
    // Restore Step 3 data (contact)
    if (this.formData.contact) {
        // Map saved field names to actual DOM element IDs
        const contactFieldMap = {
            salutation: 'salutation',
            fullName: 'contactFullName',
            designation: 'contactDesignation',
            department: 'department',
            email: 'email',
            mobile: 'mobile',
            university: 'university',
            country: 'country'
        };
        
        Object.keys(contactFieldMap).forEach(field => {
            const elementId = contactFieldMap[field];
            const input = document.getElementById(elementId);
            if (input && this.formData.contact[field]) {
                input.value = this.formData.contact[field];
            }
        });
    }
    
    // Update UI to reflect restored data
    this.populateReview();
    }, 0); // Execute after current call stack
};

RegistrationForm.prototype.clearSavedFormData = function() {
    try {
        localStorage.removeItem('xchange_registration_data');
        localStorage.removeItem('xchange_payment_retry');
    } catch (error) {
        console.error('Failed to clear saved form data:', error);
    }
};

RegistrationForm.prototype.getPaymentRetryData = function() {
    try {
        const retryData = localStorage.getItem('xchange_payment_retry');
        if (retryData) {
            return JSON.parse(retryData);
        }
    } catch (error) {
        console.error('Failed to get payment retry data:', error);
    }
    return null;
};

// Form validation helpers
RegistrationForm.prototype.validateEmail = function(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

RegistrationForm.prototype.validatePhone = function(phone) {
    // Remove all non-digit characters except + at the start
    const cleanPhone = phone.replace(/[^\d+]/g, '');
    
    // International phone number validation
    // Must start with + or digit, be 7-15 digits total
    const phoneRegex = /^\+?[1-9]\d{6,14}$/;
    
    return phoneRegex.test(cleanPhone);
}

RegistrationForm.prototype.formatPhoneNumber = function(phone) {
    // Remove all non-digit characters except + at the start
    let cleaned = phone.replace(/[^\d+]/g, '');
    
    // Ensure it starts with + if it doesn't already
    if (cleaned.length > 0 && !cleaned.startsWith('+')) {
        // If it starts with 0, replace with country code placeholder
        if (cleaned.startsWith('0')) {
            cleaned = '+' + cleaned.substring(1);
        } else {
            cleaned = '+' + cleaned;
        }
    }
    
    return cleaned;
}

// Add real-time validation
document.addEventListener('blur', (e) => {
    if (e.target.type === 'email') {
        const isValid = registrationForm?.validateEmail(e.target.value) || validateEmail(e.target.value);
        if (!isValid && e.target.value) {
            e.target.classList.add('error');
            let errorMsg = e.target.parentNode.querySelector('.error-message');
            if (!errorMsg) {
                errorMsg = document.createElement('div');
                errorMsg.className = 'error-message';
                e.target.parentNode.appendChild(errorMsg);
            }
            errorMsg.textContent = 'Please enter a valid email address';
        } else {
            e.target.classList.remove('error');
            const errorMsg = e.target.parentNode.querySelector('.error-message');
            if (errorMsg) errorMsg.remove();
        }
    } else if (e.target.type === 'tel' || e.target.id === 'mobile') {
        const isValid = registrationForm?.validatePhone(e.target.value) || validatePhone(e.target.value);
        if (!isValid && e.target.value) {
            e.target.classList.add('error');
            let errorMsg = e.target.parentNode.querySelector('.error-message');
            if (!errorMsg) {
                errorMsg = document.createElement('div');
                errorMsg.className = 'error-message';
                e.target.parentNode.appendChild(errorMsg);
            }
            errorMsg.textContent = 'Please enter a valid international phone number (e.g., +60123456789)';
        } else {
            e.target.classList.remove('error');
            const errorMsg = e.target.parentNode.querySelector('.error-message');
            if (errorMsg) errorMsg.remove();
        }
    }
}, true);

// Add phone number formatting on input
document.addEventListener('input', (e) => {
    if (e.target.type === 'tel' || e.target.id === 'mobile') {
        // Auto-format phone number as user types
        const formatted = registrationForm?.formatPhoneNumber(e.target.value) || e.target.value;
        if (formatted !== e.target.value) {
            const cursorPos = e.target.selectionStart;
            e.target.value = formatted;
            // Restore cursor position
            e.target.setSelectionRange(cursorPos, cursorPos);
        }
    }
}, true);

// Function to handle Return to Event Page with configurable URL
async function returnToEventPage() {
    try {
        const response = await fetch('get_event_url.php');
        const result = await response.json();
        
        if (result.success && result.eventPageUrl) {
            window.location.href = result.eventPageUrl;
        } else {
            // Fallback to default
            window.location.href = '../index.html';
        }
    } catch (error) {
        console.error('Failed to get event page URL:', error);
        // Fallback to default
        window.location.href = '../index.html';
    }
}

// Add error handling methods to RegistrationForm class
RegistrationForm.prototype.showConfigError = function() {
    const form = document.getElementById('registrationForm');
    if (form) {
        form.innerHTML = `
            <div class="config-error">
                <div class="error-icon">⚠️</div>
                <h2>System Configuration Error</h2>
                <p>Unable to load registration configuration from database.</p>
                <p>Please contact support or try again later.</p>
                <div class="error-actions">
                    <button onclick="location.reload()" class="btn btn-primary">Retry</button>
                </div>
            </div>
            <style>
                .config-error {
                    text-align: center;
                    padding: 3rem;
                    background: #fef2f2;
                    border: 1px solid #fecaca;
                    border-radius: 12px;
                    margin: 2rem 0;
                }
                .error-icon {
                    font-size: 3rem;
                    margin-bottom: 1rem;
                }
                .config-error h2 {
                    color: #dc2626;
                    margin-bottom: 1rem;
                }
                .config-error p {
                    color: #7f1d1d;
                    margin-bottom: 0.5rem;
                }
                .error-actions {
                    margin-top: 2rem;
                }
            </style>
        `;
    }
};

RegistrationForm.prototype.disableForm = function() {
    const form = document.getElementById('registrationForm');
    if (form) {
        // Disable all form inputs
        const inputs = form.querySelectorAll('input, select, button, textarea');
        inputs.forEach(input => {
            input.disabled = true;
        });
    }
};
