-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
844 lines (767 loc) · 37.4 KB
/
index.html
File metadata and controls
844 lines (767 loc) · 37.4 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CosmoGuide AI</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
.chat-container {
transition: transform 0.3s ease;
}
.chat-hidden {
transform: translateY(calc(100% - 60px));
}
.chat-visible {
transform: translateY(0);
}
.loading-animation {
animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: .5; }
}
.card {
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.3);
}
.gradient-bg {
background: linear-gradient(180deg, rgba(30, 41, 59, 0) 0%, rgba(30, 41, 59, 0.9) 100%);
}
/* ISS Globe Styles */
.iss-globe-container {
position: relative;
width: 100%;
height: 300px;
}
.iss-globe {
width: 100%;
height: 100%;
background-image: url('https://neo.gsfc.nasa.gov/archive/bluemarble/bmng/world_8km/world.topo.bathy.200407.3x5400x2700.png');
background-size: cover;
border-radius: 50%;
position: relative;
box-shadow: 0 0 50px rgba(0,0,255,0.5);
}
.iss-marker {
position: absolute;
width: 15px;
height: 15px;
background-color: red;
border-radius: 50%;
transform: translate(-50%, -50%);
box-shadow: 0 0 10px red;
transition: all 0.5s ease;
}
</style>
</head>
<body class="min-h-screen bg-gradient-to-b from-slate-900 to-slate-800">
<!-- Navigation -->
<nav class="border-b border-slate-700 bg-slate-900/95 backdrop-blur-sm sticky top-0 z-50">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16 items-center">
<div class="flex items-center space-x-3">
<div class="bg-blue-500/10 p-2 rounded-lg">
<i class="fas fa-rocket h-8 w-8 text-blue-500"></i>
</div>
<span class="ml-2 text-xl font-bold text-white">CosmoGuide AI</span>
</div>
<div class="flex gap-4" id="agent-selector">
<!-- Agent buttons will be inserted here -->
</div>
</div>
</div>
</nav>
<!-- Loading State -->
<div id="loading-state" class="min-h-screen flex items-center justify-center px-4">
<div class="text-center space-y-4">
<div class="relative">
<i class="fas fa-circle-notch fa-spin h-12 w-12 text-blue-500 mx-auto"></i>
<div class="absolute inset-0 bg-gradient-radial from-blue-500/20 to-transparent blur-xl"></div>
</div>
<div class="space-y-2">
<h3 class="text-xl font-medium text-white">Loading Space Data</h3>
<p class="text-slate-400" id="loading-status">Connecting to NASA APIs...</p>
</div>
</div>
</div>
<!-- Error State -->
<div id="error-state" class="min-h-screen flex items-center justify-center hidden px-4">
<div class="bg-red-500/10 border border-red-500/50 text-white p-6 rounded-lg max-w-md">
<div class="flex items-center gap-3 mb-3">
<i class="fas fa-triangle-exclamation h-6 w-6 text-red-500"></i>
<h3 class="text-lg font-semibold">Error Loading Data</h3>
</div>
<p id="error-message" class="text-slate-300"></p>
<button onclick="initializeApp()" class="mt-4 px-4 py-2 bg-red-500 hover:bg-red-600 rounded-lg transition-colors">
Try Again
</button>
</div>
</div>
<!-- Main Content -->
<main id="main-content" class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 hidden">
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="data-grid">
<!-- Data cards will be inserted here -->
</div>
</main>
<!-- Chat Interface -->
<div id="chat-container" class="fixed bottom-0 right-0 w-96 chat-container chat-hidden">
<div class="bg-slate-800/95 backdrop-blur-sm border-l border-t border-slate-700 rounded-tl-lg shadow-2xl">
<div id="chat-header" class="p-4 flex items-center justify-between cursor-pointer hover:bg-slate-700/50 transition-colors">
<div class="flex items-center gap-2">
<i class="fas fa-message h-5 w-5 text-blue-500"></i>
<span class="font-medium text-white">CosmoGuide AI</span>
</div>
<div class="text-slate-400 text-sm" id="agent-status"></div>
</div>
<div id="chat-messages" class="h-96 overflow-y-auto p-4 space-y-4">
<!-- Messages will be inserted here -->
</div>
<div class="p-4 border-t border-slate-700">
<div class="flex items-center gap-2">
<input
type="text"
id="chat-input"
placeholder="Ask about space data..."
class="flex-1 bg-slate-700 text-white rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 placeholder-slate-400"
>
<button
id="send-message"
class="p-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700 transition-colors"
>
<i class="fas fa-paper-plane h-5 w-5"></i>
</button>
</div>
</div>
</div>
</div>
<script>
// State management
const state = {
messages: [],
activeAgent: 'explorer',
isChatOpen: false,
nasaData: {
apod: null,
asteroids: [],
marsWeather: null,
issPosition: null,
spaceWeather: null,
marsPhotos: [],
exoplanets: []
}
};
// Agent configurations
const agents = {
explorer: {
name: 'Explorer',
icon: 'fa-rocket',
description: 'Discovers and explains new space phenomena'
},
analyst: {
name: 'Analyst',
icon: 'fa-brain',
description: 'Analyzes space data and predicts trends'
},
teacher: {
name: 'Teacher',
icon: 'fa-star',
description: 'Educates about space concepts'
}
};
// Function to update loading status
function updateLoadingStatus(message) {
document.getElementById('loading-status').textContent = message;
}
// Enhanced error handling for fetch requests
async function safeFetch(url, options = {}) {
try {
console.log(`Fetching: ${url}`);
updateLoadingStatus(`Fetching data from ${url.split('/').pop()}...`);
const response = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
...options.headers,
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(`Success fetching ${url}:`, data);
return data;
} catch (error) {
console.error(`Error fetching ${url}:`, error);
throw error;
}
}
// Fetch all NASA data with improved error handling
async function fetchAllData() {
try {
updateLoadingStatus('Starting to fetch space data...');
const endpoints = [
{ key: 'apod', url: '/api/nasa/apod' },
{ key: 'asteroids', url: '/api/nasa/asteroids' },
{ key: 'issPosition', url: '/api/nasa/iss' },
{ key: 'spaceWeather', url: '/api/nasa/space-weather' },
{ key: 'marsPhotos', url: '/api/nasa/mars-photos' },
{ key: 'exoplanets', url: '/api/nasa/exoplanets' }
];
const results = await Promise.allSettled(
endpoints.map(endpoint => safeFetch(endpoint.url))
);
let hasAnyData = false;
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
state.nasaData[endpoints[index].key] = result.value;
hasAnyData = true;
} else {
console.error(`Failed to fetch ${endpoints[index].key}:`, result.reason);
}
});
if (!hasAnyData) {
throw new Error('Unable to fetch any space data');
}
document.getElementById('loading-state').classList.add('hidden');
document.getElementById('main-content').classList.remove('hidden');
updateUI();
} catch (error) {
console.error('Data Fetching Error:', error);
showError(`Failed to load space data: ${error.message}`);
}
}
// Update UI function
function updateUI() {
const grid = document.getElementById('data-grid');
grid.innerHTML = '';
// Add cards only if we have data
if (state.nasaData.apod) {
grid.innerHTML += createAPODCard(state.nasaData.apod);
}
if (state.nasaData.asteroids?.length) {
grid.innerHTML += createAsteroidsCard(state.nasaData.asteroids);
}
if (state.nasaData.issPosition) {
grid.innerHTML += createISSCard(state.nasaData.issPosition);
}
if (state.nasaData.spaceWeather?.alerts?.length) {
grid.innerHTML += createSpaceWeatherCard(state.nasaData.spaceWeather);
}
if (state.nasaData.marsPhotos?.photos?.length || Array.isArray(state.nasaData.marsPhotos)) {
grid.innerHTML += createMarsPhotosCard(state.nasaData.marsPhotos);
}
}
// Card creation functions
function createAPODCard(apod) {
return `
<div class="lg:col-span-2 card">
<div class="bg-slate-800/50 backdrop-blur-sm rounded-lg border border-slate-700 overflow-hidden">
<div class="p-4 border-b border-slate-700">
<div class="flex items-center gap-2">
<i class="fas fa-star h-5 w-5 text-blue-500"></i>
<h2 class="text-lg font-semibold text-white">Astronomy Picture of the Day</h2>
</div>
</div>
<div class="p-4">
<div class="relative">
<img src="${apod.url}"
alt="${apod.title}"
class="w-full h-64 object-cover rounded-lg">
<div class="absolute bottom-0 left-0 right-0 p-4 gradient-bg rounded-b-lg">
<h3 class="text-white font-medium">${apod.title}</h3>
</div>
</div>
<p class="text-slate-300 text-sm mt-4">${apod.explanation}</p>
</div>
</div>
</div>
`;
}
function createAsteroidsCard(asteroids) {
return `
<div class="card">
<div class="bg-slate-800/50 backdrop-blur-sm rounded-lg border border-slate-700">
<div class="p-4 border-b border-slate-700">
<div class="flex items-center gap-2">
<i class="fas fa-triangle-exclamation h-5 w-5 text-blue-500"></i>
<h2 class="text-lg font-semibold text-white">Near Earth Objects</h2>
</div>
</div>
<div class="p-4 space-y-4">
${asteroids.slice(0, 5).map(asteroid => `
<div class="p-4 rounded-lg bg-slate-700/50 backdrop-blur-sm hover:bg-slate-700 transition-colors">
<div class="font-medium text-blue-400">${asteroid.name}</div>
<div class="grid grid-cols-2 gap-2 mt-2">
<div>
<div class="text-xs text-slate-400">Diameter</div>
<div class="text-sm text-white">${Math.round(asteroid.estimated_diameter.kilometers.estimated_diameter_max)} km</div>
</div>
<div>
<div class="text-xs text-slate-400">Miss Distance</div>
<div class="text-sm text-white">${Math.round(asteroid.close_approach_data[0].miss_distance.kilometers).toLocaleString()} km</div>
</div>
</div>
<div class="mt-2">
<span class="text-sm px-2 py-1 rounded-full ${asteroid.is_potentially_hazardous_asteroid ? 'bg-red-500/20 text-red-400' : 'bg-green-500/20 text-green-400'}">
${asteroid.is_potentially_hazardous_asteroid ? '⚠️ Potentially Hazardous' : '✓ Not Hazardous'}
</span>
</div>
</div>
`).join('')}
</div>
</div>
</div>
`;
}
function createISSCard(issPosition) {
return `
<div class="card">
<div class="bg-slate-800/50 backdrop-blur-sm rounded-lg border border-slate-700">
<div class="p-4 border-b border-slate-700">
<div class="flex items-center gap-2">
<i class="fas fa-satellite h-5 w-5 text-blue-500"></i>
<h2 class="text-lg font-semibold text-white">ISS Live Location</h2>
</div>
</div>
<div class="p-4">
<div class="iss-globe-container">
<div class="iss-globe">
<div class="iss-marker"></div>
</div>
</div>
<div class="grid grid-cols-2 gap-4 mt-4">
<div class="p-4 rounded-lg bg-slate-700/50 backdrop-blur-sm">
<div class="text-sm text-slate-400">Latitude</div>
<div class="text-2xl font-semibold text-white">${parseFloat(issPosition.iss_position.latitude).toFixed(2)}°</div>
</div>
<div class="p-4 rounded-lg bg-slate-700/50 backdrop-blur-sm">
<div class="text-sm text-slate-400">Longitude</div>
<div class="text-2xl font-semibold text-white">${parseFloat(issPosition.iss_position.longitude).toFixed(2)}°</div>
</div>
</div>
<div class="mt-4 text-center">
<div class="text-sm text-slate-400">Last Updated</div>
<div class="text-white">${new Date(issPosition.timestamp * 1000).toLocaleTimeString()}</div>
</div>
</div>
</div>
</div>
`;
}
function createSpaceWeatherCard(spaceWeather) {
return `
<div class="card">
<div class="bg-slate-800/50 backdrop-blur-sm rounded-lg border border-slate-700">
<div class="p-4 border-b border-slate-700">
<div class="flex items-center gap-2">
<i class="fas fa-sun h-5 w-5 text-blue-500"></i>
<h2 class="text-lg font-semibold text-white">Space Weather Alerts</h2>
</div>
</div>
<div class="p-4 space-y-4">
${spaceWeather.alerts.slice(0, 5).map(alert => `
<div class="p-4 rounded-lg bg-slate-700/50 backdrop-blur-sm">
<div class="flex items-center gap-2">
<div class="font-medium text-blue-400">${alert.type}</div>
<span class="px-2 py-0.5 rounded-full bg-blue-500/20 text-blue-400 text-xs">
${alert.severity}
</span>
</div>
<div class="text-sm text-slate-300 mt-2">${alert.message}</div>
<div class="text-xs text-slate-400 mt-1">
${new Date(alert.time).toLocaleString()}
</div>
</div>
`).join('')}
</div>
</div>
</div>
`;
}
function createMarsPhotosCard(marsPhotos) {
// Make sure we have photos data and it's in the correct format
const photos = Array.isArray(marsPhotos) ? marsData : marsPhotos?.photos || [];
if (!photos || photos.length === 0) {
return ''; // Return empty string if no photos
}
// Get a unique set of rovers
const uniqueRovers = [...new Set(photos.map(photo => photo.rover.name))];
const roverNames = uniqueRovers.join(', ');
return `
<div class="card">
<div class="bg-slate-800/50 backdrop-blur-sm rounded-lg border border-slate-700">
<div class="p-4 border-b border-slate-700">
<div class="flex items-center gap-2">
<i class="fas fa-camera h-5 w-5 text-blue-500"></i>
<h2 class="text-lg font-semibold text-white">Latest Mars Photos</h2>
</div>
<div class="text-sm text-slate-400 mt-1">
From ${roverNames} Rover
</div>
</div>
<div class="p-4">
<div class="grid grid-cols-2 gap-4">
${photos.slice(0, 4).map(photo => `
<div class="relative group">
<img src="${photo.img_src}"
alt="Mars - ${photo.camera.full_name}"
loading="lazy"
class="w-full h-32 object-cover rounded-lg"
onerror="this.src='/api/placeholder/400/320'">
<div class="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity rounded-lg">
<div class="absolute bottom-0 p-2 text-white">
<div class="text-xs font-medium">${photo.camera.full_name}</div>
<div class="text-xs opacity-75">
${new Date(photo.earth_date).toLocaleDateString()}
</div>
</div>
</div>
</div>
`).join('')}
</div>
</div>
</div>
</div>
`;
}
// function createExoplanetsCard(exoplanets) {
// return `
// <div class="card">
// <div class="bg-slate-800/50 backdrop-blur-sm rounded-lg border border-slate-700">
// <div class="p-4 border-b border-slate-700">
// <div class="flex items-center gap-2">
// <i class="fas fa-globe h-5 w-5 text-blue-500"></i>
// <h2 class="text-lg font-semibold text-white">Newly Discovered Exoplanets</h2>
// </div>
// </div>
// <div class="p-4 space-y-4">
// ${exoplanets.slice(0, 3).map(planet => `
// <div class="p-4 rounded-lg bg-slate-700/50 backdrop-blur-sm">
// <div class="font-medium text-blue-400">${planet.pl_name}</div>
// <div class="grid grid-cols-2 gap-2 mt-2">
// <div>
// <div class="text-xs text-slate-400">Distance (ly)</div>
// <div class="text-sm text-white">${planet.sy_dist?.toFixed(1) || 'Unknown'}</div>
// </div>
// <div>
// <div class="text-xs text-slate-400">Planet Type</div>
// <div class="text-sm text-white">${planet.pl_type || 'Unknown'}</div>
// </div>
// <div>
// <div class="text-xs text-slate-400">Discovery Method</div>
// <div class="text-sm text-white">${planet.discoverymethod}</div>
// </div>
// <div>
// <div class="text-xs text-slate-400">Year Discovered</div>
// <div class="text-sm text-white">${planet.disc_year}</div>
// </div>
// </div>
// </div>
// `).join('')}
// </div>
// </div>
// </div>
// `;
// }
// Function to update ISS globe marker position
function updateISSGlobeMarker(latitude, longitude) {
const globe = document.querySelector('.iss-globe');
const marker = document.querySelector('.iss-marker');
if (!globe || !marker) return;
const globeWidth = globe.offsetWidth;
const globeHeight = globe.offsetHeight;
// Convert latitude and longitude to radians
const latRad = latitude * (Math.PI / 180);
const lonRad = longitude * (Math.PI / 180);
// Calculate x and y positions
const x = (lonRad + Math.PI) / (2 * Math.PI) * globeWidth;
const y = (Math.PI / 2 - latRad) / Math.PI * globeHeight;
// Update marker position
marker.style.left = `${x}px`;
marker.style.top = `${y}px`;
}
const originalUpdateUI = updateUI;
updateUI = function() {
originalUpdateUI();
// Update ISS globe marker if ISS position is available
if (state.nasaData.issPosition?.iss_position) {
const latitude = parseFloat(state.nasaData.issPosition.iss_position.latitude);
const longitude = parseFloat(state.nasaData.issPosition.iss_position.longitude);
// Use setTimeout to ensure DOM is updated before positioning marker
setTimeout(() => {
updateISSGlobeMarker(latitude, longitude);
}, 100);
}
};
// Enhanced chat initialization
async function initializeChat() {
try {
updateLoadingStatus('Initializing AI chat...');
// Prepare initial context with all available space data
const spaceContext = {
apod: state.nasaData.apod ? {
title: state.nasaData.apod.title,
explanation: state.nasaData.apod.explanation,
date: state.nasaData.apod.date
} : null,
asteroids: state.nasaData.asteroids ? state.nasaData.asteroids.map(asteroid => ({
name: asteroid.name,
diameter: Math.round(asteroid.estimated_diameter.kilometers.estimated_diameter_max),
hazardous: asteroid.is_potentially_hazardous_asteroid,
missDistance: Math.round(asteroid.close_approach_data[0].miss_distance.kilometers)
})) : [],
issPosition: state.nasaData.issPosition?.iss_position ? {
latitude: parseFloat(state.nasaData.issPosition.iss_position.latitude).toFixed(2),
longitude: parseFloat(state.nasaData.issPosition.iss_position.longitude).toFixed(2),
timestamp: new Date(state.nasaData.issPosition.timestamp * 1000).toISOString()
} : null,
spaceWeather: state.nasaData.spaceWeather?.alerts ? {
alerts: state.nasaData.spaceWeather.alerts.slice(0, 3).map(alert => ({
type: alert.type,
severity: alert.severity,
message: alert.message
}))
} : null,
marsPhotos: state.nasaData.marsPhotos?.photos ? {
count: state.nasaData.marsPhotos.photos.length,
rover: state.nasaData.marsPhotos.photos[0]?.rover.name || 'Unknown',
latestDate: state.nasaData.marsPhotos.photos[0]?.earth_date || 'Unknown'
} : null
};
const response = await safeFetch('/api/chat/initialize', {
method: 'POST',
body: JSON.stringify({
message: "Initialize chat session",
agent: state.activeAgent,
context: {
agentType: agents[state.activeAgent].description,
spaceData: spaceContext
}
})
});
if (response.response) {
state.messages = [{
type: 'bot',
content: response.response,
agent: state.activeAgent
}];
} else {
throw new Error('Invalid response format');
}
updateChatUI();
document.getElementById('agent-status').textContent = `${agents[state.activeAgent].name} Active`;
} catch (error) {
console.error('Chat Initialization Error:', error);
state.messages = [{
type: 'bot',
content: `Hello! I'm your ${agents[state.activeAgent].name}. I have access to real-time space data including today's astronomy picture, near-Earth objects, ISS location, space weather alerts, and Mars rover photos. How can I help you explore space today?`,
agent: state.activeAgent
}];
updateChatUI();
}
}
// Enhanced message handling
async function handleSendMessage() {
const input = document.getElementById('chat-input');
const message = input.value.trim();
if (!message) return;
state.messages.push({
type: 'user',
content: message
});
updateChatUI();
input.value = '';
// Show typing indicator
state.messages.push({
type: 'bot',
content: '<div class="flex items-center gap-2"><div class="animate-pulse">Thinking</div><div class="loading-dots">...</div></div>',
agent: state.activeAgent,
isLoading: true
});
updateChatUI();
try {
// Prepare current context with all space data
const spaceContext = {
apod: state.nasaData.apod ? {
title: state.nasaData.apod.title,
explanation: state.nasaData.apod.explanation,
date: state.nasaData.apod.date
} : null,
asteroids: state.nasaData.asteroids ? state.nasaData.asteroids.map(asteroid => ({
name: asteroid.name,
diameter: Math.round(asteroid.estimated_diameter.kilometers.estimated_diameter_max),
hazardous: asteroid.is_potentially_hazardous_asteroid,
missDistance: Math.round(asteroid.close_approach_data[0].miss_distance.kilometers)
})) : [],
issPosition: state.nasaData.issPosition?.iss_position ? {
latitude: parseFloat(state.nasaData.issPosition.iss_position.latitude).toFixed(2),
longitude: parseFloat(state.nasaData.issPosition.iss_position.longitude).toFixed(2),
timestamp: new Date(state.nasaData.issPosition.timestamp * 1000).toISOString()
} : null,
spaceWeather: state.nasaData.spaceWeather?.alerts ? {
alerts: state.nasaData.spaceWeather.alerts.slice(0, 3).map(alert => ({
type: alert.type,
severity: alert.severity,
message: alert.message
}))
} : null,
marsPhotos: state.nasaData.marsPhotos?.photos ? {
count: state.nasaData.marsPhotos.photos.length,
rover: state.nasaData.marsPhotos.photos[0]?.rover.name || 'Unknown',
latestDate: state.nasaData.marsPhotos.photos[0]?.earth_date || 'Unknown'
} : null
};
const response = await safeFetch('/api/chat/initialize', {
method: 'POST',
body: JSON.stringify({
message,
agent: state.activeAgent,
context: {
agentType: agents[state.activeAgent].description,
spaceData: spaceContext,
chatHistory: state.messages
.filter(m => !m.isLoading)
.map(m => ({
role: m.type === 'user' ? 'user' : 'assistant',
content: m.content
}))
}
})
});
// Remove loading message
state.messages = state.messages.filter(m => !m.isLoading);
// Add bot response
if (response.response) {
state.messages.push({
type: 'bot',
content: response.response,
agent: state.activeAgent
});
} else {
throw new Error('Invalid response format');
}
updateChatUI();
} catch (error) {
console.error('Send Message Error:', error);
state.messages = state.messages.filter(m => !m.isLoading);
state.messages.push({
type: 'bot',
content: 'I apologize, but I encountered an error. Please try again.',
agent: state.activeAgent
});
updateChatUI();
}
}
function showError(message) {
const errorState = document.getElementById('error-state');
const errorMessage = document.getElementById('error-message');
const loadingState = document.getElementById('loading-state');
const mainContent = document.getElementById('main-content');
errorMessage.textContent = message;
errorState.classList.remove('hidden');
loadingState.classList.add('hidden');
mainContent.classList.add('hidden');
}
function setupEventListeners() {
const chatHeader = document.getElementById('chat-header');
const chatContainer = document.getElementById('chat-container');
chatHeader.addEventListener('click', () => {
state.isChatOpen = !state.isChatOpen;
chatContainer.classList.toggle('chat-hidden');
chatContainer.classList.toggle('chat-visible');
});
const sendButton = document.getElementById('send-message');
const chatInput = document.getElementById('chat-input');
sendButton.addEventListener('click', handleSendMessage);
chatInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
handleSendMessage();
}
});
}
function setupAgentSelector() {
const agentSelector = document.getElementById('agent-selector');
agentSelector.innerHTML = Object.entries(agents).map(([key, agent]) => `
<button
class="flex items-center gap-2 px-3 py-2 rounded-lg transition-colors ${
state.activeAgent === key
? 'bg-blue-500/20 text-blue-400'
: 'hover:bg-slate-800 text-slate-400'
}"
data-agent="${key}"
>
<i class="fas ${agent.icon} h-4 w-4"></i>
<span>${agent.name}</span>
</button>
`).join('');
const agentButtons = agentSelector.querySelectorAll('button');
agentButtons.forEach(button => {
button.addEventListener('click', async () => {
const newAgent = button.dataset.agent;
if (newAgent !== state.activeAgent) {
state.activeAgent = newAgent;
agentButtons.forEach(btn => {
btn.classList.remove('bg-blue-500/20', 'text-blue-400');
btn.classList.add('hover:bg-slate-800', 'text-slate-400');
});
button.classList.remove('hover:bg-slate-800', 'text-slate-400');
button.classList.add('bg-blue-500/20', 'text-blue-400');
await initializeChat();
}
});
});
}
// Enhanced chat UI update
function updateChatUI() {
const chatMessages = document.getElementById('chat-messages');
chatMessages.innerHTML = state.messages.map(message => `
<div class="flex ${message.type === 'user' ? 'justify-end' : 'justify-start'} ${message.isLoading ? 'opacity-50' : ''}">
<div class="max-w-[80%] rounded-lg p-3 ${
message.type === 'user'
? 'bg-blue-600 text-white ml-4'
: 'bg-slate-700/50 backdrop-blur-sm text-white mr-4'
}">
${message.type === 'bot' ? `
<div class="flex items-center gap-2 mb-1 text-xs text-slate-400">
<div class="bg-slate-600/50 p-1 rounded">
<i class="fas ${agents[message.agent].icon} h-3 w-3"></i>
</div>
<span>${agents[message.agent].name}</span>
</div>
` : ''}
<div class="text-sm ${message.type === 'user' ? 'text-white' : 'text-slate-200'}">
${message.content}
</div>
</div>
</div>
`).join('');
chatMessages.scrollTop = chatMessages.scrollHeight;
document.getElementById('agent-status').textContent = `${agents[state.activeAgent].name} Active`;
}
// Initialize the application
async function initializeApp() {
try {
console.log('Initializing application...');
document.getElementById('error-state').classList.add('hidden');
document.getElementById('loading-state').classList.remove('hidden');
document.getElementById('main-content').classList.add('hidden');
setupEventListeners();
setupAgentSelector();
await fetchAllData();
await initializeChat();
} catch (error) {
console.error('Initialization Error:', error);
showError('Failed to initialize the application. Please try again.');
}
}
// Start the application when the document is ready
document.addEventListener('DOMContentLoaded', initializeApp);
</script>
</body>
</html>