-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1979 lines (1779 loc) Β· 82.3 KB
/
script.js
File metadata and controls
1979 lines (1779 loc) Β· 82.3 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
'use strict';
/* ββ Constants βββββββββββββββββββββββββββββββββββββββββββββ */
const DEFAULT_CATEGORIES = [
{ name: 'Arts & Entertainment', slug: 'arts-entertainment', color: '#7c4ea8' },
{ name: 'Community & Civic', slug: 'community-civic', color: '#1e5c9a' },
{ name: 'Food & Markets', slug: 'food-markets', color: '#b86018' },
{ name: 'Sports & Recreation', slug: 'sports-recreation', color: '#2a7a42' },
];
let categoriesCache = [...DEFAULT_CATEGORIES];
/** @returns {{ name: string, slug: string, color: string }[]} */
function loadCategories() {
return categoriesCache;
}
function saveCategories(cats) {
categoriesCache = cats;
fetch(`${API_BASE}/api/categories`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-Admin-Password': sessionStorage.getItem('albionAdminPw') || '',
},
body: JSON.stringify(cats),
}).catch(e => console.error('[API] saveCategories failed:', e));
}
/** @returns {Object.<string,string>} name β slug */
function getCategorySlugs() {
return Object.fromEntries(loadCategories().map(c => [c.name, c.slug]));
}
/** @returns {Object.<string,string>} name β color */
function getCategoryColors() {
return Object.fromEntries(loadCategories().map(c => [c.name, c.color]));
}
// Keep module-level aliases updated via functions so existing call sites work
const CATEGORY_SLUGS = new Proxy({}, { get: (_, k) => getCategorySlugs()[k] });
const CAT_COLORS = new Proxy({}, { get: (_, k) => getCategoryColors()[k] });
function slugify(name) {
return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
}
function randomCatColor() {
const colors = ['#7c4ea8','#1e5c9a','#b86018','#2a7a42','#b84444','#2a6e7a','#7a6a2a','#a85e7c'];
return colors[Math.floor(Math.random() * colors.length)];
}
function rebuildCategoryUI() {
const cats = loadCategories();
// Rebuild filter nav buttons (keep All + Near Me + Print)
const nav = document.querySelector('.filter-inner');
nav.querySelectorAll('.filter-btn[data-cat-slug]:not([data-cat-slug="all"])').forEach(b => b.remove());
const divider = nav.querySelector('.filter-divider');
cats.forEach(cat => {
const btn = document.createElement('button');
btn.className = 'filter-btn';
btn.dataset.catSlug = cat.slug;
btn.textContent = cat.name;
nav.insertBefore(btn, divider);
});
if (currentCategory !== 'all' && !cats.find(c => c.slug === currentCategory)) {
currentCategory = 'all';
nav.querySelector('[data-cat-slug="all"]').classList.add('active');
}
// Rebuild form category select
const sel = document.getElementById('event-category');
const current = sel.value;
sel.innerHTML = cats.map(c =>
`<option value="${c.name}"${c.name === current ? ' selected' : ''}>${c.name}</option>`
).join('');
// Rebuild admin category manager if open
renderAdminCategoryManager();
}
function renderAdminCategoryManager() {
const container = document.getElementById('admin-category-manager');
if (!container) return;
const cats = loadCategories();
container.innerHTML = `
<div class="admin-cat-list">
${cats.map(c => `
<div class="admin-cat-row">
<span class="admin-cat-dot" style="background:${c.color}"></span>
<span class="admin-cat-name">${sanitize(c.name)}</span>
${DEFAULT_CATEGORIES.find(d => d.slug === c.slug) ? '' :
`<button class="btn-admin-del-cat" data-slug="${c.slug}" aria-label="Remove category">✕</button>`}
</div>`).join('')}
</div>
<div class="admin-cat-add">
<input type="text" id="admin-new-cat-name" placeholder="New category name\u2026" class="admin-cat-input">
<input type="color" id="admin-new-cat-color" value="#2a7a42" class="admin-cat-color-pick" title="Pick a color">
<button id="btn-admin-add-cat" class="btn-admin-action">Add</button>
</div>`;
}
const defaultEvents = [
{
id: 1,
name: "Farmers Market",
date: "2026-04-05",
time: "08:00",
location: "Town Square, Albion IN",
description: "Weekly farmers market with fresh local produce, baked goods, and handmade crafts from Noble County farmers and artisans.",
category: "Food & Markets",
organizer: "albionfarmers@example.com",
recurring: "weekly",
featured: true,
status: "active",
going: 14, maybe: 6, went: 0,
comments: ["Can't wait for the strawberries this season!", "Will the honey vendor be there?"],
image: null,
},
{
id: 2,
name: "Spring Town Hall Meeting",
date: "2026-04-08",
time: "19:00",
location: "Albion Town Hall, 101 N Orange St",
description: "Quarterly town hall open to all residents. Agenda includes road improvements on SR-9, park renovation updates, and plans for a community garden.",
category: "Community & Civic",
organizer: "townhall@albion.in.gov",
recurring: "none",
featured: true,
status: "active",
going: 22, maybe: 8, went: 0,
comments: [],
image: null,
},
{
id: 3,
name: "Albion Parks 5K Fun Run",
date: "2026-04-12",
time: "09:00",
location: "Albion City Park",
description: "Annual 5K fun run through the park. All ages welcome β walkers included. Pre-registration appreciated but walk-ins accepted at the trailhead.",
category: "Sports & Recreation",
organizer: "parks@albion.in.gov",
recurring: "none",
featured: false,
status: "active",
going: 31, maybe: 12, went: 0,
comments: ["Is there a kids division?", "Will there be water stations along the route?"],
image: null,
},
{
id: 4,
name: "Noble County Art Show",
date: "2026-04-18",
time: "10:00",
location: "Albion Public Library, 108 W Main St",
description: "Annual juried art show featuring works by Noble County artists. Opening reception Friday 5β7 PM. Free admission all weekend.",
category: "Arts & Entertainment",
organizer: "artshow@albionlibrary.org",
recurring: "none",
featured: false,
status: "active",
going: 18, maybe: 9, went: 0,
comments: [],
image: null,
},
{
id: 5,
name: "Spring Softball League",
date: "2026-04-03",
time: "18:00",
location: "Albion Athletic Complex",
description: "Spring recreational softball league β season runs April through June. Games every Friday evening. All skill levels welcome.",
category: "Sports & Recreation",
organizer: "softball@albion.com",
recurring: "weekly",
featured: false,
status: "active",
going: 24, maybe: 5, went: 0,
comments: ["Go Tigers!"],
image: null,
},
{
id: 6,
name: "Easter Egg Hunt",
date: "2026-04-04",
time: "10:00",
location: "City Park, Albion IN",
description: "Annual Easter egg hunt for children ages 2β12. Bring a basket! New date TBD β follow the Albion Parks Facebook page for updates.",
category: "Community & Civic",
organizer: "community@albion.in.gov",
recurring: "none",
featured: false,
status: "postponed",
going: 0, maybe: 0, went: 0,
comments: [],
image: null,
},
];
/* ββ API βββββββββββββββββββββββββββββββββββββββββββββββββββ */
const API_BASE = ''; // same origin β Worker handles /api/* routes
/* ββ State βββββββββββββββββββββββββββββββββββββββββββββββββ */
let currentQuery = '';
let currentCategory = 'all';
let currentView = 'list'; // 'list' | 'calendar'
let calendarYear = new Date().getFullYear();
let calendarMonth = new Date().getMonth();
let map = null;
let mapLoaded = false;
let modalMap = null;
let nearMeActive = false;
let userLocation = null;
let pastEventsOpen = false;
let eventsPage = 1;
const PAGE_SIZE = 12;
let editingEventId = null;
/* ββ Geocoding βββββββββββββββββββββββββββββββββββββββββββββ */
let geocodeCache = {};
let geocodeQueue = [];
let geocodeRunning = false;
function loadGeoCache() {
try { geocodeCache = JSON.parse(localStorage.getItem('albionGeoCache') || '{}'); }
catch (e) { geocodeCache = {}; }
}
function saveGeoCache() {
try { localStorage.setItem('albionGeoCache', JSON.stringify(geocodeCache)); }
catch (e) { /* quota exceeded β ignore */ }
}
function geocodeAddress(address, callback) {
if (!address) { callback(null); return; }
if (geocodeCache[address]) { callback(geocodeCache[address]); return; }
geocodeQueue.push({ address, callback });
if (!geocodeRunning) processGeocodeQueue();
}
function processGeocodeQueue() {
if (geocodeQueue.length === 0) { geocodeRunning = false; return; }
geocodeRunning = true;
const { address, callback } = geocodeQueue.shift();
const url = `https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(address + ', Noble County, Indiana')}&format=json&limit=1`;
fetch(url)
.then(r => r.json())
.then(data => {
const coords = data && data.length > 0
? { lat: parseFloat(data[0].lat), lng: parseFloat(data[0].lon) }
: null;
if (coords) {
geocodeCache[address] = coords;
saveGeoCache();
}
callback(coords);
})
.catch(() => callback(null))
.finally(() => setTimeout(processGeocodeQueue, 1200)); // Nominatim: max 1 req/sec
}
/* ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββ */
function sanitize(str) {
const el = document.createElement('div');
el.textContent = String(str == null ? '' : str);
return el.innerHTML;
}
/** @param {string} raw @returns {string} safe HTML with basic markdown */
function renderMarkdown(raw) {
if (!raw) return '';
const esc = raw
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
const withInline = esc
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.+?)\*/g, '<em>$1</em>')
.replace(/\[([^\]]{1,200})\]\((https?:\/\/[^)\s]{1,500})\)/g,
'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
// List items
const withLists = withInline.replace(/^[-β’]\s(.+)$/gm, '<li>$1</li>');
const withUl = withLists.replace(/(<li>.*?)(?=\n(?!<li>)|$)/gs,
(m) => m.endsWith('</li>') ? m : m);
// Wrap consecutive li blocks
const wrapped = withUl.replace(/(<li>[\s\S]*?<\/li>)(?:\n(<li>[\s\S]*?<\/li>))*/g,
m => `<ul>${m}</ul>`);
// Paragraphs
return wrapped
.split(/\n{2,}/)
.map(b => b.trim())
.filter(Boolean)
.map(b => (b.startsWith('<ul>') || b.startsWith('<li>')) ? b : `<p>${b.replace(/\n/g, '<br>')}</p>`)
.join('');
}
function formatDate(dateStr, timeStr) {
const dt = new Date(dateStr + 'T' + (timeStr || '00:00') + ':00');
const datePart = dt.toLocaleDateString('en-US', {
weekday: 'short', month: 'short', day: 'numeric', year: 'numeric'
});
if (!timeStr) return datePart;
const timePart = dt.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
return `${datePart} \u00b7 ${timePart}`;
}
function haversineDistance(lat1, lon1, lat2, lon2) {
const R = 3959; // miles
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(dLat / 2) ** 2
+ Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) ** 2;
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
/* ββ ICS Generation ββββββββββββββββββββββββββββββββββββββββ */
function generateICS(event, reminderMinutes = 1440) {
const pad = n => String(n).padStart(2, '0');
const esc = s => (s || '').replace(/[\\;,]/g, '\\$&').replace(/\n/g, '\\n');
const [y, m, d] = event.date.split('-');
const [hh, mm] = (event.time || '00:00').split(':');
const startDt = `${y}${m}${d}T${hh}${mm}00`;
const eParts = (event.endTime || '').split(':').filter(Boolean);
const endHour = eParts[0] || pad((parseInt(hh, 10) + 1) % 24);
const endMin = eParts[1] || mm;
const endDt = `${y}${m}${d}T${endHour}${endMin}00`;
const alarm = reminderMinutes > 0 ? [
'BEGIN:VALARM',
`TRIGGER:-PT${reminderMinutes}M`,
'ACTION:DISPLAY',
`DESCRIPTION:Reminder: ${esc(event.name)}`,
'END:VALARM',
].join('\r\n') : '';
const lines = [
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//Albion Community Events//EN',
'BEGIN:VEVENT',
`DTSTART:${startDt}`,
`DTEND:${endDt}`,
`SUMMARY:${esc(event.name)}`,
`DESCRIPTION:${esc(event.description)}`,
`LOCATION:${esc(event.location)}`,
];
if (alarm) lines.push(alarm);
lines.push('END:VEVENT', 'END:VCALENDAR');
const blob = new Blob([lines.join('\r\n')], { type: 'text/calendar;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${(event.name || 'event').replace(/\s+/g, '_')}.ics`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
/** @param {Object} event @returns {string} Google Calendar URL */
function buildGoogleCalURL(event) {
const pad = n => String(n).padStart(2, '0');
const [y, m, d] = event.date.split('-');
const [hh, mm] = (event.time || '00:00').split(':');
const eParts = (event.endTime || '').split(':').filter(Boolean);
const endH = eParts[0] || pad((parseInt(hh, 10) + 1) % 24);
const endM = eParts[1] || mm;
const start = `${y}${m}${d}T${hh}${mm}00`;
const end = `${y}${m}${d}T${endH}${endM}00`;
const p = new URLSearchParams({
action: 'TEMPLATE',
text: event.name || '',
dates: `${start}/${end}`,
details: event.description || '',
location: event.location || '',
});
return `https://calendar.google.com/calendar/render?${p.toString()}`;
}
/* ββ Share Image (Canvas) ββββββββββββββββββββββββββββββββββ */
function wrapText(ctx, text, x, y, maxWidth, lineHeight) {
const words = String(text).split(' ');
let line = '';
for (const word of words) {
const test = line ? line + ' ' + word : word;
if (ctx.measureText(test).width > maxWidth && line) {
ctx.fillText(line, x, y);
line = word;
y += lineHeight;
} else {
line = test;
}
}
ctx.fillText(line, x, y);
return y + lineHeight;
}
function generateShareImage(event) {
const canvas = document.createElement('canvas');
canvas.width = 1200;
canvas.height = 630;
const ctx = canvas.getContext('2d');
const color = CAT_COLORS[event.category] || '#2c4a30';
// Background gradient
const grad = ctx.createLinearGradient(0, 0, 1200, 630);
grad.addColorStop(0, color);
grad.addColorStop(1, '#1a2e1c');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, 1200, 630);
// Subtle overlay pattern (horizontal lines)
ctx.fillStyle = 'rgba(255,255,255,0.03)';
for (let i = 0; i < 630; i += 12) ctx.fillRect(0, i, 1200, 6);
// Category pill
const pillText = (event.category || '').toUpperCase();
ctx.font = 'bold 18px Inter, -apple-system, sans-serif';
const pillW = ctx.measureText(pillText).width + 32;
ctx.fillStyle = 'rgba(255,255,255,0.18)';
ctx.beginPath();
ctx.roundRect(60, 60, pillW, 36, 18);
ctx.fill();
ctx.fillStyle = '#ffffff';
ctx.fillText(pillText, 76, 84);
// Featured star
if (event.featured) {
ctx.font = 'bold 18px Inter, sans-serif';
ctx.fillStyle = '#f0c060';
ctx.fillText('\u2605 FEATURED', pillW + 80, 84);
}
// Event name
ctx.fillStyle = '#ffffff';
ctx.font = 'bold 66px Lora, Georgia, serif';
const titleY = wrapText(ctx, event.name || '', 60, 165, 1080, 78);
// Date
ctx.fillStyle = 'rgba(255,255,255,0.85)';
ctx.font = '30px Inter, sans-serif';
ctx.fillText(formatDate(event.date, event.time), 60, Math.max(titleY + 10, 320));
// Location
if (event.location) {
ctx.fillStyle = 'rgba(255,255,255,0.65)';
ctx.font = '26px Inter, sans-serif';
ctx.fillText(event.location, 60, Math.max(titleY + 55, 365));
}
// Footer bar
ctx.fillStyle = 'rgba(0,0,0,0.25)';
ctx.fillRect(0, 570, 1200, 60);
ctx.fillStyle = 'rgba(255,255,255,0.5)';
ctx.font = '20px Inter, sans-serif';
ctx.fillText('Albion, Indiana \u2014 Community Events Board', 60, 606);
canvas.toBlob(blob => {
const filename = `${(event.name || 'event').replace(/\s+/g, '_')}_share.png`;
if (navigator.canShare && navigator.canShare({ files: [new File([blob], filename, { type: 'image/png' })] })) {
navigator.share({ files: [new File([blob], filename, { type: 'image/png' })] }).catch(() => {});
} else {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
}, 'image/png');
}
/* ββ Image Resize ββββββββββββββββββββββββββββββββββββββββββ */
function resizeImage(file, maxWidth, callback) {
const reader = new FileReader();
reader.onload = e => {
const img = new Image();
img.onload = () => {
const scale = Math.min(1, maxWidth / img.width);
const canvas = document.createElement('canvas');
canvas.width = img.width * scale;
canvas.height = img.height * scale;
canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
callback(canvas.toDataURL('image/jpeg', 0.78));
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
/* ββ Creator Tokens ββββββββββββββββββββββββββββββββββββββββ */
function getCreatorToken(id) {
try {
const tokens = JSON.parse(localStorage.getItem('albionCreatorTokens') || '{}');
return tokens[String(id)] || null;
} catch { return null; }
}
function saveCreatorToken(id, token) {
try {
const tokens = JSON.parse(localStorage.getItem('albionCreatorTokens') || '{}');
tokens[String(id)] = token;
localStorage.setItem('albionCreatorTokens', JSON.stringify(tokens));
} catch {}
}
function isCreator(id) {
return !!getCreatorToken(id);
}
/* ββ Events Cache + API ββββββββββββββββββββββββββββββββββββ */
let eventsCache = [];
let pendingEventsCache = [];
function loadEvents() { return eventsCache; }
async function refreshEvents() {
try {
const r = await fetch(`${API_BASE}/api/events`);
if (r.ok) eventsCache = await r.json();
} catch (e) { console.error('[API] refreshEvents failed:', e); }
}
async function refreshPendingEvents() {
if (!isAdminMode()) { pendingEventsCache = []; return; }
try {
const r = await fetch(`${API_BASE}/api/events/pending`, {
headers: { 'X-Admin-Password': sessionStorage.getItem('albionAdminPw') || '' },
});
pendingEventsCache = r.ok ? await r.json() : [];
} catch { pendingEventsCache = []; }
}
async function refreshCategories() {
try {
const r = await fetch(`${API_BASE}/api/categories`);
if (r.ok) categoriesCache = await r.json();
} catch (e) { console.error('[API] refreshCategories failed:', e); }
}
/* ββ Weather βββββββββββββββββββββββββββββββββββββββββββββββ */
const ALBION_LAT = 41.3959;
const ALBION_LNG = -85.4258;
/** @type {Object|null} */
let weatherData = null;
/** @param {number} code @returns {{emoji:string,label:string}} */
function wmoCodeInfo(code) {
const map = {
0: ['βοΈ','Clear'], 1: ['π€οΈ','Mainly clear'], 2: ['β
','Partly cloudy'],
3: ['βοΈ','Overcast'], 45: ['π«οΈ','Fog'], 48: ['π«οΈ','Icy fog'],
51: ['π¦οΈ','Drizzle'], 53: ['π¦οΈ','Drizzle'], 55: ['π§οΈ','Heavy drizzle'],
61: ['π§οΈ','Rain'], 63: ['π§οΈ','Rain'], 65: ['π§οΈ','Heavy rain'],
71: ['βοΈ','Snow'], 73: ['βοΈ','Snow'], 75: ['βοΈ','Heavy snow'],
77: ['π¨οΈ','Snow grains'], 80: ['π¦οΈ','Showers'], 81: ['π§οΈ','Showers'],
82: ['π§οΈ','Heavy showers'], 85: ['π¨οΈ','Snow showers'], 86: ['π¨οΈ','Snow showers'],
95: ['βοΈ','Thunderstorm'], 96: ['βοΈ','Thunderstorm'], 99: ['βοΈ','Thunderstorm'],
};
const entry = map[code] || ['π‘οΈ','Weather'];
return { emoji: entry[0], label: entry[1] };
}
async function fetchWeather() {
const key = 'albionWeatherV1';
const cached = sessionStorage.getItem(key);
if (cached) { weatherData = JSON.parse(cached); return weatherData; }
try {
const url = `https://api.open-meteo.com/v1/forecast?latitude=${ALBION_LAT}&longitude=${ALBION_LNG}&daily=weather_code,temperature_2m_max,temperature_2m_min&temperature_unit=fahrenheit&timezone=America%2FIndiana%2FIndianapolis&forecast_days=16`;
const r = await fetch(url);
weatherData = await r.json();
sessionStorage.setItem(key, JSON.stringify(weatherData));
} catch (e) { weatherData = null; }
return weatherData;
}
function injectWeather() {
if (!weatherData?.daily) return;
const { time, weather_code, temperature_2m_max, temperature_2m_min } = weatherData.daily;
const byDate = {};
time.forEach((d, i) => {
byDate[d] = {
code: weather_code[i],
max: Math.round(temperature_2m_max[i]),
min: Math.round(temperature_2m_min[i]),
};
});
document.querySelectorAll('.event-card[data-event-date]').forEach(card => {
const w = byDate[card.dataset.eventDate];
const badge = card.querySelector('.weather-badge');
if (!w || !badge) return;
const { emoji } = wmoCodeInfo(w.code);
badge.innerHTML = `<span class="weather-icon">${emoji}</span><span class="weather-temp">${w.max}Β°<span class="weather-temp-low">/${w.min}Β°F</span></span>`;
badge.hidden = false;
});
}
function isAdminMode() {
return sessionStorage.getItem('albionAdminSession') === '1';
}
function setAdminMode(on) {
if (on) {
sessionStorage.setItem('albionAdminSession', '1');
} else {
sessionStorage.removeItem('albionAdminSession');
sessionStorage.removeItem('albionAdminPw');
pendingEventsCache = [];
}
}
function adminHeaders(extra = {}) {
return {
'X-Admin-Password': sessionStorage.getItem('albionAdminPw') || '',
...extra,
};
}
/* ββ Dark Mode βββββββββββββββββββββββββββββββββββββββββββββ */
function applyDarkMode(dark) {
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
localStorage.setItem('albionDarkMode', dark ? '1' : '0');
const btn = document.getElementById('btn-dark-mode');
if (btn) {
btn.innerHTML = dark ? '☀' : '☾';
btn.title = dark ? 'Switch to light mode' : 'Switch to dark mode';
}
}
function toggleDarkMode() {
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
applyDarkMode(!isDark);
}
/* ββ Data Processing βββββββββββββββββββββββββββββββββββββββ */
const today = new Date(new Date().toDateString()); // midnight local
// Advance a date by one recurring interval
function advanceDate(date, recurring) {
const d = new Date(date);
if (recurring === 'weekly') d.setDate(d.getDate() + 7);
else d.setMonth(d.getMonth() + 1);
return d;
}
// Next upcoming instance of a recurring event (or the event itself if still future)
function getNextInstance(event) {
let date = new Date(event.date + 'T00:00:00');
if (date >= today) return event; // original date is still upcoming
while (date < today) date = advanceDate(date, event.recurring);
const dateStr = date.toISOString().split('T')[0];
return { ...event, date: dateStr, _instanceDate: dateStr };
}
// Most recent past instance of a recurring event
function getLastPastInstance(event) {
let date = new Date(event.date + 'T00:00:00');
if (date >= today) return null;
let last = date;
while (true) {
const next = advanceDate(date, event.recurring);
if (next >= today) break;
last = next;
date = next;
}
const dateStr = last.toISOString().split('T')[0];
return { ...event, date: dateStr, _instanceDate: dateStr };
}
// All instances of a recurring event within a given month (for calendar)
function getInstancesInMonth(event, year, month) {
const until = new Date(Date.now() + 366 * 24 * 60 * 60 * 1000);
const results = [];
let date = new Date(event.date + 'T00:00:00');
// Fast-forward to start of target month if needed
const monthStart = new Date(year, month, 1);
while (date < monthStart) date = advanceDate(date, event.recurring);
const monthEnd = new Date(year, month + 1, 1);
while (date < monthEnd && date < until) {
const dateStr = date.toISOString().split('T')[0];
results.push({ ...event, date: dateStr, _instanceDate: dateStr });
date = advanceDate(date, event.recurring);
}
return results;
}
// List view: one entry per event (next occurrence for recurring)
function getAllEvents() {
const events = loadEvents();
const all = [];
events.forEach(ev => {
if (ev.recurring && ev.recurring !== 'none') {
const next = getNextInstance(ev);
if (next) all.push(next);
} else {
all.push(ev);
}
});
return all;
}
// Calendar view: all instances within the given month
function getAllEventsForMonth(year, month) {
const events = loadEvents();
const all = [];
const seen = new Set();
events.forEach(ev => {
if (ev.recurring && ev.recurring !== 'none') {
getInstancesInMonth(ev, year, month).forEach(inst => {
const key = `${inst.id}-${inst.date}`;
if (!seen.has(key)) { seen.add(key); all.push(inst); }
});
} else {
const d = new Date(ev.date + 'T00:00:00');
if (d.getFullYear() === year && d.getMonth() === month) all.push(ev);
}
});
return all;
}
function getUpcomingEvents() {
return getAllEvents().filter(ev => new Date(ev.date + 'T00:00:00') >= today);
}
function getPastEvents() {
const events = loadEvents();
const past = [];
events.forEach(ev => {
if (ev.recurring && ev.recurring !== 'none') {
const last = getLastPastInstance(ev);
if (last) past.push(last);
} else {
if (new Date(ev.date + 'T00:00:00') < today) past.push(ev);
}
});
return past.sort((a, b) => new Date(b.date) - new Date(a.date)).slice(0, 10);
}
function sortEvents(events) {
if (nearMeActive && userLocation) {
return [...events].sort((a, b) => {
const ca = geocodeCache[a.location];
const cb = geocodeCache[b.location];
const da = ca ? haversineDistance(userLocation.lat, userLocation.lng, ca.lat, ca.lng) : Infinity;
const db = cb ? haversineDistance(userLocation.lat, userLocation.lng, cb.lat, cb.lng) : Infinity;
return da - db;
});
}
return [...events].sort((a, b) => {
if (a.featured && !b.featured) return -1;
if (!a.featured && b.featured) return 1;
return new Date(a.date) - new Date(b.date);
});
}
function getFilteredEvents() {
const upcoming = getUpcomingEvents();
const filtered = upcoming.filter(ev => {
const q = currentQuery.toLowerCase();
const matchSearch = !q
|| ev.name.toLowerCase().includes(q)
|| (ev.description || '').toLowerCase().includes(q)
|| ev.category.toLowerCase().includes(q)
|| (ev.location || '').toLowerCase().includes(q);
const matchCat = currentCategory === 'all'
|| CATEGORY_SLUGS[ev.category] === currentCategory;
return matchSearch && matchCat;
});
return sortEvents(filtered);
}
/* ββ Rendering βββββββββββββββββββββββββββββββββββββββββββββ */
function renderEventCard(event) {
const catSlug = CATEGORY_SLUGS[event.category] || 'community-civic';
const domId = event._instanceDate ? `${event.id}-${event._instanceDate}` : String(event.id);
const baseId = event.id;
const comments = event.comments || [];
const commentCount = comments.length;
const creatorControls = !isAdminMode() && isCreator(baseId) ? `
<div class="creator-controls">
<button class="btn-creator-edit" data-id="${baseId}">✎ Edit your event</button>
</div>` : '';
let distanceBadge = '';
if (nearMeActive && userLocation && geocodeCache[event.location]) {
const coords = geocodeCache[event.location];
const d = haversineDistance(userLocation.lat, userLocation.lng, coords.lat, coords.lng);
distanceBadge = `<span class="distance-badge">${d < 10 ? d.toFixed(1) : Math.round(d)} mi</span>`;
}
const adminControls = isAdminMode() ? `
<div class="admin-controls">
<span class="admin-label">Admin:</span>
<div class="admin-status-group">
<button class="btn-admin-set-status${event.status === 'active' ? ' current-status' : ''}" data-id="${baseId}" data-status="active">Active</button>
<button class="btn-admin-set-status${event.status === 'postponed' ? ' current-status' : ''}" data-id="${baseId}" data-status="postponed">Postpone</button>
<button class="btn-admin-set-status${event.status === 'cancelled' ? ' current-status' : ''}" data-id="${baseId}" data-status="cancelled">Cancel</button>
</div>
<button class="btn-admin-action btn-admin-toggle-featured" data-id="${baseId}">${event.featured ? '★ Unpin' : '☆ Pin'}</button>
<button class="btn-admin-action btn-admin-delete" data-id="${baseId}">Delete</button>
</div>` : '';
const commentsHtml = comments.map(c => {
if (typeof c === 'string') return `<div class="comment"><span class="comment-anon">Anonymous</span> ${sanitize(c)}</div>`;
return `<div class="comment"><span class="comment-author">${sanitize(c.name || 'Anonymous')}</span> ${sanitize(c.text)}</div>`;
}).join('');
const dateDisplay = event.endTime
? `${sanitize(formatDate(event.date, event.time))} β ${sanitize(formatTime(event.endTime))}`
: sanitize(formatDate(event.date, event.time));
return `
<article class="event-card${event.featured ? ' featured' : ''}${event.status !== 'active' ? ' status-' + event.status : ''}" data-cat-slug="${catSlug}" data-event-date="${event.date}">
<div class="card-inner">
${adminControls}
${creatorControls}
${event.image ? `<img src="${event.image}" class="event-image" alt="${sanitize(event.name)}" loading="lazy">` : ''}
<div class="card-top">
<div class="card-badges">
<span class="cat-pill">${sanitize(event.category)}</span>
${event.recurring !== 'none' ? `<span class="recurring-tag">${event.recurring === 'weekly' ? 'Weekly' : 'Monthly'}</span>` : ''}
${event.featured ? `<span class="featured-tag">★ Featured</span>` : ''}
${distanceBadge}
<div class="weather-badge" hidden></div>
</div>
<span class="event-date-str">${dateDisplay}</span>
</div>
<h3 class="event-title" data-modal-id="${baseId}" tabindex="0" role="button" aria-label="View details for ${sanitize(event.name)}">${sanitize(event.name)}</h3>
<div class="event-meta">
${event.location ? `<span class="meta-item"><span class="meta-label">Where:</span> ${sanitize(event.location)}</span>` : ''}
${event.organizer ? `<span class="meta-item"><span class="meta-label">Contact:</span> ${sanitize(event.organizer)}</span>` : ''}
</div>
${event.description ? `<div class="event-desc">${renderMarkdown(event.description)}</div>` : ''}
${event.status === 'cancelled' ? `<div class="status-banner status-cancelled">This event has been cancelled.</div>` : ''}
${event.status === 'postponed' ? `<div class="status-banner status-postponed">This event has been postponed \u2014 check back for updates.</div>` : ''}
<div class="card-actions">
<div class="attend-group">
<button class="btn-attend going" data-id="${baseId}">✓ Going <span class="attend-count">${event.going}</span></button>
<button class="btn-attend maybe" data-id="${baseId}">? Maybe <span class="attend-count">${event.maybe}</span></button>
<button class="btn-attend went" data-id="${baseId}">★ I Went <span class="attend-count">${event.went}</span></button>
</div>
<div class="util-group">
<button class="btn-util share" data-id="${baseId}">Share</button>
<button class="btn-util calendar" data-id="${baseId}">+ ICS</button>
<a class="btn-util gcal" href="${buildGoogleCalURL(event)}" target="_blank" rel="noopener">+ Google Cal</a>
<button class="btn-util share-img" data-id="${baseId}">Get Image</button>
<button class="btn-util report" data-id="${baseId}">Report</button>
</div>
</div>
<details class="comments-wrap">
<summary class="comments-toggle">Comments (${commentCount})</summary>
<div class="comments-list" id="comments-${domId}">${commentsHtml}</div>
<div class="comment-row">
<input type="text" class="comment-name-input" placeholder="Your name\u2026" aria-label="Your name">
<div class="comment-row-inputs">
<input type="text" class="comment-input" id="comment-input-${domId}"
placeholder="Add a comment\u2026" aria-label="Add a comment to ${sanitize(event.name)}">
<button class="btn-post-comment add-comment" data-id="${baseId}" data-dom-id="${domId}">Post</button>
</div>
</div>
</details>
</div>
</article>`;
}
function displayEvents(events, resetPage = true) {
const list = document.getElementById('event-list');
const noEvents = document.getElementById('no-events');
const count = document.getElementById('event-count');
if (resetPage) eventsPage = 1;
const visible = events.slice(0, eventsPage * PAGE_SIZE);
const hasMore = events.length > visible.length;
list.innerHTML = visible.length === 0 ? '' : visible.map(ev => renderEventCard(ev)).join('');
let loadMoreRow = document.getElementById('load-more-row');
if (hasMore) {
if (!loadMoreRow) {
loadMoreRow = document.createElement('div');
loadMoreRow.id = 'load-more-row';
loadMoreRow.className = 'load-more-row';
list.after(loadMoreRow);
}
loadMoreRow.hidden = false;
loadMoreRow.innerHTML = `<button class="btn-load-more" id="btn-load-more">Load more (${events.length - visible.length} remaining)</button>`;
loadMoreRow.dataset.allIds = JSON.stringify(events.map(e => e.id));
} else if (loadMoreRow) {
loadMoreRow.hidden = true;
}
noEvents.hidden = events.length > 0;
count.textContent = events.length > 0 ? `${events.length} event${events.length !== 1 ? 's' : ''}` : '';
if (map) updateMap(events);
if (!weatherData) {
fetchWeather().then(() => injectWeather());
} else {
injectWeather();
}
}
function displayPastEvents() {
const past = getPastEvents();
const sec = document.getElementById('past-events-section');
const list = document.getElementById('past-event-list');
if (past.length === 0) { sec.hidden = true; return; }
sec.hidden = false;
list.innerHTML = past.map(ev => renderEventCard(ev, true)).join('');
}
function displayPendingEvents() {
const sec = document.getElementById('pending-section');
const list = document.getElementById('pending-list');
const count = document.getElementById('pending-count');
if (!sec) return;
if (!isAdminMode() || pendingEventsCache.length === 0) {
sec.hidden = true;
return;
}
sec.hidden = false;
if (count) count.textContent = `${pendingEventsCache.length} awaiting approval`;
list.innerHTML = pendingEventsCache.map(ev => {
const catSlug = CATEGORY_SLUGS[ev.category] || 'community-civic';
return `
<article class="event-card pending-card" data-cat-slug="${catSlug}">
<div class="card-inner">
<div class="pending-badge">● Pending Review</div>
<div class="card-top">
<div class="card-badges">
<span class="cat-pill">${sanitize(ev.category)}</span>
</div>
<span class="event-date-str">${sanitize(formatDate(ev.date, ev.time))}</span>
</div>
<h3 class="event-title-plain">${sanitize(ev.name)}</h3>
<div class="event-meta">
${ev.location ? `<span class="meta-item"><span class="meta-label">Where:</span> ${sanitize(ev.location)}</span>` : ''}
${ev.organizer ? `<span class="meta-item"><span class="meta-label">Contact:</span> ${sanitize(ev.organizer)}</span>` : ''}
</div>
${ev.description ? `<div class="event-desc">${renderMarkdown(ev.description)}</div>` : ''}
<div class="pending-actions">
<button class="btn-approve-event" data-id="${ev.id}">✓ Approve</button>
<button class="btn-reject-event" data-id="${ev.id}">✕ Reject</button>
</div>
</div>
</article>`;
}).join('');
}
function displayTodayBanner() {
const banner = document.getElementById('today-banner');
if (!banner) return;
const todayStr = new Date().toISOString().split('T')[0];
const events = getAllEvents().filter(ev => ev.date === todayStr && ev.status !== 'cancelled');
if (events.length === 0) { banner.hidden = true; return; }
banner.hidden = false;
const rows = events.map(ev => {
const color = getCategoryColors()[ev.category] || '#4f7c5a';
return `<div class="today-event-row" data-modal-id="${ev.id}">
<span class="today-event-dot" style="background:${color}"></span>
<span class="today-event-name">${sanitize(ev.name)}</span>
${ev.time ? `<span class="today-event-time">${formatTime(ev.time)}</span>` : ''}
${ev.location ? `<span class="today-event-loc">${sanitize(ev.location)}</span>` : ''}
</div>`;
}).join('');
banner.innerHTML = `<div class="today-banner-heading">π Happening Today</div><div class="today-event-list">${rows}</div>`;
}
/* ββ View Switching ββββββββββββββββββββββββββββββββββββββββ */
function switchView(view) {
currentView = view;
const listEl = document.getElementById('event-list');
const noEvents = document.getElementById('no-events');
const calView = document.getElementById('calendar-view');
const btnList = document.getElementById('btn-view-list');
const btnCal = document.getElementById('btn-view-calendar');
if (view === 'calendar') {
listEl.hidden = true;
noEvents.hidden = true;
calView.hidden = false;
btnList.classList.remove('active'); btnList.setAttribute('aria-pressed', 'false');
btnCal.classList.add('active'); btnCal.setAttribute('aria-pressed', 'true');
renderCalendar(calendarYear, calendarMonth);
} else {
calView.hidden = true;
listEl.hidden = false;
btnList.classList.add('active'); btnList.setAttribute('aria-pressed', 'true');
btnCal.classList.remove('active'); btnCal.setAttribute('aria-pressed', 'false');