File size: 10,415 Bytes
2ca0dc6
173f164
 
 
 
 
2ca0dc6
173f164
 
 
 
 
 
 
2ca0dc6
173f164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ca0dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173f164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ca0dc6
 
 
 
 
 
 
 
 
173f164
2ca0dc6
 
173f164
 
 
 
 
 
 
2ca0dc6
 
 
 
 
 
173f164
 
 
 
2ca0dc6
 
 
 
 
 
 
 
 
 
173f164
2ca0dc6
173f164
 
c12d620
 
 
 
173f164
 
 
c12d620
 
 
 
173f164
63f2b2a
2ca0dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173f164
63f2b2a
 
 
 
 
 
 
 
 
 
 
 
2ca0dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63f2b2a
2ca0dc6
 
 
 
 
 
 
63f2b2a
2ca0dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173f164
2ca0dc6
173f164
 
2ca0dc6
 
 
 
 
 
 
 
 
 
 
 
 
173f164
 
 
2ca0dc6
 
 
 
 
 
 
 
 
 
 
 
 
173f164
63f2b2a
2ca0dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173f164
 
2ca0dc6
 
 
d28383a
 
 
 
 
 
 
 
2ca0dc6
 
 
d28383a
173f164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348

// 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 = '<div class="animate-spin rounded-full h-5 w-5 border-b-2 border-white mx-auto"></div>';
    }
  }

  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 = '<div class="text-center py-12"><p class="text-gray-600 dark:text-gray-400">No properties found matching your criteria.</p></div>';
      return;
    }

    propertiesGrid.innerHTML = properties.map(property => `
      <div class="property-card bg-white dark:bg-gray-800 rounded-2xl overflow-hidden">
        <div class="h-48 bg-gradient-to-r from-primary-500 to-secondary-500"></div>
        <div class="p-6">
          <h3 class="text-xl font-semibold text-gray-900 dark:text-white mb-2">${property.title}</h3>
          <p class="text-gray-600 dark:text-gray-400 mb-4">${property.bedrooms} Beds • ${property.bathrooms} Baths • ${property.squareFeet} sqft</p>
          <div class="flex justify-between items-center">
            <span class="text-2xl font-bold text-primary-600">${property.price.toLocaleString()}</span>
            <a href="/property-details.html?id=${property._id}" class="bg-primary-500 hover:bg-primary-600 text-white px-6 py-2 rounded-lg font-semibold transition-colors hover:scale-105">View Details</a>
          </div>
        </div>
      </div>
    `).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 };
}