-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1409 lines (1204 loc) · 45.1 KB
/
script.js
File metadata and controls
1409 lines (1204 loc) · 45.1 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Weather App JavaScript
// API Configuration
const API_CONFIG = {
geocoding: 'https://geocoding-api.open-meteo.com/v1/search',
weather: 'https://api.open-meteo.com/v1/forecast'
};
// Weather code mappings for icons
const WEATHER_CODES = {
0: { description: 'Clear sky', icon: 'sunny' },
1: { description: 'Mainly clear', icon: 'sunny' },
2: { description: 'Partly cloudy', icon: 'partly-cloudy' },
3: { description: 'Overcast', icon: 'overcast' },
45: { description: 'Fog', icon: 'fog' },
48: { description: 'Depositing rime fog', icon: 'fog' },
51: { description: 'Light drizzle', icon: 'drizzle' },
53: { description: 'Moderate drizzle', icon: 'drizzle' },
55: { description: 'Dense drizzle', icon: 'drizzle' },
56: { description: 'Light freezing drizzle', icon: 'drizzle' },
57: { description: 'Dense freezing drizzle', icon: 'drizzle' },
61: { description: 'Slight rain', icon: 'rain' },
63: { description: 'Moderate rain', icon: 'rain' },
65: { description: 'Heavy rain', icon: 'rain' },
66: { description: 'Light freezing rain', icon: 'rain' },
67: { description: 'Heavy freezing rain', icon: 'rain' },
71: { description: 'Slight snow fall', icon: 'snow' },
73: { description: 'Moderate snow fall', icon: 'snow' },
75: { description: 'Heavy snow fall', icon: 'snow' },
77: { description: 'Snow grains', icon: 'snow' },
80: { description: 'Slight rain showers', icon: 'rain' },
81: { description: 'Moderate rain showers', icon: 'rain' },
82: { description: 'Violent rain showers', icon: 'rain' },
85: { description: 'Slight snow showers', icon: 'snow' },
86: { description: 'Heavy snow showers', icon: 'snow' },
95: { description: 'Thunderstorm', icon: 'storm' },
96: { description: 'Thunderstorm with slight hail', icon: 'storm' },
99: { description: 'Thunderstorm with heavy hail', icon: 'storm' }
};
// Application State
const appState = {
currentLocation: null,
weatherData: null,
units: {
temperature: 'celsius',
windSpeed: 'kmh',
precipitation: 'mm'
},
theme: 'dark',
favorites: JSON.parse(localStorage.getItem('weatherAppFavorites') || '[]'),
selectedDay: 0 // For hourly forecast day selection
};
// DOM Elements (will be populated when DOM is loaded)
const elements = {};
// Utility Functions
const utils = {
// Format temperature based on current units
formatTemperature(temp) {
if (appState.units.temperature === 'fahrenheit') {
return `${Math.round(temp * 9/5 + 32)}°F`;
}
return `${Math.round(temp)}°C`;
},
// Format wind speed based on current units
formatWindSpeed(speed) {
if (appState.units.windSpeed === 'mph') {
return `${Math.round(speed * 0.621371)} mph`;
}
return `${Math.round(speed)} km/h`;
},
// Format precipitation based on current units
formatPrecipitation(amount) {
if (appState.units.precipitation === 'inches') {
return `${(amount * 0.0393701).toFixed(1)} in`;
}
return `${amount.toFixed(1)} mm`;
},
// Get weather icon path
getWeatherIcon(weatherCode) {
const weather = WEATHER_CODES[weatherCode] || WEATHER_CODES[0];
return `./assets/images/icon-${weather.icon}.webp`;
},
// Get weather description
getWeatherDescription(weatherCode) {
const weather = WEATHER_CODES[weatherCode] || WEATHER_CODES[0];
return weather.description;
},
// Format date
formatDate(dateString) {
const date = new Date(dateString);
return date.toLocaleDateString('en-US', {
weekday: 'short',
month: 'short',
day: 'numeric'
});
},
// Format time
formatTime(dateString) {
const date = new Date(dateString);
return date.toLocaleTimeString('en-US', {
hour: 'numeric',
hour12: true
});
},
// Debounce function for search
debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
},
// Show loading state
showLoading(element) {
element.classList.add('loading');
},
// Hide loading state
hideLoading(element) {
element.classList.remove('loading');
},
// Show error message
showError(message) {
// TODO: Implement error display
console.error(message);
}
};
// API Functions
const api = {
// Search for locations
async searchLocations(query) {
try {
const response = await fetch(
`${API_CONFIG.geocoding}?name=${encodeURIComponent(query)}&count=5&language=en&format=json`
);
if (!response.ok) {
throw new Error('Failed to search locations');
}
const data = await response.json();
return data.results || [];
} catch (error) {
utils.showError('Failed to search locations');
return [];
}
},
// Get weather data
async getWeatherData(latitude, longitude, retryCount = 0) {
console.log('API: Fetching weather data for:', latitude, longitude, 'Retry:', retryCount);
try {
const params = new URLSearchParams({
latitude: latitude,
longitude: longitude,
hourly: [
'temperature_2m',
'relative_humidity_2m',
'apparent_temperature',
'precipitation_probability',
'precipitation',
'weather_code',
'surface_pressure',
'wind_speed_10m',
'wind_direction_10m'
].join(','),
daily: [
'weather_code',
'temperature_2m_max',
'temperature_2m_min',
'sunrise',
'sunset',
'uv_index_max',
'precipitation_sum',
'wind_speed_10m_max'
].join(','),
current: [
'temperature_2m',
'relative_humidity_2m',
'apparent_temperature',
'precipitation',
'weather_code',
'surface_pressure',
'wind_speed_10m',
'wind_direction_10m',
'visibility'
].join(','),
timezone: 'auto',
forecast_days: 7
});
const url = `${API_CONFIG.weather}?${params}`;
console.log('API: Making request to:', url);
// Add timeout to the fetch request
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
const response = await fetch(url, {
signal: controller.signal,
headers: {
'Accept': 'application/json',
}
});
clearTimeout(timeoutId);
if (!response.ok) {
console.error('API: Response not ok:', response.status, response.statusText);
throw new Error(`Failed to fetch weather data: ${response.status} ${response.statusText}`);
}
const data = await response.json();
console.log('API: Successfully received data');
return data;
} catch (error) {
console.error('API: Error fetching weather data:', error);
// Retry up to 2 times with exponential backoff
if (retryCount < 2) {
const delay = Math.pow(2, retryCount) * 1000; // 1s, 2s delays
console.log(`API: Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
return this.getWeatherData(latitude, longitude, retryCount + 1);
}
utils.showError('Failed to fetch weather data');
return null;
}
}
};
// Theme Management
const theme = {
init() {
console.log('Initializing theme system...');
this.bindEvents();
const savedTheme = localStorage.getItem('weatherAppTheme');
const autoTheme = localStorage.getItem('weatherAppAutoTheme') !== 'false';
console.log('Saved theme:', savedTheme);
console.log('Auto theme enabled:', autoTheme);
if (autoTheme && !savedTheme) {
this.setAutoTheme();
} else {
const themeToUse = savedTheme || 'dark';
this.setTheme(themeToUse);
}
this.updateThemeIcon();
console.log('Theme system initialized with theme:', appState.theme);
},
bindEvents() {
const themeToggle = document.getElementById('themeToggle');
if (themeToggle) {
themeToggle.addEventListener('click', () => {
this.toggle();
});
// Add keyboard support
themeToggle.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
this.toggle();
}
});
}
// Add keyboard shortcut (Ctrl/Cmd + Shift + T)
document.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'T') {
e.preventDefault();
this.toggle();
}
});
},
setTheme(themeName) {
console.log('Setting theme to:', themeName);
appState.theme = themeName;
document.documentElement.setAttribute('data-theme', themeName);
localStorage.setItem('weatherAppTheme', themeName);
localStorage.setItem('weatherAppAutoTheme', 'false');
this.updateThemeIcon();
// Dispatch custom event for theme change
window.dispatchEvent(new CustomEvent('themeChanged', {
detail: { theme: themeName }
}));
},
setAutoTheme() {
const hour = new Date().getHours();
const isNight = hour < 6 || hour >= 18;
const autoTheme = isNight ? 'dark' : 'light';
appState.theme = autoTheme;
document.documentElement.setAttribute('data-theme', autoTheme);
localStorage.setItem('weatherAppAutoTheme', 'true');
this.updateThemeIcon();
},
toggle() {
const themeToggle = document.getElementById('themeToggle');
// Add visual feedback
if (themeToggle) {
themeToggle.style.transform = 'scale(0.95)';
setTimeout(() => {
themeToggle.style.transform = 'scale(1)';
}, 150);
}
const newTheme = appState.theme === 'dark' ? 'light' : 'dark';
this.setTheme(newTheme);
// Log theme change for debugging
console.log(`Theme switched to: ${newTheme}`);
},
updateThemeIcon() {
const themeIcon = document.getElementById('themeIcon');
const themeToggle = document.getElementById('themeToggle');
if (themeIcon && themeToggle) {
// Add transition class for smooth icon change
themeIcon.style.transition = 'opacity 0.2s ease-in-out';
if (appState.theme === 'dark') {
themeIcon.src = './assets/images/icon-sunny.webp';
themeIcon.alt = 'Switch to light mode';
themeToggle.setAttribute('aria-label', 'Switch to light mode');
themeToggle.setAttribute('title', 'Switch to light mode');
} else {
themeIcon.src = './assets/images/icon-overcast.webp';
themeIcon.alt = 'Switch to dark mode';
themeToggle.setAttribute('aria-label', 'Switch to dark mode');
themeToggle.setAttribute('title', 'Switch to dark mode');
}
}
}
};
// Animations and Visual Effects
const animations = {
init() {
this.app = document.getElementById('app');
this.particlesContainer = document.getElementById('weatherParticles');
},
setWeatherBackground(weatherCode) {
if (!this.app) return;
// Remove existing weather classes
this.app.classList.remove('weather-clear', 'weather-cloudy', 'weather-rainy', 'weather-snowy', 'weather-stormy');
// Add appropriate weather class based on weather code
if (weatherCode === 0 || weatherCode === 1) {
this.app.classList.add('weather-clear');
this.createParticles('clear');
} else if (weatherCode === 2 || weatherCode === 3) {
this.app.classList.add('weather-cloudy');
this.createParticles('cloudy');
} else if (weatherCode >= 51 && weatherCode <= 67) {
this.app.classList.add('weather-rainy');
this.createParticles('rain');
} else if (weatherCode >= 71 && weatherCode <= 86) {
this.app.classList.add('weather-snowy');
this.createParticles('snow');
} else if (weatherCode >= 95) {
this.app.classList.add('weather-stormy');
this.createParticles('storm');
} else {
this.app.classList.add('weather-cloudy');
this.createParticles('cloudy');
}
},
createParticles(weatherType) {
if (!this.particlesContainer) return;
// Clear existing particles
this.particlesContainer.innerHTML = '';
let particleCount = 0;
let particleClass = '';
switch (weatherType) {
case 'rain':
particleCount = 50;
particleClass = 'rain';
break;
case 'snow':
particleCount = 30;
particleClass = 'snow';
break;
case 'clear':
particleCount = 10;
particleClass = 'clear';
break;
case 'storm':
particleCount = 60;
particleClass = 'rain';
break;
default:
particleCount = 5;
particleClass = 'clear';
}
for (let i = 0; i < particleCount; i++) {
const particle = document.createElement('div');
particle.className = `particle ${particleClass}`;
// Random positioning
particle.style.left = Math.random() * 100 + '%';
particle.style.animationDelay = Math.random() * 3 + 's';
particle.style.animationDuration = (Math.random() * 2 + 1) + 's';
if (particleClass === 'clear') {
particle.style.width = Math.random() * 4 + 2 + 'px';
particle.style.height = particle.style.width;
}
this.particlesContainer.appendChild(particle);
}
},
animateValue(element, start, end, duration = 1000) {
const startTime = performance.now();
const startValue = parseFloat(start) || 0;
const endValue = parseFloat(end) || 0;
const difference = endValue - startValue;
const animate = (currentTime) => {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
// Easing function (ease-out)
const easeOut = 1 - Math.pow(1 - progress, 3);
const currentValue = startValue + (difference * easeOut);
if (element.textContent.includes('°')) {
element.textContent = Math.round(currentValue) + '°';
} else if (element.textContent.includes('%')) {
element.textContent = Math.round(currentValue) + '%';
} else {
element.textContent = Math.round(currentValue);
}
if (progress < 1) {
requestAnimationFrame(animate);
}
};
requestAnimationFrame(animate);
}
};
// Favorites Management
const favorites = {
init() {
this.bindEvents();
this.updateUI();
},
bindEvents() {
// Favorite button in current weather
const favoriteButton = document.getElementById('favoriteButton');
if (favoriteButton) {
favoriteButton.addEventListener('click', () => {
this.toggleCurrentLocation();
});
}
// Favorites dropdown
const favoritesButton = document.getElementById('favoritesButton');
const favoritesMenu = document.getElementById('favoritesMenu');
if (favoritesButton && favoritesMenu) {
favoritesButton.addEventListener('click', () => {
const isOpen = favoritesMenu.classList.contains('active');
if (isOpen) {
favoritesMenu.classList.remove('active');
favoritesButton.setAttribute('aria-expanded', 'false');
} else {
favoritesMenu.classList.add('active');
favoritesButton.setAttribute('aria-expanded', 'true');
this.updateFavoritesList();
}
});
// Close favorites menu when clicking outside
document.addEventListener('click', (e) => {
if (!favoritesButton.contains(e.target) && !favoritesMenu.contains(e.target)) {
favoritesMenu.classList.remove('active');
favoritesButton.setAttribute('aria-expanded', 'false');
}
});
}
},
toggleCurrentLocation() {
if (!appState.currentLocation) return;
const favoriteButton = document.getElementById('favoriteButton');
if (this.isFavorite(appState.currentLocation)) {
this.remove(appState.currentLocation);
favoriteButton.classList.remove('active');
favoriteButton.setAttribute('aria-label', 'Add to favorites');
} else {
this.add(appState.currentLocation);
favoriteButton.classList.add('active');
favoriteButton.setAttribute('aria-label', 'Remove from favorites');
}
},
add(location) {
const favorite = {
id: Date.now(),
name: location.name,
country: location.country,
latitude: location.latitude,
longitude: location.longitude
};
appState.favorites.push(favorite);
this.save();
this.updateUI();
},
remove(location) {
appState.favorites = appState.favorites.filter(fav =>
!(fav.latitude === location.latitude && fav.longitude === location.longitude)
);
this.save();
this.updateUI();
},
removeById(id) {
appState.favorites = appState.favorites.filter(fav => fav.id !== id);
this.save();
this.updateUI();
},
save() {
localStorage.setItem('weatherAppFavorites', JSON.stringify(appState.favorites));
},
isFavorite(location) {
return appState.favorites.some(fav =>
fav.latitude === location.latitude && fav.longitude === location.longitude
);
},
updateUI() {
// Update favorite button state
const favoriteButton = document.getElementById('favoriteButton');
if (favoriteButton && appState.currentLocation) {
if (this.isFavorite(appState.currentLocation)) {
favoriteButton.classList.add('active');
favoriteButton.setAttribute('aria-label', 'Remove from favorites');
} else {
favoriteButton.classList.remove('active');
favoriteButton.setAttribute('aria-label', 'Add to favorites');
}
}
},
updateFavoritesList() {
const favoritesList = document.getElementById('favoritesList');
const noFavorites = document.getElementById('noFavorites');
if (!favoritesList) return;
if (appState.favorites.length === 0) {
favoritesList.innerHTML = `
<div class="no-favorites">
<p>No saved locations yet</p>
<p class="text-small">Add locations to your favorites for quick access</p>
</div>
`;
} else {
const favoritesHTML = appState.favorites.map(favorite => `
<div class="favorite-item" data-favorite-id="${favorite.id}">
<div class="favorite-info">
<div class="favorite-name">${favorite.name}</div>
<div class="favorite-country">${favorite.country}</div>
</div>
<button class="favorite-remove" data-favorite-id="${favorite.id}" aria-label="Remove ${favorite.name} from favorites">
×
</button>
</div>
`).join('');
favoritesList.innerHTML = favoritesHTML;
// Add event listeners
favoritesList.querySelectorAll('.favorite-item').forEach(item => {
item.addEventListener('click', (e) => {
if (e.target.classList.contains('favorite-remove')) return;
const favoriteId = parseInt(item.dataset.favoriteId);
const favorite = appState.favorites.find(fav => fav.id === favoriteId);
if (favorite) {
appState.currentLocation = favorite;
weather.loadWeatherData(favorite.latitude, favorite.longitude);
// Close favorites menu
const favoritesMenu = document.getElementById('favoritesMenu');
const favoritesButton = document.getElementById('favoritesButton');
if (favoritesMenu && favoritesButton) {
favoritesMenu.classList.remove('active');
favoritesButton.setAttribute('aria-expanded', 'false');
}
}
});
});
favoritesList.querySelectorAll('.favorite-remove').forEach(button => {
button.addEventListener('click', (e) => {
e.stopPropagation();
const favoriteId = parseInt(button.dataset.favoriteId);
this.removeById(favoriteId);
});
});
}
}
};
// Geolocation
const geolocation = {
async getCurrentPosition() {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error('Geolocation is not supported'));
return;
}
navigator.geolocation.getCurrentPosition(
position => resolve(position),
error => reject(error),
{ timeout: 10000, enableHighAccuracy: true }
);
});
},
async loadCurrentLocationWeather() {
console.log('Attempting to get current location...');
try {
const position = await this.getCurrentPosition();
const { latitude, longitude } = position.coords;
console.log('Got current position:', latitude, longitude);
// Get location name from reverse geocoding (simplified)
appState.currentLocation = {
name: 'Current Location',
latitude,
longitude
};
await weather.loadWeatherData(latitude, longitude);
} catch (error) {
console.log('Could not get current location:', error.message);
// Provide more specific error handling
if (error.code === 1) {
console.log('Geolocation permission denied, using default location');
} else if (error.code === 2) {
console.log('Geolocation position unavailable, using default location');
} else if (error.code === 3) {
console.log('Geolocation timeout, using default location');
}
// Fallback to default location (Berlin)
console.log('Falling back to default location...');
await this.loadDefaultLocation();
}
},
async loadDefaultLocation() {
console.log('Loading default location (Berlin)...');
appState.currentLocation = {
name: 'Berlin',
country: 'Germany',
latitude: 52.52437,
longitude: 13.41053
};
try {
await weather.loadWeatherData(52.52437, 13.41053);
} catch (error) {
console.error('Failed to load default location weather:', error);
// Show sample data for demonstration purposes
console.log('Showing sample data for demonstration...');
weather.showSampleData();
}
}
};
// Search functionality
const search = {
init() {
elements.searchInput = document.getElementById('searchInput');
elements.searchButton = document.getElementById('searchButton');
elements.searchResults = document.getElementById('searchResults');
if (!elements.searchInput || !elements.searchButton || !elements.searchResults) {
console.error('Search elements not found');
return;
}
// Debounced search function
const debouncedSearch = utils.debounce(this.performSearch.bind(this), 300);
// Event listeners
elements.searchInput.addEventListener('input', (e) => {
const query = e.target.value.trim();
if (query.length >= 2) {
debouncedSearch(query);
} else {
this.hideResults();
}
});
elements.searchButton.addEventListener('click', () => {
const query = elements.searchInput.value.trim();
if (query) {
this.performSearch(query);
}
});
elements.searchInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
const query = elements.searchInput.value.trim();
if (query) {
this.performSearch(query);
}
} else if (e.key === 'Escape') {
this.hideResults();
}
});
// Hide results when clicking outside
document.addEventListener('click', (e) => {
if (!elements.searchInput.contains(e.target) && !elements.searchResults.contains(e.target)) {
this.hideResults();
}
});
// Handle keyboard navigation in search results
elements.searchInput.addEventListener('keydown', (e) => {
const results = elements.searchResults.querySelectorAll('.search-result-item');
const activeResult = elements.searchResults.querySelector('.search-result-item.active');
let currentIndex = Array.from(results).indexOf(activeResult);
if (e.key === 'ArrowDown') {
e.preventDefault();
currentIndex = Math.min(currentIndex + 1, results.length - 1);
this.highlightResult(results, currentIndex);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
currentIndex = Math.max(currentIndex - 1, 0);
this.highlightResult(results, currentIndex);
} else if (e.key === 'Enter' && activeResult) {
e.preventDefault();
activeResult.click();
}
});
},
async performSearch(query) {
try {
utils.showLoading(elements.searchButton);
const locations = await api.searchLocations(query);
this.displayResults(locations);
} catch (error) {
console.error('Search failed:', error);
this.showSearchError();
} finally {
utils.hideLoading(elements.searchButton);
}
},
displayResults(locations) {
if (!locations || locations.length === 0) {
this.showNoResults();
return;
}
const resultsHTML = locations.map(location => `
<div class="search-result-item" data-location='${JSON.stringify(location)}'>
<div class="search-result-name">${location.name}</div>
<div class="search-result-details">
${location.admin1 ? location.admin1 + ', ' : ''}${location.country}
</div>
</div>
`).join('');
elements.searchResults.innerHTML = resultsHTML;
this.showResults();
// Add click listeners to results
elements.searchResults.querySelectorAll('.search-result-item').forEach(item => {
item.addEventListener('click', () => {
const location = JSON.parse(item.dataset.location);
this.selectLocation(location);
});
});
},
selectLocation(location) {
appState.currentLocation = location;
elements.searchInput.value = `${location.name}, ${location.country}`;
this.hideResults();
// Load weather for selected location
weather.loadWeatherData(location.latitude, location.longitude);
},
showResults() {
elements.searchResults.classList.add('active');
},
hideResults() {
elements.searchResults.classList.remove('active');
},
showNoResults() {
elements.searchResults.innerHTML = `
<div class="search-result-item">
<div class="search-result-name">No results found</div>
<div class="search-result-details">Try a different search term</div>
</div>
`;
this.showResults();
},
showSearchError() {
elements.searchResults.innerHTML = `
<div class="search-result-item">
<div class="search-result-name">Search failed</div>
<div class="search-result-details">Please try again</div>
</div>
`;
this.showResults();
},
highlightResult(results, index) {
results.forEach((result, i) => {
if (i === index) {
result.classList.add('active');
result.scrollIntoView({ block: 'nearest' });
} else {
result.classList.remove('active');
}
});
}
};
// Weather data management
const weather = {
async loadWeatherData(latitude, longitude) {
console.log('Loading weather data for:', latitude, longitude);
try {
this.showLoading();
const data = await api.getWeatherData(latitude, longitude);
console.log('Weather data received:', data);
if (data) {
appState.weatherData = data;
this.displayWeatherData(data);
this.showWeatherData();
console.log('Weather data displayed successfully');
} else {
console.log('No weather data received');
this.showError('Unable to load weather data. Please check your internet connection and try again.');
}
} catch (error) {
console.error('Weather loading failed:', error);
this.showError('Unable to connect to weather service. Please check your internet connection and try again.');
}
},
displayWeatherData(data) {
// Update current weather
this.updateCurrentWeather(data);
// Update metrics
this.updateMetrics(data);
// Update forecasts
this.updateDailyForecast(data);
this.updateHourlyForecast(data);
// Update favorites UI
favorites.updateUI();
// Update weather animations
if (data.current && data.current.weather_code !== undefined) {
animations.setWeatherBackground(data.current.weather_code);
}
},
updateCurrentWeather(data) {
const current = data.current;
const location = appState.currentLocation;
if (elements.currentLocation) {
elements.currentLocation.textContent = location ?
`${location.name}, ${location.country}` : 'Current Location';
}
if (elements.currentDate) {
elements.currentDate.textContent = new Date().toLocaleDateString('en-US', {
weekday: 'long',
month: 'long',
day: 'numeric',
year: 'numeric'
});
}
if (elements.currentTemp) {
elements.currentTemp.textContent = utils.formatTemperature(current.temperature_2m);
}
if (elements.currentWeatherIcon) {
elements.currentWeatherIcon.src = utils.getWeatherIcon(current.weather_code);
elements.currentWeatherIcon.alt = utils.getWeatherDescription(current.weather_code);
}
if (elements.currentDescription) {
elements.currentDescription.textContent = utils.getWeatherDescription(current.weather_code);
}
},
updateMetrics(data) {
const current = data.current;
const daily = data.daily;
if (elements.feelsLike) {
elements.feelsLike.textContent = utils.formatTemperature(current.apparent_temperature);
}
if (elements.humidity) {
elements.humidity.textContent = `${Math.round(current.relative_humidity_2m)}%`;
}
if (elements.windSpeed) {
elements.windSpeed.textContent = utils.formatWindSpeed(current.wind_speed_10m);
}
if (elements.precipitation) {
elements.precipitation.textContent = utils.formatPrecipitation(current.precipitation || 0);
}
// Additional metrics
if (elements.uvIndex && daily && daily.uv_index_max) {
elements.uvIndex.textContent = Math.round(daily.uv_index_max[0]);
}
if (elements.visibility && current.visibility) {
const visibilityKm = (current.visibility / 1000).toFixed(1);
elements.visibility.textContent = `${visibilityKm} km`;
}
if (elements.pressure) {
elements.pressure.textContent = `${Math.round(current.surface_pressure)} hPa`;
}
// Sun times
if (elements.sunrise && elements.sunset && daily) {
const sunrise = new Date(daily.sunrise[0]);
const sunset = new Date(daily.sunset[0]);
elements.sunrise.textContent = sunrise.toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',