// Location Data (Fallback/Initial)
const locationData = {
    "Telangana": {
        "Hyderabad": ["Gachibowli", "Madhapur", "Jubilee Hills", "Banjara Hills", "Kukatpally", "Kondapur", "Hitech City", "Manikonda"],
        "Ranga Reddy": ["Shamshabad", "Rajendranagar", "Serilingampally"],
        "Medchal-Malkajgiri": ["Medchal", "Kompally", "Alwal"]
    },
    "Andhra Pradesh": {
        "Visakhapatnam": ["Gajuwaka", "MVP Colony", "Seethammadhara"],
        "Vijayawada": ["Benz Circle", "Patamata", "Gunadala"],
        "Guntur": ["Arundelpet", "Brodipet", "Vidyanagar"]
    }
};

// Feature Templates
const featureTemplates = {
    "Apartment Flat": `
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4 md:gap-6">
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Bedrooms (BHK)</label>
                <div class="flex gap-2 flex-wrap">
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="bhk" value="1" class="hidden"> 1 BHK</label>
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="bhk" value="2" class="hidden"> 2 BHK</label>
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="bhk" value="3" class="hidden"> 3 BHK</label>
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="bhk" value="4+" class="hidden"> 4+ BHK</label>
                </div>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Furnishing</label>
                <select class="premium-input" name="furnishing">
                    <option value="Unfurnished">Unfurnished</option>
                    <option value="Semi-furnished">Semi-furnished</option>
                    <option value="Fully-furnished">Fully-furnished</option>
                </select>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Built-up Area (sq.ft)</label>
                <input type="number" class="premium-input" name="builtUpArea" placeholder="Ex: 1200">
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Facing</label>
                <select class="premium-input" name="facing">
                    <option value="East">East</option>
                    <option value="West">West</option>
                    <option value="North">North</option>
                    <option value="South">South</option>
                    <option value="North-East">North-East</option>
                    <option value="North-West">North-West</option>
                    <option value="South-East">South-East</option>
                    <option value="South-West">South-West</option>
                </select>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Total Floors</label>
                <input type="number" class="premium-input" name="totalFloors" placeholder="Total building floors">
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Floor No.</label>
                <input type="number" class="premium-input" name="floorNo" placeholder="Property floor number">
            </div>
        </div>
    `,
    "Agriculture Land": `
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4 md:gap-6">
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Land Area (acres)</label>
                <input type="number" class="premium-input" name="landArea" placeholder="Ex: 2.5">
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Soil Type</label>
                <select class="premium-input" name="soilType">
                    <option value="Red">Red</option>
                    <option value="Black">Black</option>
                    <option value="Loamy">Loamy</option>
                    <option value="Mixed">Mixed</option>
                </select>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Water Availability</label>
                <div class="flex gap-4">
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="waterAvailability" value="Yes" class="hidden"> Yes</label>
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="waterAvailability" value="No" class="hidden" checked> No</label>
                </div>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Electricity Connection</label>
                <div class="flex gap-4">
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="electricity" value="Yes" class="hidden"> Yes</label>
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="electricity" value="No" class="hidden" checked> No</label>
                </div>
            </div>
        </div>
    `,
    "Independent House": `
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4 md:gap-6">
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Bedrooms (BHK)</label>
                <div class="flex gap-2 flex-wrap">
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="bhk" value="1" class="hidden"> 1 BHK</label>
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="bhk" value="2" class="hidden"> 2 BHK</label>
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="bhk" value="3" class="hidden"> 3 BHK</label>
                </div>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Facing</label>
                <select class="premium-input" name="facing">
                    <option value="East">East</option>
                    <option value="West">West</option>
                    <option value="North">North</option>
                    <option value="South">South</option>
                    <option value="North-East">North-East</option>
                    <option value="North-West">North-West</option>
                    <option value="South-East">South-East</option>
                    <option value="South-West">South-West</option>
                </select>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Plot Area (sq.yds)</label>
                <input type="number" class="premium-input" name="plotArea" placeholder="Ex: 200">
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Furnishing</label>
                <select class="premium-input" name="furnishing">
                    <option value="Unfurnished">Unfurnished</option>
                    <option value="Semi-furnished">Semi-furnished</option>
                    <option value="Fully-furnished">Fully-furnished</option>
                </select>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Total Floors</label>
                <input type="number" class="premium-input" name="totalFloors" placeholder="Total building floors">
            </div>
        </div>
    `,
    "Villa": `
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4 md:gap-6">
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Bedrooms (BHK)</label>
                <div class="flex gap-2 flex-wrap">
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="bhk" value="2" class="hidden"> 2 BHK</label>
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="bhk" value="3" class="hidden"> 3 BHK</label>
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="bhk" value="4" class="hidden"> 4 BHK</label>
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="bhk" value="5+" class="hidden"> 5+ BHK</label>
                </div>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Facing</label>
                <select class="premium-input" name="facing">
                    <option value="East">East</option>
                    <option value="West">West</option>
                    <option value="North">North</option>
                    <option value="South">South</option>
                    <option value="North-East">North-East</option>
                    <option value="North-West">North-West</option>
                    <option value="South-East">South-East</option>
                    <option value="South-West">South-West</option>
                </select>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Plot Area (sq.yds)</label>
                <input type="number" class="premium-input" name="plotArea" placeholder="Ex: 300">
            </div>
             <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Furnishing</label>
                <select class="premium-input" name="furnishing">
                    <option value="Unfurnished">Unfurnished</option>
                    <option value="Semi-furnished">Semi-furnished</option>
                    <option value="Fully-furnished">Fully-furnished</option>
                </select>
            </div>
        </div>
    `,
    "Plot": `
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4 md:gap-6">
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Plot Area (sq.yds)</label>
                <input type="number" class="premium-input" name="plotArea" placeholder="Ex: 200">
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Facing</label>
                <select class="premium-input" name="facing">
                    <option value="East">East</option>
                    <option value="West">West</option>
                    <option value="North">North</option>
                    <option value="South">South</option>
                    <option value="North-East">North-East</option>
                    <option value="North-West">North-West</option>
                    <option value="South-East">South-East</option>
                    <option value="South-West">South-West</option>
                </select>
            </div>
            <div class="space-y-2 md:col-span-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Layout Type</label>
                <select class="premium-input" name="layoutType">
                    <option value="HMDA Layout">HMDA Layout</option>
                    <option value="HUDA Layout">HUDA Layout</option>
                    <option value="Grampanchayath Layout">Grampanchayath Layout</option>
                    <option value="DTCP Layout">DTCP Layout</option>
                    <option value="YTDA Layout">YTDA Layout</option>
                    <option value="Others">Others</option>
                </select>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Full LRS Available?</label>
                <div class="flex gap-4">
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="lrs" value="Yes" class="hidden"> Yes</label>
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="lrs" value="No" class="hidden" checked> No</label>
                </div>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Boundary Wall?</label>
                <div class="flex gap-4">
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="boundary" value="Yes" class="hidden"> Yes</label>
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="boundary" value="No" class="hidden" checked> No</label>
                </div>
            </div>
        </div>
    `,
    "Commercial": `
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4 md:gap-6">
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Commercial Type</label>
                <select class="premium-input" name="commercialType">
                    <option value="Office Space">Office Space</option>
                    <option value="Shop/Showroom">Shop/Showroom</option>
                    <option value="Warehouse">Warehouse</option>
                    <option value="Industrial">Industrial</option>
                </select>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Furnishing</label>
                <select class="premium-input" name="furnishing">
                    <option value="Unfurnished">Unfurnished</option>
                    <option value="Semi-furnished">Semi-furnished</option>
                    <option value="Fully-furnished">Fully-furnished</option>
                </select>
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Built-up Area (sq.ft)</label>
                <input type="number" class="premium-input" name="builtUpArea" placeholder="Ex: 1000">
            </div>
            <div class="space-y-2">
                <label class="text-[11px] font-black text-slate-400 uppercase tracking-widest ml-2">Parking Availability</label>
                <div class="flex gap-4">
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="parking" value="Yes" class="hidden"> Yes</label>
                    <label class="btn-outline flex-1 selection-chip"><input type="radio" name="parking" value="No" class="hidden" checked> No</label>
                </div>
            </div>
        </div>
    `
};

let pincodeData = [];

document.addEventListener('DOMContentLoaded', function () {
    const propertyTypeSelect = document.getElementById('propertyTypeSelect');
    const dynamicFeaturesDiv = document.getElementById('dynamicFeatures');
    const constructionAgeGroup = document.getElementById('constructionAgeGroup');
    const pincodeInput = document.getElementById('pincodeInput');
    const stateInput = document.getElementById('stateInput');
    const districtInput = document.getElementById('districtInput');
    const areaSelect = document.getElementById('areaSelect');
    const pincodeStatus = document.getElementById('pincodeStatus');
    const submitPropertyBtn = document.getElementById('submitProperty');
    const propTitle = document.getElementById('propTitle');
    const propPrice = document.getElementById('propPrice');
    const propAddress = document.getElementById('propAddress');
    const propDesc = document.getElementById('propDesc');
    const listingName = document.getElementById('listingName');
    const listingMobile = document.getElementById('listingMobile');
    const listingBy = document.getElementById('listingBy');
    const propertyHierarchy = document.getElementById('propertyHierarchy');
    const approvalsWrapper = document.getElementById('approvalsWrapper');
    const amenitiesWrapper = document.getElementById('amenitiesWrapper');
    
    // Voice Recorder Variables
    const startRecordBtn = document.getElementById('startRecordBtn');
    const stopRecordBtn = document.getElementById('stopRecordBtn');
    const playAudioBtn = document.getElementById('playAudioBtn');
    const deleteAudioBtn = document.getElementById('deleteAudioBtn');
    const audioPreviewContainer = document.getElementById('audioPreviewContainer');
    const audioPlayback = document.getElementById('audioPlayback');
    const recordStatus = document.getElementById('recordStatus');
    const audioProgress = document.getElementById('audioProgress');

    let mediaRecorder;
    let audioChunks = [];
    let audioBlob = null;
    let audioUrl = null;
    let selectedPhotos = [];

    // Voice Recording Logic
    if (startRecordBtn) {
        startRecordBtn.addEventListener('click', async () => {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                mediaRecorder = new MediaRecorder(stream);
                audioChunks = [];

                mediaRecorder.ondataavailable = (event) => {
                    audioChunks.push(event.data);
                };

                mediaRecorder.onstop = () => {
                    audioBlob = new Blob(audioChunks, { type: 'audio/mp3' });
                    audioUrl = URL.createObjectURL(audioBlob);
                    audioPlayback.src = audioUrl;
                    
                    audioPreviewContainer.classList.remove('hidden');
                    startRecordBtn.classList.remove('hidden');
                    startRecordBtn.classList.remove('recording-active');
                    stopRecordBtn.classList.add('hidden');
                    recordStatus.textContent = "Voice note recorded";
                    recordStatus.classList.replace('text-rose-500', 'text-emerald-500');
                };

                mediaRecorder.start();
                startRecordBtn.classList.add('recording-active');
                stopRecordBtn.classList.remove('hidden');
                startRecordBtn.classList.add('hidden');
                recordStatus.textContent = "Recording... (Max 60s)";
                recordStatus.classList.add('text-rose-500');

                // Auto stop after 60s
                setTimeout(() => {
                    if (mediaRecorder.state === "recording") {
                        mediaRecorder.stop();
                    }
                }, 60000);

            } catch (err) {
                console.error("Microphone access denied:", err);
                alert("Microphone access is required for voice notes.");
            }
        });
    }

    if (stopRecordBtn) {
        stopRecordBtn.addEventListener('click', () => {
            if (mediaRecorder && mediaRecorder.state === "recording") {
                mediaRecorder.stop();
            }
        });
    }

    if (playAudioBtn) {
        playAudioBtn.addEventListener('click', () => {
            if (audioPlayback.paused) {
                audioPlayback.play();
                playAudioBtn.innerHTML = '<i class="fas fa-pause"></i>';
            } else {
                audioPlayback.pause();
                playAudioBtn.innerHTML = '<i class="fas fa-play"></i>';
            }
        });

        audioPlayback.addEventListener('timeupdate', () => {
            const progress = (audioPlayback.currentTime / audioPlayback.duration) * 100;
            audioProgress.style.width = progress + "%";
        });

        audioPlayback.addEventListener('ended', () => {
            playAudioBtn.innerHTML = '<i class="fas fa-play"></i>';
            audioProgress.style.width = "0%";
        });
    }

    if (deleteAudioBtn) {
        deleteAudioBtn.addEventListener('click', () => {
            audioBlob = null;
            audioUrl = null;
            audioPlayback.src = "";
            audioPreviewContainer.classList.add('hidden');
            recordStatus.textContent = "Tap to start recording";
            recordStatus.classList.remove('text-emerald-500', 'text-rose-500');
            audioProgress.style.width = "0%";
        });
    }
    if (photoInput && photoContainer) {
        photoInput.addEventListener('change', function (e) {
            const files = Array.from(e.target.files);
            if (selectedPhotos.length + files.length > 10) {
                alert("Maximum 10 photos allowed.");
                return;
            }

            files.forEach(file => {
                if (file.size > 5 * 1024 * 1024) return; // 5MB limit
                
                const reader = new FileReader();
                reader.onload = function (event) {
                    const photoId = Date.now() + Math.random();
                    selectedPhotos.push({ id: photoId, file: file, data: event.target.result });
                    renderPhotos();
                }
                reader.readAsDataURL(file);
            });
            photoInput.value = ""; // Reset input
        });
    }

    function renderPhotos() {
        // Clear previous previews except the "Add" button
        const addBtn = photoContainer.querySelector('label');
        photoContainer.innerHTML = "";
        
        selectedPhotos.forEach(photo => {
            const wrapper = document.createElement('div');
            wrapper.className = "aspect-square glass-card overflow-hidden relative group animate-in zoom-in-50 duration-300";
            wrapper.innerHTML = `
                <img src="${photo.data}" class="w-full h-full object-cover">
                <button type="button" class="absolute top-2 right-2 w-6 h-6 bg-rose-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity" onclick="removePhoto(${photo.id})">
                    <i class="fas fa-times text-[10px]"></i>
                </button>
            `;
            photoContainer.appendChild(wrapper);
        });

        if (selectedPhotos.length < 10) {
            photoContainer.appendChild(addBtn);
        }
    }

    window.removePhoto = function(id) {
        selectedPhotos = selectedPhotos.filter(p => p.id !== id);
        renderPhotos();
    };

    // Load Pincode Data
    fetch('assets/data/PINCODES.csv')
        .then(response => response.text())
        .then(csvText => {
            pincodeData = parseCSV(csvText);
            console.log("Pincode data loaded:", pincodeData.length, "entries");
        })
        .catch(err => console.error("Error loading pincode data:", err));

    // Pincode Lookup Logic
    if (pincodeInput) {
        pincodeInput.addEventListener('input', function () {
            const pincode = this.value;
            if (pincode.length === 6) {
                // Use PINCODE_DATA if available, fallback to pincodeData (fetched CSV)
                const data = (typeof PINCODE_DATA !== 'undefined') ? PINCODE_DATA[pincode] : pincodeData.find(i => i.pincode === pincode);
                
                if (data) {
                    const state = data.s || data.state;
                    const districtOrCity = data.c || data.district || data.city;
                    const areas = data.a || (pincodeData.filter(i => i.pincode === pincode).map(i => i.area));

                    stateInput.value = state;
                    districtInput.value = districtOrCity;

                    areaSelect.innerHTML = '<option value="">Select Area</option>';
                    const uniqueAreas = [...new Set(areas)];
                    uniqueAreas.sort().forEach(area => {
                        const option = document.createElement('option');
                        option.value = area;
                        option.textContent = area;
                        areaSelect.appendChild(option);
                    });
                    
                    const manualOption = document.createElement('option');
                    manualOption.value = "MANUAL";
                    manualOption.textContent = "+ Area not in list (Enter Manually)";
                    areaSelect.appendChild(manualOption);

                    pincodeStatus.textContent = "Pincode verified";
                    pincodeStatus.className = "text-[10px] font-bold mt-1 px-2 text-emerald-500";
                } else {
                    pincodeStatus.textContent = "Pincode not found";
                    pincodeStatus.className = "text-[10px] font-bold mt-1 px-2 text-rose-500";
                    
                    areaSelect.innerHTML = '<option value="">Select Area</option>';
                    const manualOption = document.createElement('option');
                    manualOption.value = "MANUAL";
                    manualOption.textContent = "+ Enter Area Manually";
                    areaSelect.appendChild(manualOption);
                }
            } else {
                pincodeStatus.textContent = "";
            }
        });

        // Handle Manual Area Selection
        areaSelect.addEventListener('change', function() {
            if (this.value === 'MANUAL') {
                const manualArea = prompt("Please enter your Area/Locality name:");
                if (manualArea && manualArea.trim()) {
                    const newOption = document.createElement('option');
                    newOption.value = manualArea.trim();
                    newOption.textContent = manualArea.trim();
                    newOption.selected = true;
                    this.insertBefore(newOption, this.firstChild);
                } else {
                    this.value = "";
                }
            }
        });
    }

    function toggleConditionalSections() {
        const type = propertyTypeSelect?.value;
        
        const isApartment = (type === 'Apartment Flat');
        const isVilla = (type === 'Villa');
        const isHouse = (type === 'Independent House');
        const isCommercial = (type === 'Commercial');

        // Logic: Approvals & Amenities visible for Apartments, Villas, Independent Houses, and Commercial properties
        const shouldShow = isApartment || isVilla || isHouse || isCommercial;

        if (approvalsWrapper) {
            approvalsWrapper.style.display = shouldShow ? 'block' : 'none';
        }
        if (amenitiesWrapper) {
            amenitiesWrapper.style.display = shouldShow ? 'block' : 'none';
        }
    }

    function updateFeatures() {
        if (!propertyTypeSelect || !dynamicFeaturesDiv) return;
        const selectedType = propertyTypeSelect.value;
        dynamicFeaturesDiv.innerHTML = featureTemplates[selectedType] || '';

        if (constructionAgeGroup) {
            if (selectedType === 'Plot' || selectedType === 'Agriculture Land') {
                constructionAgeGroup.classList.add('hidden');
            } else {
                constructionAgeGroup.classList.remove('hidden');
            }
        }
        initRadioButtons();
        toggleConditionalSections();
    }

    if (propertyTypeSelect) {
        updateFeatures();
        propertyTypeSelect.addEventListener('change', updateFeatures);
    }

    if (propertyHierarchy) {
        propertyHierarchy.addEventListener('change', toggleConditionalSections);
    }

    if (submitPropertyBtn) {
        submitPropertyBtn.addEventListener('click', async function () {
            const title = (propTitle && propTitle.value.trim()) || '';
            const type = propertyTypeSelect ? propertyTypeSelect.value : '';
            const price = (propPrice && propPrice.value.trim()) || '';
            const pincode = (pincodeInput && pincodeInput.value.trim()) || '';
            const state = (stateInput && stateInput.value.trim()) || '';
            const district = (districtInput && districtInput.value.trim()) || '';
            const area = (areaSelect && areaSelect.value.trim()) || '';
            const address = (propAddress && propAddress.value.trim()) || '';
            const desc = (propDesc && propDesc.value.trim()) || '';
            const lName = (listingName && listingName.value.trim()) || '';
            const lMobile = (listingMobile && listingMobile.value.trim()) || '';
            const lBy = (listingBy && listingBy.value) || 'Owner';
            const constructionAge = constructionAgeSelect ? constructionAgeSelect.value : '';

            const hierarchy = document.getElementById('propertyHierarchy')?.value || 'Normal';
            const approvals = Array.from(document.querySelectorAll('input[name="approvals"]:checked')).map(cb => cb.value);
            const amenities = Array.from(document.querySelectorAll('input[name="amenities"]:checked')).map(cb => cb.value);
            
            // Extract features from dynamic template
            const featureData = {};
            dynamicFeaturesDiv.querySelectorAll('input, select').forEach(el => {
                if (el.type === 'radio' && !el.checked) return;
                if (el.name) featureData[el.name] = el.value;
            });

            if (!title || !type || !price || !pincode || !area || !lName || !lMobile) {
                return alert('Please fill all required fields correctly.');
            }

            let currentUser = Auth.getCurrentUser();
            if (!currentUser) {
                try {
                    const otpRes = await Auth.requestRegistrationOTP(lName, lMobile);
                    alert(otpRes.message || 'OTP Sent');
                    const inputOtp = prompt('Enter the 4-digit OTP sent to your mobile:');
                    if (!inputOtp || inputOtp.trim().length !== 4) return;
                    const regAddress = `${address}, ${area}, ${district}, ${state} - ${pincode}`;
                    currentUser = await Auth.register(lName, lMobile, inputOtp.trim(), regAddress);
                } catch (err) {
                    alert('Verification failed: ' + err.message);
                    return;
                }
            }

            const property = {
                title, type, price,
                location: { pincode, state, district, area },
                address, description: desc,
                constructionAge,
                hierarchy,
                approvals,
                amenities,
                features: featureData,
                photos: selectedPhotos.map(p => p.data),
                voiceNote: audioBlob ? "Recorded" : null, // In a real app, you'd upload the audio file
                listing: { name: lName, mobile: lMobile, by: lBy }
            };

            try {
                const response = await API.Properties.create(property);
                alert('Property submitted successfully!');
                window.location.href = 'properties.html';
            } catch (err) {
                console.error(err);
                alert('Failed to submit property.');
            }
        });
    }
});

function parseCSV(csvText) {
    const lines = csvText.split('\n');
    const result = [];
    for (let i = 1; i < lines.length; i++) {
        const line = lines[i].trim();
        if (!line) continue;
        const parts = line.split(',');
        if (parts.length >= 4) {
            result.push({
                pincode: parts[0].trim(),
                state: parts[1].trim(),
                district: parts[2].trim(),
                area: parts[3].trim().replace(/"/g, '')
            });
        }
    }
    return result;
}

function initRadioButtons() {
    document.querySelectorAll('.selection-chip input[type="radio"]').forEach(input => {
        const updateStyle = () => {
            const name = input.name;
            document.querySelectorAll(`input[name="${name}"]`).forEach(rb => {
                if (rb.checked) {
                    rb.parentElement.classList.add('active');
                } else {
                    rb.parentElement.classList.remove('active');
                }
            });
        };
        input.addEventListener('change', updateStyle);
        if (input.checked) updateStyle();
    });
}
