// Form navigation and functionality for Premium Rentals

document.addEventListener('DOMContentLoaded', function() {
    // Form state management
    let currentSection = 1;
    const totalSections = 7;
    
    // DOM Elements
    const form = document.getElementById('rental-application-form');
    const progressBar = document.getElementById('progress-bar');
    const progressPercent = document.getElementById('progress-percent');
    const stepIndicators = document.querySelectorAll('.step-indicator');
    const formSections = document.querySelectorAll('.form-section');
    const successModal = document.getElementById('success-modal');
    
    // Initialize the form
    initializeForm();
    
    // Function to initialize the form
    function initializeForm() {
        updateProgressBar();
        setupEventListeners();
        
        // Extensive logging for form submission debugging
        if (form) {
            console.log('Form element found');
            
            // Log when form submit is attempted
            form.addEventListener('submit', function(e) {
                console.log('Form submit event triggered');
                console.log('Event object:', e);
                
                // Make all sections visible so all fields are submitted
                const allSections = document.querySelectorAll('.form-section');
                console.log('Found sections:', allSections.length);
                
                allSections.forEach((section, index) => {
                    console.log('Making section ' + index + ' visible');
                    section.classList.remove('hidden');
                });
                
                console.log('Form should now submit');
            });
            
            // Also log general form events
            form.addEventListener('click', function(e) {
                console.log('Form clicked:', e.target);
            });
        } else {
            console.log('Form element NOT found');
        }
    }
    
    // Set up event listeners
    function setupEventListeners() {
        // Next buttons
        document.querySelectorAll('[onclick^="nextSection"]').forEach(button => {
            button.addEventListener('click', function() {
                const section = parseInt(this.getAttribute('onclick').match(/\d+/)[0]);
                nextSection(section);
            });
        });
        
        // Previous buttons
        document.querySelectorAll('[onclick^="prevSection"]').forEach(button => {
            button.addEventListener('click', function() {
                const section = parseInt(this.getAttribute('onclick').match(/\d+/)[0]);
                prevSection(section);
            });
        });
        
        // Step indicators
        stepIndicators.forEach((indicator, index) => {
            indicator.addEventListener('click', function() {
                showSection(index + 1);
            });
        });
        
        // Close modal
        document.querySelector('[onclick="closeModal()"]').addEventListener('click', closeModal);
        
        // Close modal when clicking outside
        window.addEventListener('click', function(event) {
            if (event.target === successModal) {
                closeModal();
            }
        });
    }
    
    // Show a specific section
    function showSection(sectionNumber) {
        // Hide all sections
        formSections.forEach(section => {
            section.classList.add('hidden');
        });
        
        // Update step indicators
        stepIndicators.forEach((indicator, index) => {
            const circle = indicator.children[0];
            if (index + 1 < sectionNumber) {
                circle.className = 'w-10 h-10 rounded-full bg-green-500 text-white flex items-center justify-center mb-1';
                circle.innerHTML = '<i class="fas fa-check"></i>';
            } else if (index + 1 === sectionNumber) {
                circle.className = 'w-10 h-10 rounded-full bg-primary text-white flex items-center justify-center mb-1';
                circle.textContent = index + 1;
            } else {
                circle.className = 'w-10 h-10 rounded-full bg-gray-300 text-gray-700 flex items-center justify-center mb-1';
                circle.textContent = index + 1;
            }
        });
        
        // Show selected section
        document.getElementById(`section-${sectionNumber}`).classList.remove('hidden');
        
        currentSection = sectionNumber;
        updateProgressBar();
    }
    
    // Navigate to next section
    function nextSection(current) {
        if (validateSection(current) && current < totalSections) {
            showSection(current + 1);
        }
    }
    
    // Navigate to previous section
    function prevSection(current) {
        if (current > 1) {
            showSection(current - 1);
        }
    }
    
    // Update progress bar
    function updateProgressBar() {
        const progress = Math.round((currentSection / totalSections) * 100);
        progressBar.style.width = `${progress}%`;
        progressPercent.textContent = progress;
    }
    
    // Validate form section
    function validateSection(sectionNumber) {
        const section = document.getElementById(`section-${sectionNumber}`);
        const requiredFields = section.querySelectorAll('[required]');
        let isValid = true;
        
        requiredFields.forEach(field => {
            if (!field.value.trim()) {
                isValid = false;
                field.classList.add('border-red-500');
                // Add error message
                if (!field.nextElementSibling || !field.nextElementSibling.classList.contains('error-message')) {
                    const errorMsg = document.createElement('div');
                    errorMsg.className = 'error-message text-red-500 text-sm mt-1';
                    errorMsg.textContent = 'This field is required';
                    field.parentNode.insertBefore(errorMsg, field.nextSibling);
                }
            } else {
                field.classList.remove('border-red-500');
                // Remove error message if it exists
                if (field.nextElementSibling && field.nextElementSibling.classList.contains('error-message')) {
                    field.nextElementSibling.remove();
                }
            }
        });
        
        return isValid;
    }
    
    // Scroll to form
    window.scrollToForm = function() {
        document.querySelector('#section-1').scrollIntoView({ behavior: 'smooth' });
    };
    

    
    // Close modal
    window.closeModal = function() {
        successModal.classList.add('hidden');
    };
    
    // Form data collection (for demonstration purposes)
    function collectFormData() {
        const formData = new FormData(form);
        const data = {};
        
        for (const [key, value] of formData.entries()) {
            data[key] = value;
        }
        
        return data;
    }
});