// EstateSphere Pro - Main JavaScript class EstateSphereApp { constructor() { this.currentUser = null; this.darkMode = false; this.apiBaseUrl = 'http://localhost:3000/api'; this.init(); } init() { this.setupTheme(); this.setupEventListeners(); this.loadUserPreferences(); this.checkAuthStatus(); } setupTheme() { const savedTheme = localStorage.getItem('estatesphere-theme'); const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; this.darkMode = savedTheme === 'dark' || (!savedTheme && prefersDark); this.applyTheme(); } applyTheme() { if (this.darkMode) { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } localStorage.setItem('estatesphere-theme', this.darkMode ? 'dark' : 'light'); } toggleTheme() { this.darkMode = !this.darkMode; this.applyTheme(); } async apiCall(endpoint, options = {}) { try { const token = localStorage.getItem('estatesphere-token'); const headers = { 'Content-Type': 'application/json', ...options.headers }; if (token) { headers['Authorization'] = `Bearer ${token}`; } const response = await fetch(`${this.apiBaseUrl}${endpoint}`, { ...options, headers }); if (!response.ok) { throw new Error(`API error: ${response.statusText}`); } const data = await response.json(); return { success: true, data }; } catch (error) { console.error('API call failed:', error); return { success: false, error: error.message }; } } setupEventListeners() { // Theme toggle const themeToggle = document.querySelector('.theme-toggle'); if (themeToggle) { themeToggle.addEventListener('click', () => this.toggleTheme()); } // Mobile menu toggle const mobileMenuBtn = document.querySelector('.mobile-menu-btn'); const mobileMenu = document.querySelector('.mobile-menu'); if (mobileMenuBtn && mobileMenu) { mobileMenuBtn.addEventListener('click', () => { mobileMenu.classList.toggle('hidden'); }); } // Property search functionality this.setupPropertySearch(); // Contact form handling this.setupContactForm(); // Login form handling this.setupLoginForm(); // Registration form handling this.setupRegistrationForm(); } setupPropertySearch() { const searchForm = document.querySelector('#property-search'); if (searchForm) { searchForm.addEventListener('submit', (e) => { e.preventDefault(); this.performPropertySearch(new FormData(searchForm)); }); } async performPropertySearch(formData) { const params = new URLSearchParams(); for (const [key, value] of formData.entries()) { if (value) params.append(key, value); } // Show loading state this.showLoading(); try { const result = await this.apiCall(`/properties/search?${params.toString()}`); if (result.success) { this.displaySearchResults(result.data); } else { alert('Search failed: ' + result.error); } } catch (error) { alert('Search failed: ' + error.message); } finally { this.hideLoading(); } } showLoading() { const searchButton = document.querySelector('#property-search button[type="submit"]'); if (searchButton) { searchButton.innerHTML = '
'; } } hideLoading() { const searchButton = document.querySelector('#property-search button[type="submit"]'); if (searchButton) { searchButton.textContent = 'Search Properties'; } } displaySearchResults(properties) { const propertiesGrid = document.getElementById('properties-grid'); if (!propertiesGrid) return; if (properties.length === 0) { propertiesGrid.innerHTML = '

No properties found matching your criteria.

'; return; } propertiesGrid.innerHTML = properties.map(property => `

${property.title}

${property.bedrooms} Beds • ${property.bathrooms} Baths • ${property.squareFeet} sqft

${property.price.toLocaleString()} View Details
`).join(''); } setupContactForm() { const contactForm = document.getElementById('contact-form'); if (contactForm) { contactForm.addEventListener('submit', async (e) => { e.preventDefault(); const formData = new FormData(contactForm); const result = await this.apiCall('/contact', { method: 'POST', body: JSON.stringify(Object.fromEntries(formData))) }); } } setupLoginForm() { const loginForm = document.getElementById('login-form'); if (loginForm) { loginForm.addEventListener('submit', async (e) => { e.preventDefault(); const formData = new FormData(loginForm); const result = await this.apiCall('/login', { method: 'POST', body: JSON.stringify(Object.fromEntries(formData))) }); } } setupRegistrationForm() { const registerForm = document.getElementById('register-form'); if (registerForm) { registerForm.addEventListener('submit', async (e) => { e.preventDefault(); const formData = new FormData(registerForm); const result = await this.apiCall('/register', { method: 'POST', body: JSON.stringify(Object.fromEntries(formData))) }); } } async checkAuthStatus() { const token = localStorage.getItem('estatesphere-token'); if (token) { const result = await this.apiCall('/profile'); if (result.success) { this.currentUser = result.data; this.updateUIForAuth(); } } updateUIForAuth() { const authButtons = document.querySelectorAll('.auth-buttons'); const userActions = document.querySelectorAll('.user-actions'); if (this.currentUser) { authButtons.forEach(btn => btn.style.display = 'none'); userActions.forEach(action => action.style.display = 'flex'); // Update user info in UI const userInfoElements = document.querySelectorAll('.user-info'); userInfoElements.forEach(el => { el.textContent = this.currentUser.name; }); } } // Authentication methods async login(email, password) { const result = await this.apiCall('/login', { method: 'POST', body: JSON.stringify({ email, password }) }); if (result.success) { localStorage.setItem('estatesphere-token', result.data.token); this.currentUser = result.data.user; this.updateUIForAuth(); return { success: true }; } else { return { success: false, error: result.error }; } } async register(userData) { const result = await this.apiCall('/register', { method: 'POST', body: JSON.stringify(userData) }); if (result.success) { localStorage.setItem('estatesphere-token', result.data.token); this.currentUser = result.data.user; this.updateUIForAuth(); return { success: true }; } else { return { success: false, error: result.error }; } } logout() { localStorage.removeItem('estatesphere-token'); this.currentUser = null; this.updateUIForAuth(); } // Property management methods async loadProperties(page = 1, limit = 9) { const result = await this.apiCall(`/properties?page=${page}&limit=${limit}`); return result; } async loadPropertyDetails(propertyId) { const result = await this.apiCall(`/properties/${propertyId}`); return result; } async loadFeaturedProperties() { const result = await this.apiCall('/properties/featured'); return result; } async loadAgents() { const result = await this.apiCall('/agents'); return result; } calculateMortgage(loanAmount, interestRate, loanTerm) { const monthlyRate = interestRate / 100 / 12; const payments = loanTerm * 12; const x = Math.pow(1 + monthlyRate, payments); const monthlyPayment = (loanAmount * x * monthlyRate) / (x - 1); return monthlyPayment; } loadUserPreferences() { // Load user preferences from localStorage } } // Initialize the app when DOM is loaded document.addEventListener('DOMContentLoaded', () => { window.estateSphereApp = new EstateSphereApp(); }); // Utility Functions const EstateUtils = { formatCurrency(amount, currency = 'USD') { return new Intl.NumberFormat('en-US', { style: 'currency', currency: currency }).format(amount); }, formatDate(date) { return new Intl.DateTimeFormat('en-US').format(new Date(date)); }, debounce(func, wait) { let timeout; return function executedFunction(...args) { const later = () => { clearTimeout(timeout); func(...args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; }, throttle(func, limit) { let inThrottle; return function() { const args = arguments; const context = this; if (!inThrottle) { func.apply(context, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } }; } }; // Export for module usage if (typeof module !== 'undefined' && module.exports) { module.exports = { EstateSphereApp, EstateUtils }; }