-
Notifications
You must be signed in to change notification settings - Fork 1
/
community.html
672 lines (601 loc) · 29.8 KB
/
community.html
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
<!-- community.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Added -->
<title>Community Hub - Urban Upgrades</title>
<!-- Include Tailwind CSS for styling -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Include Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Include Roboto Font -->
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<style>
/* Custom styles */
body {
font-family: 'Roboto', sans-serif;
}
.btn-animate:hover {
transform: scale(1.05);
transition: transform 0.2s;
}
/* Loading Spinner Styles */
#loading {
display: flex;
justify-content: center;
align-items: center;
height: 100px;
}
/* Modal Styles */
.modal {
transition: opacity 0.25s ease;
}
body.modal-open {
overflow: hidden;
}
/* Fade-in Animation */
.fade-in {
animation: fadeIn 0.5s ease-in-out;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
/* City Display Styles */
.city-display {
margin-left: 10px;
min-width: 120px;
text-align: left;
color: #4B5563; /* Tailwind's gray-700 */
font-size: 0.875rem; /* Tailwind's text-sm */
}
/* Input Container */
.input-container {
display: flex;
align-items: center;
}
/* Delete Button Styles */
.delete-button {
background: none;
border: none;
color: #e53e3e; /* Tailwind's red-600 */
cursor: pointer;
padding: 0.25rem;
}
.delete-button:hover {
color: #c53030; /* Tailwind's red-700 */
}
</style>
</head>
<body class="bg-blue-100 text-gray-800">
<!-- Header section with title and navigation -->
<header class="text-center py-6 bg-blue-600 text-white shadow-md">
<h1 class="text-4xl font-bold">Community Hub</h1>
<nav class="mt-4 flex justify-center space-x-4">
<a href="index.html" class="text-white hover:text-blue-300 flex items-center">
<i class="fas fa-home mr-2"></i> Home
</a>
<a href="correspondence.html" class="text-white hover:text-blue-300 flex items-center">
<i class="fas fa-envelope mr-2"></i> Correspondence
</a>
<a href="login.html" class="text-white hover:text-blue-300 flex items-center">
<i class="fas fa-sign-out-alt mr-2"></i> Logout
</a>
</nav>
</header>
<!-- Main content area -->
<main class="max-w-4xl mx-auto p-6 mt-10 bg-white rounded-lg shadow-lg">
<!-- Location Selection Section -->
<section class="mb-8">
<h2 class="text-xl font-semibold mb-2">Input ZIP Code To Filter Threads</h2>
<div class="space-y-2">
<div class="input-container">
<input
type="text"
id="locationZipInput"
placeholder="Enter your ZIP code..."
required
pattern="\d{5}"
title="Please enter a valid 5-digit ZIP code."
maxlength="5"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
>
<p id="locationCityDisplay" class="city-display"></p>
</div>
<small class="text-gray-500">We'll display your city once a valid ZIP code is entered.</small>
</div>
</section>
<!-- New Post Section -->
<section class="mb-8">
<h2 class="text-2xl font-semibold mb-4">Submit a New Post</h2>
<form id="threadForm" class="space-y-4">
<div>
<label for="threadNameInput" class="block text-sm font-medium text-gray-700">Thread Title</label>
<input
type="text"
id="threadNameInput"
placeholder="Enter your thread title here..."
required
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
>
</div>
<div>
<label for="threadZipCodeInput" class="block text-sm font-medium text-gray-700">Zip Code</label>
<div class="input-container">
<input
type="text"
id="threadZipCodeInput"
placeholder="Enter the ZIP code for your post..."
required
pattern="\d{5}"
title="Please enter a valid 5-digit ZIP code."
maxlength="5"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
>
<p id="threadCityDisplay" class="city-display"></p>
</div>
<small class="text-gray-500">We'll display the city once a valid ZIP code is entered.</small>
</div>
<button type="submit" class="w-full bg-blue-600 text-white px-4 py-2 rounded btn-animate flex items-center justify-center">
<i class="fas fa-plus mr-2"></i> Add Thread
</button>
</form>
</section>
<!-- Posts Section -->
<section>
<!-- Updated Title with id -->
<h2 id="topPostsTitle" class="text-2xl font-semibold mb-4">Top Posts in Your Region</h2>
<!-- Loading Indicator --> <!-- Updated Loading Indicator -->
<div id="loading" class="flex justify-center items-center h-24" aria-live="polite" aria-busy="true">
<div class="w-12 h-12 border-4 border-blue-600 border-t-transparent border-solid rounded-full animate-spin"></div>
</div>
<div id="posts-container" class="space-y-4 hidden">
<!-- Posts will be dynamically populated here -->
</div>
</section>
</main>
<!-- Comments Modal -->
<div id="commentsModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden">
<div class="bg-white p-6 rounded-lg w-11/12 max-w-2xl relative fade-in">
<button id="closeCommentsModal" class="absolute top-2 right-2 text-gray-600 hover:text-gray-800">
<i class="fas fa-times fa-lg"></i>
</button>
<h2 id="modalThreadTitle" class="text-2xl font-semibold mb-4"></h2>
<div id="commentsSection" class="max-h-96 overflow-y-auto mb-4">
<!-- Comments will be displayed here -->
<div id="commentsContainer" class="space-y-4">
<!-- Comment items -->
</div>
</div>
<form id="commentForm" class="space-y-4">
<textarea
id="commentInput"
placeholder="Add a comment..."
required
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
></textarea>
<div class="flex justify-end">
<button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded btn-animate flex items-center">
<i class="fas fa-paper-plane mr-2"></i> Post Comment
</button>
</div>
</form>
</div>
</div>
<!-- Delete Confirmation Modal -->
<div id="deleteConfirmationModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden">
<div class="bg-white p-6 rounded-lg w-11/12 max-w-md relative fade-in">
<h3 id="deleteConfirmationTitle" class="text-xl font-semibold mb-4">Confirm Deletion</h3>
<p id="deleteConfirmationMessage" class="mb-6">Are you sure you want to delete this item?</p>
<div class="flex justify-end space-x-4">
<button id="cancelDeleteButton" class="bg-gray-300 text-gray-700 px-4 py-2 rounded">Cancel</button>
<button id="confirmDeleteButton" class="bg-red-600 text-white px-4 py-2 rounded">Delete</button>
</div>
</div>
</div>
<!-- Scripts -->
<script type="module" defer>
import {
addThread,
getAllThreads,
getCommentsWithUpvotes,
addCommentToThread,
incrementUpvote,
decrementUpvote,
deleteThread,
deleteCommentFromThread
} from './database_funcs.js';
// Importing sendPostRequest and saveEmailToFirestore
import {
sendPostRequest,
saveEmailToFirestore
} from './Javascript_API_POST_function.js';
const threadForm = document.getElementById('threadForm');
const postsContainer = document.getElementById('posts-container');
const loadingIndicator = document.getElementById('loading');
const commentsModal = document.getElementById('commentsModal');
const closeCommentsModal = document.getElementById('closeCommentsModal');
const modalThreadTitle = document.getElementById('modalThreadTitle');
const commentsContainerDiv = document.getElementById('commentsContainer');
const commentForm = document.getElementById('commentForm');
const commentInput = document.getElementById('commentInput');
const locationZipInput = document.getElementById('locationZipInput');
const locationCityDisplay = document.getElementById('locationCityDisplay');
const threadZipCodeInput = document.getElementById('threadZipCodeInput');
const threadCityDisplay = document.getElementById('threadCityDisplay');
const topPostsTitle = document.getElementById('topPostsTitle'); // Added for dynamic title
// Delete Confirmation Modal Elements
const deleteConfirmationModal = document.getElementById('deleteConfirmationModal');
const deleteConfirmationTitle = document.getElementById('deleteConfirmationTitle');
const deleteConfirmationMessage = document.getElementById('deleteConfirmationMessage');
const cancelDeleteButton = document.getElementById('cancelDeleteButton');
const confirmDeleteButton = document.getElementById('confirmDeleteButton');
let currentThreadId = null;
let currentLocation = null; // { city, zip_code }
let deleteAction = null; // Function to execute on delete confirmation
// Debounce function to limit API calls
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
// Function to fetch city from ZIP code using Zippopotam.us API
async function fetchCity(zipCode) {
try {
const response = await fetch(`https://api.zippopotam.us/us/${zipCode}`);
if (response.ok) {
const data = await response.json();
const place = data.places[0];
return {
city: place['place name'],
};
} else {
return null;
}
} catch (error) {
console.error('Error fetching city:', error);
return null;
}
}
// Debounced handler for location ZIP code input
const handleLocationZipInput = debounce(async (event) => {
const zipCode = event.target.value.trim();
if (/^\d{5}$/.test(zipCode)) {
const locationData = await fetchCity(zipCode);
if (locationData) {
currentLocation = {
zip_code: zipCode,
city: locationData.city,
};
locationCityDisplay.textContent = `${locationData.city}`;
// Update the title with the city name
topPostsTitle.textContent = `Top Posts in ${locationData.city}`;
displayThreads(); // Update the threads based on the new location
} else {
locationCityDisplay.textContent = 'Invalid ZIP code';
currentLocation = null;
topPostsTitle.textContent = 'Top Posts in Your Region'; // Reset title
postsContainer.innerHTML = '<p class="text-gray-500">Please enter a valid ZIP code to view threads.</p>';
}
} else {
locationCityDisplay.textContent = '';
currentLocation = null;
topPostsTitle.textContent = 'Top Posts in Your Region'; // Reset title
postsContainer.innerHTML = '<p class="text-gray-500">Please enter a valid ZIP code to view threads.</p>';
}
}, 500); // 500ms debounce delay
// Debounced handler for thread ZIP code input
const handleThreadZipInput = debounce(async (event) => {
const zipCode = event.target.value.trim();
if (/^\d{5}$/.test(zipCode)) {
const locationData = await fetchCity(zipCode);
if (locationData) {
threadCityDisplay.textContent = `${locationData.city}`;
} else {
threadCityDisplay.textContent = 'Invalid ZIP code';
}
} else {
threadCityDisplay.textContent = '';
}
}, 500); // 500ms debounce delay
// Event listeners for ZIP code inputs
locationZipInput.addEventListener('input', handleLocationZipInput);
threadZipCodeInput.addEventListener('input', handleThreadZipInput);
// Function to open comments modal
function openCommentsModal(thread) {
currentThreadId = thread.id;
modalThreadTitle.textContent = thread.thread_name;
commentsContainerDiv.innerHTML = '';
fetchComments(thread.id);
commentsModal.classList.remove('hidden');
document.body.classList.add('modal-open');
}
// Function to close comments modal
function closeModal() {
commentsModal.classList.add('hidden');
document.body.classList.remove('modal-open');
commentForm.reset();
currentThreadId = null;
}
closeCommentsModal.addEventListener('click', closeModal);
// Function to open delete confirmation modal
function openDeleteConfirmation(title, message, action) {
deleteConfirmationTitle.textContent = title;
deleteConfirmationMessage.textContent = message;
deleteAction = action;
deleteConfirmationModal.classList.remove('hidden');
document.body.classList.add('modal-open');
}
// Function to close delete confirmation modal
function closeDeleteConfirmation() {
deleteConfirmationModal.classList.add('hidden');
document.body.classList.remove('modal-open');
deleteAction = null;
}
// Event listeners for delete confirmation buttons
cancelDeleteButton.addEventListener('click', closeDeleteConfirmation);
confirmDeleteButton.addEventListener('click', async () => {
if (deleteAction) {
await deleteAction();
closeDeleteConfirmation();
}
});
// Function to create post element
function createPostElement(thread) {
const threadDiv = document.createElement('div');
threadDiv.className = 'bg-gray-100 p-6 rounded-lg shadow-md hover:bg-gray-200 transition-colors duration-200';
const threadHeader = document.createElement('div');
threadHeader.className = 'flex justify-between items-center mb-4';
const threadTitle = document.createElement('h3');
threadTitle.className = 'text-xl font-bold text-blue-600';
threadTitle.textContent = thread.thread_name;
const threadActionsDiv = document.createElement('div');
threadActionsDiv.className = 'flex space-x-2';
const viewCommentsButton = document.createElement('button');
viewCommentsButton.className = 'text-blue-500 hover:text-blue-700 flex items-center';
viewCommentsButton.innerHTML = '<i class="fas fa-comments mr-2"></i> View Comments';
viewCommentsButton.addEventListener('click', () => openCommentsModal(thread));
const deleteThreadButton = document.createElement('button');
deleteThreadButton.className = 'delete-button';
deleteThreadButton.innerHTML = '<i class="fas fa-trash-alt"></i>';
deleteThreadButton.title = 'Delete Thread';
deleteThreadButton.addEventListener('click', () => {
openDeleteConfirmation(
'Delete Thread',
'Are you sure you want to delete this thread? This action cannot be undone.',
async () => {
try {
await deleteThread(thread.id);
await displayThreads();
} catch (error) {
console.error('Error deleting thread:', error);
alert('Failed to delete thread. Please try again.');
}
}
);
});
// Resolve Button
const resolveButton = document.createElement('button');
resolveButton.className = 'text-green-500 hover:text-green-700 flex items-center';
resolveButton.innerHTML = '<i class="fas fa-check-circle mr-2"></i> Resolve';
resolveButton.addEventListener('click', async () => {
try {
// Call getCommentsWithUpvotes(thread.id)
const data = await getCommentsWithUpvotes(thread.id);
// The output of that would be used as the parameter to call sendPostRequest(data)
const emailContent = await sendPostRequest(JSON.stringify(data));
// Then that output would be sent here along with the thread_id
await saveEmailToFirestore(emailContent, thread.id);
alert('Email generated and saved successfully.');
} catch (error) {
console.error('Error resolving thread:', error);
alert('Failed to resolve thread. Please try again.');
}
});
threadActionsDiv.appendChild(viewCommentsButton);
threadActionsDiv.appendChild(deleteThreadButton);
threadActionsDiv.appendChild(resolveButton); // Added Resolve Button
threadHeader.appendChild(threadTitle);
threadHeader.appendChild(threadActionsDiv);
const threadLocation = document.createElement('p');
threadLocation.className = 'text-gray-600';
threadLocation.textContent = `Location: ${thread.city}, ${thread.zip_code}`;
threadDiv.appendChild(threadHeader);
threadDiv.appendChild(threadLocation);
return threadDiv;
}
// Updated displayThreads function with sorting
async function displayThreads() {
// Show loading indicator
loadingIndicator.style.display = 'flex';
postsContainer.classList.add('hidden');
try {
const threads = await getAllThreads();
if (!currentLocation) {
postsContainer.innerHTML = '<p class="text-gray-500">Please enter your ZIP code to view threads.</p>';
} else {
// Filter threads based on current location's zip code and city
const filteredThreads = threads.filter(thread =>
thread.zip_code === currentLocation.zip_code && thread.city === currentLocation.city
);
if (filteredThreads.length === 0) {
postsContainer.innerHTML = '<p class="text-gray-500">No threads available in your region. Be the first to post!</p>';
} else {
// Calculate total score for each thread
const threadsWithScores = await Promise.all(filteredThreads.map(async (thread) => {
const commentsData = await getCommentsWithUpvotes(thread.id);
const commentsUpvotesSum = commentsData.comments.reduce((sum, comment) => {
const upvote = Number(comment.upvotes);
return sum + (isNaN(upvote) ? 0 : upvote);
}, 0);
const threadUpvotes = Number(thread.upvotes);
const totalScore = (isNaN(threadUpvotes) ? 0 : threadUpvotes) + (isNaN(commentsUpvotesSum) ? 0 : commentsUpvotesSum);
return { ...thread, totalScore };
}));
// Sort threads based on totalScore in descending order
threadsWithScores.sort((a, b) => b.totalScore - a.totalScore);
// Clear existing posts
postsContainer.innerHTML = '';
// Create and append sorted thread elements
threadsWithScores.forEach(thread => {
const threadElement = createPostElement(thread);
postsContainer.appendChild(threadElement);
});
}
}
// Hide loading indicator and show posts container
loadingIndicator.style.display = 'none';
postsContainer.classList.remove('hidden');
} catch (error) {
console.error('Error displaying threads:', error);
alert('Failed to load threads. Please try again later.');
loadingIndicator.style.display = 'none';
}
}
// Function to fetch and display comments
async function fetchComments(threadId) {
try {
const data = await getCommentsWithUpvotes(threadId);
commentsContainerDiv.innerHTML = '';
if (data.comments.length === 0) {
commentsContainerDiv.innerHTML = '<p class="text-gray-500">No comments yet. Be the first to comment!</p>';
} else {
data.comments.forEach(comment => {
const commentElement = createCommentElement(comment, threadId);
commentsContainerDiv.appendChild(commentElement);
});
}
} catch (error) {
console.error('Error fetching comments:', error);
alert('Failed to load comments. Please try again later.');
}
}
// Function to create comment element
function createCommentElement(comment, threadId) {
const commentDiv = document.createElement('div');
commentDiv.className = 'bg-gray-50 p-4 rounded shadow comment-animate flex flex-col';
const commentHeader = document.createElement('div');
commentHeader.className = 'flex justify-between items-center mb-2';
const textP = document.createElement('p');
textP.textContent = comment.text;
textP.className = 'text-gray-800';
const deleteCommentButton = document.createElement('button');
deleteCommentButton.className = 'delete-button';
deleteCommentButton.innerHTML = '<i class="fas fa-trash-alt"></i>';
deleteCommentButton.title = 'Delete Comment';
deleteCommentButton.addEventListener('click', () => {
openDeleteConfirmation(
'Delete Comment',
'Are you sure you want to delete this comment? This action cannot be undone.',
async () => {
try {
await deleteCommentFromThread(threadId, comment.id);
await fetchComments(threadId);
await displayThreads(); // Refresh threads to update sorting
} catch (error) {
console.error('Error deleting comment:', error);
alert('Failed to delete comment. Please try again.');
}
}
);
});
commentHeader.appendChild(textP);
commentHeader.appendChild(deleteCommentButton);
const upvotesP = document.createElement('p');
upvotesP.textContent = `Upvotes: ${comment.upvotes}`;
upvotesP.className = 'mb-2 text-gray-600';
const voteButtonsDiv = document.createElement('div');
voteButtonsDiv.className = 'flex space-x-4';
// Upvote button
const upvoteButton = document.createElement('button');
upvoteButton.className = 'flex items-center text-green-500 hover:text-green-600';
upvoteButton.innerHTML = '<i class="fas fa-thumbs-up mr-1"></i> Upvote';
upvoteButton.onclick = async () => {
try {
await incrementUpvote(threadId, comment.id);
await fetchComments(threadId);
await displayThreads(); // Refresh threads to update sorting
} catch (error) {
console.error('Error incrementing upvote:', error);
alert('Failed to upvote. Please try again.');
}
};
// Downvote button
const downvoteButton = document.createElement('button');
downvoteButton.className = 'flex items-center text-red-500 hover:text-red-600';
downvoteButton.innerHTML = '<i class="fas fa-thumbs-down mr-1"></i> Downvote';
downvoteButton.onclick = async () => {
try {
await decrementUpvote(threadId, comment.id);
await fetchComments(threadId);
await displayThreads(); // Refresh threads to update sorting
} catch (error) {
console.error('Error decrementing upvote:', error);
alert('Failed to downvote. Please try again.');
}
};
voteButtonsDiv.appendChild(upvoteButton);
voteButtonsDiv.appendChild(downvoteButton);
commentDiv.appendChild(commentHeader);
commentDiv.appendChild(upvotesP);
commentDiv.appendChild(voteButtonsDiv);
return commentDiv;
}
// Event listener for thread form submission
threadForm.addEventListener('submit', async (event) => {
event.preventDefault();
const threadName = document.getElementById('threadNameInput').value.trim();
const zipCode = document.getElementById('threadZipCodeInput').value.trim();
const cityText = threadCityDisplay.textContent;
if (!threadName || !zipCode || !cityText || cityText === 'Invalid ZIP code') {
alert('Please enter a valid thread title and ZIP code.');
return;
}
const city = cityText;
try {
await addThread(threadName, zipCode, city);
threadForm.reset(); // Clear all inputs
threadCityDisplay.textContent = '';
await displayThreads(); // Refresh the threads list
} catch (error) {
console.error('Error adding thread:', error);
alert('Failed to add thread. Please try again.');
}
});
// Event listener for comment form submission
commentForm.addEventListener('submit', async (event) => {
event.preventDefault();
const commentText = commentInput.value.trim();
if (!commentText) {
alert('Please enter a comment.');
return;
}
try {
await addCommentToThread(currentThreadId, commentText);
commentForm.reset();
await fetchComments(currentThreadId);
await displayThreads(); // Refresh threads to update sorting
} catch (error) {
console.error('Error adding comment:', error);
alert('Failed to add comment. Please try again.');
}
});
// Initialize by displaying threads if location is already set
if (currentLocation) {
displayThreads();
}
// Close modals when clicking outside of them
window.addEventListener('click', (event) => {
if (event.target === commentsModal) {
closeModal();
}
if (event.target === deleteConfirmationModal) {
closeDeleteConfirmation();
}
});
</script>
</body>
</html>