// --- submitListing helper (create docId first, upload images, then setDoc) --- async function submitListing({ title, price, category, state, city, description, status = 'active', files }) { // require auth const user = auth?.currentUser; if (!user) throw new Error('Please sign in first.'); // Create a doc ref (we don't write yet) so we have an ID to use in storage paths const docRef = doc(collection(db, 'listings')); const listingId = docRef.id; // Upload images (uses your uploadImages(listingId, uid, files) implementation) let imageUrls = []; try { if (files && files.length) { imageUrls = await uploadImages(listingId, user.uid, files); } } catch (err) { // bubble up an error to caller throw new Error('Image upload failed: ' + (err?.message || err)); } // Build keywords const keywords = Array.from(new Set([ ...tokenize(title), ...tokenize(category), ...tokenize(city), (state || '').toLowerCase() ])).slice(0, 50); // Build payload (matches your existing doc shape) const payload = { title: title || '', price: Number(price || 0), category: category || '', state: (state || '').toUpperCase(), city: city || '', description: description || '', ownerUid: user.uid, status, publicPreview: true, keywords, imageUrls, coverUrl: imageUrls[0] || null, createdAt: serverTimestamp() }; // Save the document await setDoc(docRef, payload); // Return the id so caller can build link / show UI return listingId; } // --- Replace your existing form submit handler with this wiring --- $('listingForm').addEventListener('submit', async (e) => { e.preventDefault(); try { // Basic auth check const user = auth.currentUser; if (!user) { alert('Please sign in first.'); return; } // Gather fields const title = $('title').value.trim(); const price = Number($('price').value); const category = $('category').value.trim(); const state = $('state').value.trim().toUpperCase(); const city = $('city').value.trim(); const status = $('status').value; const description = $('desc').value.trim(); const files = $('photos').files; // Validate required if (!title || !category || !state || !description || !(price >= 0)) { alert('Please fill out all required fields.'); return; } // Disable submit button while working const submitBtn = e.submitter || $('listingForm').querySelector('button[type="submit"]'); submitBtn?.setAttribute('disabled', 'disabled'); // Call helper that handles uploads + Firestore write const listingId = await submitListing({ title, price, category, state, city, description, status, files }); // Success UI const link = `/listing.html?id=${encodeURIComponent(listingId)}`; $('viewLink').href = link; $('viewLink').textContent = link; $('done').classList.remove('hidden'); window.scrollTo({ top: 0, behavior: 'smooth' }); } catch (err) { console.error(err); alert('Save failed: ' + (err?.message || err)); } finally { // Re-enable submit button const submitBtn = $('listingForm').querySelector('button[type="submit"]'); submitBtn?.removeAttribute('disabled'); } });