document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('requestPropertyForm');

    // --- Visual Chip Logic ---
    function updateChipStyles() {
        document.querySelectorAll('input[type="radio"], input[type="checkbox"]').forEach(input => {
            const chip = input.parentElement.querySelector('.selection-chip');
            if (chip) {
                if (input.checked) {
                    chip.classList.add('active');
                } else {
                    chip.classList.remove('active');
                }
            }
        });
    }

    // Attach to all inputs in the form
    form.querySelectorAll('input').forEach(input => {
        input.addEventListener('change', updateChipStyles);
    });
    updateChipStyles();

    // --- Form Submission ---
    if (form) {
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.innerHTML;

            const formData = new FormData(form);
            const data = Object.fromEntries(formData);

            // Collect multiple values for checkboxes (Property Type, BHK)
            const propertyTypes = Array.from(form.querySelectorAll('input[name="propertyType"]:checked')).map(el => el.value);
            const bhks = Array.from(form.querySelectorAll('input[name="bhk"]:checked')).map(el => el.value);

            if (propertyTypes.length === 0) return alert('Please select at least one property type');
            if (!data.customerName) return alert('Please enter your name');
            if (!data.customerMobile || data.customerMobile.length !== 10) return alert('Please enter a valid 10-digit mobile number');

            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Submitting...';

            let currentUser = Auth.getCurrentUser();

            // Handling guest registration if not logged in
            if (!currentUser) {
                try {
                    const otpRes = await Auth.requestRegistrationOTP(data.customerName, data.customerMobile);
                    alert(otpRes.message || 'OTP Sent to ' + data.customerMobile);
                    const inputOtp = prompt('Enter the 4-digit OTP sent to your mobile:');
                    
                    if (!inputOtp || inputOtp.trim().length !== 4) {
                        alert('Invalid OTP. Please try again.');
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = originalBtnText;
                        return;
                    }

                    currentUser = await Auth.register(data.customerName, data.customerMobile, inputOtp.trim(), data.preferredLocations || 'Not Specified');
                } catch (err) {
                    alert('Verification failed: ' + (err.message || 'Unknown error'));
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalBtnText;
                    return;
                }
            }

            const requestLead = {
                lead_type: 'property_request',
                customerName: data.customerName,
                customerMobile: data.customerMobile,
                posterRole: data.posterRole, // New field captured from radio button
                requirementType: data.requirementType,
                propertyTypes: propertyTypes,
                bhks: bhks,
                budgetMin: data.budgetMin,
                budgetMax: data.budgetMax,
                moveTimeline: data.moveTimeline,
                preferredLocations: data.preferredLocations,
                additionalRequirements: data.requirements,
                status: 'New',
                timestamp: new Date().toISOString()
            };

            try {
                const response = await API.Leads.create(requestLead);
                
                submitBtn.innerHTML = '<i class="fas fa-check-circle mr-2"></i> Request Submitted!';
                alert('Success! We have received your property search request. Our team will contact you shortly with matching options.');
                
                window.location.href = 'properties.html';
            } catch (err) {
                console.error(err);
                alert('Submission failed: ' + (err.message || 'Unknown error'));
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
            }
        });
    }
});
