-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2147 lines (1885 loc) · 91.5 KB
/
app.js
File metadata and controls
2147 lines (1885 loc) · 91.5 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
/* ═══════════════════════════════════════════════════════════════
Haven — Luxury Cruise Companion
Norwegian Luna · April 4–11, 2026 · Suite 12846
═══════════════════════════════════════════════════════════════ */
'use strict';
// ─── State ───────────────────────────────────────────────────────
const state = {
view: 'pin', // 'pin' | 'main'
pin: '',
activeTab: 'today',
who: null, // 'fred' | 'holly' — who logged in
};
// ─── Content ──────────────────────────────────────────────────────
let itinerary = null;
let gfGuide = null;
let ports = null;
let spa = null;
let entertainment = null;
let tips = null;
let navigation = null;
let surprises = null;
let dailyBriefing = null;
let emergency = null;
let packing = null;
let moments = null;
let butler = null;
// ─── Connectivity State ───────────────────────────────────────────
let _isOnline = navigator.onLine;
function updateConnectivityState(online) {
const wasOnline = _isOnline;
_isOnline = online;
renderOfflineBanner();
if (online && !wasOnline) {
// Reconnected — trigger background sync
triggerContentSync();
}
}
function triggerContentSync() {
if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage({ type: 'SYNC_CONTENT' });
}
}
function renderOfflineBanner() {
let banner = document.getElementById('offline-banner');
if (!_isOnline) {
if (!banner) {
banner = document.createElement('div');
banner.id = 'offline-banner';
banner.innerHTML = '📵 Offline mode — all content available from cache';
document.body.appendChild(banner);
}
banner.style.display = 'flex';
} else {
if (banner) banner.style.display = 'none';
}
}
window.addEventListener('online', () => updateConnectivityState(true));
window.addEventListener('offline', () => updateConnectivityState(false));
// ─── Sailing Constants ────────────────────────────────────────────
const SAIL_DATE = new Date('2026-04-04T11:00:00-05:00'); // Miami ET
const RETURN_DATE = new Date('2026-04-11T07:00:00-05:00');
// Haven AI endpoint (Cloudflare Pages Function)
// ─── Venue Locations ──────────────────────────────────────────────
const VENUE_LOCATIONS = {
// ── The Haven (Deck 16, aft) ──────────────────────────────────────
'The Haven Restaurant': 'Deck 16, Aft (Haven exclusive)',
'Haven Restaurant': 'Deck 16, Aft (Haven exclusive)',
'Haven Pool': 'Deck 16, Aft (Haven exclusive)',
'Haven Sundeck': 'Deck 16, Aft (Haven exclusive)',
'Haven Lounge': 'Deck 16, Aft (Haven exclusive)',
'Haven Lounge & Bar': 'Deck 16, Aft (Haven exclusive)',
"Bull's Eye Bar": 'Deck 16, Aft (Haven exclusive)',
"The Bull's Eye Bar": 'Deck 16, Aft (Haven exclusive)',
'Haven Concierge': 'Deck 16, Aft (Haven exclusive)',
// ── Deck 6 (Casino, bars, Hasuki, Improv) ────────────────────────
'Casino': 'Deck 6, Midship (Penrose Atrium)',
'Hasuki': 'Deck 6, Midship',
'Whiskey Bar': 'Deck 6, Midship (Atrium)',
'Swirl Wine Bar': 'Deck 6, Midship',
'Penrose Bar': 'Deck 6, Midship (Atrium)',
'Improv at Sea': 'Deck 6, Forward (comedy club)',
'Improv at Sea Comedy Club': 'Deck 6, Forward (comedy club)',
'Commodore Room': 'Deck 6, Midship (main dining room)',
// ── Deck 7 (specialty dining, Atrium, shops, Syd Norman's) ───────
'Starbucks': 'Deck 7, Midship (Penrose Atrium)',
'Starbucks®': 'Deck 7, Midship (Penrose Atrium)',
"Cagney's Steakhouse": 'Deck 7, Forward',
"Cagney's": 'Deck 7, Forward',
'Le Bistro': 'Deck 7, Forward',
'Nama': 'Deck 7, Midship',
'Nama Sushi': 'Deck 7, Midship',
"Syd Norman's": 'Deck 7, Midship',
"Syd Norman's Pour House": 'Deck 7, Midship',
'Metropolitan Bar': 'Deck 7, Aft',
'Guest Services': 'Deck 7, Midship (Penrose Atrium)',
'Shore Excursions': 'Deck 7, Midship (Penrose Atrium)',
'Hudson\'s': 'Deck 7, Aft (main dining room)',
// ── Deck 8 (Ocean Boulevard, Indulge, specialty dining) ──────────
'Indulge Food Hall': 'Deck 8, Aft (Ocean Boulevard)',
'The Local': 'Deck 8, Midship (Ocean Boulevard)',
'The Local Bar & Grill': 'Deck 8, Midship (Ocean Boulevard)',
'Los Lobos': 'Deck 8, Midship (Ocean Boulevard)',
'Onda by Scarpetta': 'Deck 8, Midship (Ocean Boulevard)',
// ── Deck 15 (Mandara Spa, fitness, Haven elevator) ───────────────
'Mandara Spa': 'Deck 15, Forward',
'Mandara Spa & Salon': 'Deck 15, Forward',
'Thermal Suite': 'Deck 15, Forward (inside Mandara Spa)',
'Pulse Fitness Center': 'Deck 15, Forward',
'Splash Academy': 'Deck 15, Midship (kids club)',
// ── Deck 17 (pools, Observation Lounge, specialty dining) ────────
'Main Pool': 'Deck 17, Midship',
'Waves Pool Bar': 'Deck 17, Midship',
'Surfside Café': 'Deck 17, Midship',
'Observation Lounge': 'Deck 17, Forward',
'Palomar': 'Deck 17, Midship (Mediterranean specialty)',
'Sukhothai': 'Deck 17, Midship (Thai specialty)',
'Vibe Beach Club': 'Deck 17 (adults-only, paid access)',
// ── Upper decks ──────────────────────────────────────────────────
'Aqua SlideCoaster': 'Decks 18–20, Aft-midship',
'Bullseye Bar': 'Deck 18, Aft',
"Bull's Eye Bar (Sports)": 'Deck 18, Aft',
};
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
}
// ─── Surprises Storage Helpers ────────────────────────────────────
function getSurprises() {
try {
return JSON.parse(localStorage.getItem('haven_surprises') || '[]');
} catch { return []; }
}
function saveSurprises(arr) {
localStorage.setItem('haven_surprises', JSON.stringify(arr));
}
function initSurprisesStorage() {
if (!surprises || !surprises.surprises) return;
// Merge: add any IDs from surprises.json not already in localStorage
const existing = JSON.parse(localStorage.getItem('haven_surprises') || '[]');
const existingIds = new Set(existing.map(s => s.id));
const newEntries = surprises.surprises
.filter(s => !existingIds.has(s.id))
.map(s => ({
id: s.id,
title: s.icon ? `${s.icon} ${s.title}` : s.title,
message: s.message,
scheduledAt: `${s.date}T${s.time}:00`,
shown: false
}));
if (newEntries.length > 0) {
localStorage.setItem('haven_surprises', JSON.stringify([...existing, ...newEntries]));
}
}
// Measure actual header height and set CSS variable for sticky nav-tabs offset
function updateHeaderOffset() {
const header = document.querySelector('.app-header');
if (header) {
document.documentElement.style.setProperty('--header-height', header.offsetHeight + 'px');
}
}
window.addEventListener('resize', updateHeaderOffset);
function linkVenueNames(html) {
// Sort by length desc so longer names match first ("Onda by Scarpetta" before "Onda")
const sorted = Object.keys(VENUE_LOCATIONS).sort((a, b) => b.length - a.length);
for (const venue of sorted) {
const loc = VENUE_LOCATIONS[venue];
// Match the HTML-escaped version of the venue name (since html is already escaped)
const htmlEncodedVenue = escapeHtml(venue);
const escaped = htmlEncodedVenue.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
html = html.replace(new RegExp(escaped, 'g'),
`<span class="venue-link" data-location="${escapeHtml(loc)}">${venue} 📍</span>`);
}
return html;
}
// ─── Venue Lookup FAB ─────────────────────────────────────────────
function addVenueFAB() {
if (document.getElementById('venue-fab')) return; // no duplicates
const fab = document.createElement('button');
fab.id = 'venue-fab';
fab.className = 'venue-fab';
fab.innerHTML = '📍';
fab.title = 'Find a venue';
fab.setAttribute('aria-label', 'Find a venue');
fab.onclick = showVenueLookup;
document.body.appendChild(fab);
}
function showVenueLookup() {
document.querySelectorAll('.venue-lookup-overlay').forEach(e => e.remove());
// Build venue list from navigation.json venues array
const venues = navigation?.venues || [];
const overlay = document.createElement('div');
overlay.className = 'venue-lookup-overlay';
overlay.innerHTML = `
<div class="venue-lookup-backdrop" onclick="this.closest('.venue-lookup-overlay').remove()"></div>
<div class="venue-lookup-sheet">
<div class="venue-lookup-header">
<span class="venue-lookup-title">📍 Find a Venue</span>
<button class="venue-lookup-close" onclick="this.closest('.venue-lookup-overlay').remove()">✕</button>
</div>
<div class="venue-lookup-search-wrap">
<input type="text" class="venue-lookup-search" placeholder="Search venues…" autocomplete="off" autocorrect="off" spellcheck="false">
</div>
<div class="venue-lookup-list" id="venue-lookup-list"></div>
</div>
`;
document.body.appendChild(overlay);
// Populate and filter
const listEl = overlay.querySelector('#venue-lookup-list');
const searchEl = overlay.querySelector('.venue-lookup-search');
function renderVenueList(filter) {
const q = (filter || '').toLowerCase().trim();
const filtered = venues
.filter(v => !q || (v.name || '').toLowerCase().includes(q))
.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
if (!filtered.length) {
listEl.innerHTML = '<div class="venue-lookup-empty">No venues found</div>';
return;
}
listEl.innerHTML = filtered.map(v => `
<div class="venue-lookup-item" data-venue-id="${escapeHtml(v.id || v.name)}">
<div class="venue-lookup-name">${escapeHtml(v.name || '')}</div>
<div class="venue-lookup-deck">${escapeHtml(v.deck ? 'Deck ' + v.deck : (v.location || ''))}</div>
</div>
`).join('');
// Tap to show directions
listEl.querySelectorAll('.venue-lookup-item').forEach(item => {
item.addEventListener('click', () => {
const venueName = item.querySelector('.venue-lookup-name').textContent;
const venue = venues.find(v => v.name === venueName);
if (venue) showVenueDetail(venue, overlay);
});
});
}
renderVenueList('');
searchEl.addEventListener('input', e => renderVenueList(e.target.value));
// Auto-focus search on desktop
setTimeout(() => searchEl.focus(), 100);
}
function showVenueDetail(venue, overlayEl) {
const sheet = overlayEl.querySelector('.venue-lookup-sheet');
const fromSuite = venue.directions_from_suite || '';
const toSuite = venue.directions_to_suite || '';
sheet.innerHTML = `
<div class="venue-lookup-header">
<button class="venue-lookup-back" onclick="showVenueLookup(); this.closest('.venue-lookup-overlay').remove()">← Back</button>
<button class="venue-lookup-close" onclick="this.closest('.venue-lookup-overlay').remove()">✕</button>
</div>
<div class="venue-detail-content">
<h2 class="venue-detail-name">${escapeHtml(venue.name || '')}</h2>
<div class="venue-detail-deck">📍 ${escapeHtml(venue.deck ? 'Deck ' + venue.deck : (venue.location || ''))}</div>
${venue.description ? `<p class="venue-detail-desc">${escapeHtml(venue.description)}</p>` : ''}
${fromSuite ? `
<div class="venue-detail-dir">
<div class="venue-dir-label">From Suite 12846</div>
<div class="venue-dir-text">${escapeHtml(fromSuite)}</div>
</div>` : ''}
${toSuite ? `
<div class="venue-detail-dir">
<div class="venue-dir-label">Back to Suite</div>
<div class="venue-dir-text">${escapeHtml(toSuite)}</div>
</div>` : ''}
</div>
`;
}
// ─── PIN Auth ─────────────────────────────────────────────────────
const PINS = { '1313': 'fred', '1009': 'holly', '0405': 'holly' };
function handlePinInput(digit) {
if (state.pin.length >= 4) return;
state.pin += digit;
renderPinDots();
if (state.pin.length === 4) {
setTimeout(checkPin, 80);
}
}
function handlePinBack() {
if (state.pin.length > 0) {
state.pin = state.pin.slice(0, -1);
renderPinDots();
}
}
function checkPin() {
const who = PINS[state.pin];
if (who) {
state.who = who;
sessionStorage.setItem('haven_view', 'main');
sessionStorage.setItem('haven_who', who);
navigateTo('main');
} else {
shakePinDisplay();
document.getElementById('pin-error').textContent = 'Try again';
document.getElementById('pin-error').classList.add('visible');
setTimeout(() => {
state.pin = '';
renderPinDots();
document.getElementById('pin-error').classList.remove('visible');
}, 500);
}
}
function renderPinDots() {
const dots = document.querySelectorAll('.pin-dot');
dots.forEach((dot, i) => {
dot.classList.toggle('filled', i < state.pin.length);
});
}
function shakePinDisplay() {
const dotsEl = document.getElementById('pin-dots-row');
dotsEl.classList.remove('shake');
void dotsEl.offsetWidth;
dotsEl.classList.add('shake');
}
// ─── Navigation ───────────────────────────────────────────────────
function navigateTo(view) {
state.view = view;
document.querySelectorAll('.screen').forEach(s => s.classList.remove('active'));
if (view === 'pin') {
document.getElementById('pin-screen').classList.add('active');
state.pin = '';
state.who = null;
sessionStorage.removeItem('haven_view');
sessionStorage.removeItem('haven_who');
// Remove surprises tab from DOM so it doesn't persist across logins
const existingTab = document.querySelector('[data-tab="surprises"]');
if (existingTab) existingTab.remove();
const existingPanel = document.getElementById('tab-surprises');
if (existingPanel) existingPanel.remove();
renderPinDots();
return;
}
if (view === 'main') {
document.getElementById('main-screen').classList.add('active');
renderMainView();
renderOfflineBanner();
return;
}
}
// ─── Content Loading ──────────────────────────────────────────────
async function loadContent() {
try {
const [itin, gf, p, s, ent, t, nav, surp, brief, emerg, pack, mom, btlr] = await Promise.all([
fetch('content/itinerary.json').then(r => r.json()),
fetch('content/gf-guide.json').then(r => r.json()),
fetch('content/ports.json').then(r => r.json()),
fetch('content/spa.json').then(r => r.json()),
fetch('content/entertainment.json').then(r => r.json()),
fetch('content/tips.json').then(r => r.json()),
fetch('content/navigation.json').then(r => r.json()),
fetch('content/surprises.json').then(r => r.json()).catch(() => null),
fetch('content/daily-briefing.json').then(r => r.json()).catch(() => null),
fetch('content/emergency.json').then(r => r.json()).catch(() => null),
fetch('content/packing.json').then(r => r.json()).catch(() => null),
fetch('content/moments.json').then(r => r.json()).catch(() => null),
fetch('content/butler.json').then(r => r.json()).catch(() => null),
]);
itinerary = itin;
gfGuide = gf;
ports = p;
spa = s;
entertainment = ent;
tips = t;
navigation = nav;
surprises = surp;
initSurprisesStorage();
dailyBriefing = brief;
emergency = emerg;
packing = pack;
moments = mom;
butler = btlr;
} catch (err) {
console.warn('Content load error:', err);
}
}
// ─── Date Utilities ───────────────────────────────────────────────
function getTodayDayIndex() {
const now = new Date();
// Compare calendar dates (local), not elapsed milliseconds.
// This avoids off-by-one errors when the device clock is less than
// 24 hours past the sail departure time (e.g. 10am the next morning).
const sailCal = new Date(SAIL_DATE.getFullYear(), SAIL_DATE.getMonth(), SAIL_DATE.getDate());
const nowCal = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const diff = Math.round((nowCal - sailCal) / (1000 * 60 * 60 * 24));
if (diff < 0 || diff > 7) return -1;
return diff;
}
function formatDate(dateStr) {
const parts = dateStr.match(/(\w+)\s+(\d+)/);
if (!parts) return dateStr;
const d = new Date(`${parts[1]} ${parts[2]}, 2026`);
return d.toLocaleDateString('en-US', { month: 'long', day: 'numeric', weekday: 'long' });
}
function getSailing() {
const now = new Date();
const msUntil = SAIL_DATE - now;
if (msUntil <= 0) {
const msInto = now - SAIL_DATE;
const msRemaining = RETURN_DATE - now;
if (msRemaining <= 0) return { status: 'complete', text: 'Cruise complete — welcome home!' };
const daysRemaining = Math.ceil(msRemaining / (1000 * 60 * 60 * 24));
return { status: 'sailing', text: `Day ${getTodayDayIndex() + 1} of cruise · ${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining` };
}
const days = Math.floor(msUntil / (1000 * 60 * 60 * 24));
const hours = Math.floor((msUntil % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
if (days > 0) return { status: 'upcoming', text: `${days} day${days !== 1 ? 's' : ''} until we sail` };
return { status: 'upcoming', text: `${hours} hour${hours !== 1 ? 's' : ''} until we sail!` };
}
function getTimeOfDay() {
const h = new Date().getHours();
if (h < 12) return 'morning';
if (h < 17) return 'afternoon';
return 'evening';
}
function formatTime(t) {
if (!t) return '';
if (t.includes('am') || t.includes('pm')) return t;
return t;
}
function getGFStatus(status) {
const map = {
safe: { emoji: '✅', label: 'GF Safe', cls: 'safe' },
caution: { emoji: '⚠️', label: 'Use Caution', cls: 'caution' },
avoid: { emoji: '🚫', label: 'Avoid', cls: 'avoid' },
};
return map[status] || map.caution;
}
// ─── Main View ───────────────────────────────────────────────────
function renderMainView() {
// Add Surprises tab for Fred only
if (state.who === 'fred') {
const mainTabs = document.getElementById('main-tabs');
if (mainTabs && !document.querySelector('[data-tab="surprises"]')) {
const surpriseTab = document.createElement('button');
surpriseTab.className = 'nav-tab';
surpriseTab.dataset.tab = 'surprises';
surpriseTab.onclick = () => switchFredTab('surprises');
surpriseTab.textContent = '🎁';
mainTabs.appendChild(surpriseTab);
const scrollContent = document.querySelector('.scroll-content');
if (scrollContent && !document.getElementById('tab-surprises')) {
const surprisePanel = document.createElement('div');
surprisePanel.id = 'tab-surprises';
surprisePanel.className = 'tab-panel';
scrollContent.appendChild(surprisePanel);
}
}
}
// Add Pack tab (visible before April 4, 2026)
const now = new Date();
const today = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')}`;
const packHiddenAfter = packing?.hiddenAfter || '2026-04-04';
if (today < packHiddenAfter) {
const mainTabs = document.getElementById('main-tabs');
if (mainTabs && !document.querySelector('[data-tab="pack"]')) {
const tipsTab = document.querySelector('[data-tab="tips"]');
const packTab = document.createElement('button');
packTab.className = 'nav-tab';
packTab.dataset.tab = 'pack';
packTab.onclick = () => switchFredTab('pack');
packTab.textContent = '🧳';
if (tipsTab) {
mainTabs.insertBefore(packTab, tipsTab);
} else {
mainTabs.appendChild(packTab);
}
const scrollContent = document.querySelector('.scroll-content');
if (scrollContent && !document.getElementById('tab-pack')) {
const packPanel = document.createElement('div');
packPanel.id = 'tab-pack';
packPanel.className = 'tab-panel';
scrollContent.appendChild(packPanel);
}
}
}
switchFredTab(state.activeTab);
setupVoice();
setupAskInput();
setupEmergencyTriggers();
addVenueFAB();
// Check surprises for Holly after initial load
if (state.who === 'holly') {
setTimeout(checkAndShowSurprises, 800);
}
}
function switchFredTab(tab) {
state.activeTab = tab;
document.querySelectorAll('.nav-tab').forEach(t => {
t.classList.toggle('active', t.dataset.tab === tab);
});
document.querySelectorAll('.tab-panel').forEach(p => {
p.classList.toggle('active', p.id === `tab-${tab}`);
});
const panel = document.getElementById(`tab-${tab}`);
if (!panel) return;
switch (tab) {
case 'today': renderTodayTab(panel); break;
case 'itinerary': renderItineraryTab(panel); break;
case 'gf': renderGFTab(panel); break;
case 'ports': renderPortsTab(panel); break;
case 'spa': renderSpaTab(panel); break;
case 'entertainment': renderEntertainmentTab(panel); break;
case 'tips': renderTipsTab(panel); break;
case 'decks': renderDeckTab(panel); break;
case 'pack': renderPackingTab(panel); break;
case 'surprises': renderSurprisesAdmin(panel); break;
}
// Check for surprises on Holly's Today tab
if (tab === 'today' && state.who === 'holly') {
setTimeout(checkAndShowSurprises, 500);
}
}
// ─── Surprises ────────────────────────────────────────────────────
function checkAndShowSurprises() {
if (state.who !== 'holly') return;
const now = new Date();
const surpriseList = getSurprises();
const due = surpriseList.filter(s => !s.shown && new Date(s.scheduledAt) <= now);
if (due.length === 0) return;
showSurpriseModal(due[0], due.length);
}
function showSurpriseModal(surprise, remaining) {
document.querySelectorAll('.surprise-modal').forEach(m => m.remove());
const modal = document.createElement('div');
modal.className = 'surprise-modal';
modal.innerHTML = `
<div class="surprise-modal-overlay"></div>
<div class="surprise-modal-card">
${remaining > 1 ? `<div class="surprise-queue">${remaining} surprises waiting</div>` : ''}
<h2 class="surprise-title">${escapeHtml(surprise.title)}</h2>
<p class="surprise-message">${escapeHtml(surprise.message)}</p>
<button class="surprise-dismiss" onclick="dismissSurprise('${escapeHtml(surprise.id)}')">
${remaining > 1 ? 'Next →' : 'Close ✕'}
</button>
</div>
`;
document.body.appendChild(modal);
}
function dismissSurprise(id) {
// Mark shown
const list = getSurprises();
const idx = list.findIndex(s => s.id === id);
if (idx !== -1) { list[idx].shown = true; saveSurprises(list); }
// Remove modal
document.querySelectorAll('.surprise-modal').forEach(m => m.remove());
// Check if more are due
const now = new Date();
const next = getSurprises().find(s => !s.shown && new Date(s.scheduledAt) <= now);
if (next) {
const remaining = getSurprises().filter(s => !s.shown && new Date(s.scheduledAt) <= now).length;
showSurpriseModal(next, remaining);
}
}
// ─── Emergency Overlay ────────────────────────────────────────
let _emergencyPressTimer = null;
function showEmergencyOverlay() {
document.querySelectorAll('.emergency-overlay').forEach(e => e.remove());
if (!emergency) {
// Show placeholder if content not yet loaded
const msg = document.createElement('div');
msg.className = 'emergency-overlay';
msg.innerHTML = `
<div class="emergency-backdrop" onclick="this.closest('.emergency-overlay').remove()"></div>
<div class="emergency-card">
<div class="emergency-header">
<span class="emergency-title">⚠️ Emergency Info</span>
<button class="emergency-close" onclick="this.closest('.emergency-overlay').remove()">✕</button>
</div>
<p style="color:#e0e0e0;padding:16px">Loading emergency info… try again in a moment.</p>
</div>`;
document.body.appendChild(msg);
return;
}
const items = Object.values(emergency).map(item => `
<div class="emergency-item">
<div class="emergency-item-label">${escapeHtml(item.label)}</div>
<div class="emergency-item-value">${escapeHtml(item.value)}</div>
${item.phone ? `<div class="emergency-item-detail">📞 ${escapeHtml(item.phone)}</div>` : ''}
${item.hours ? `<div class="emergency-item-detail">🕐 ${escapeHtml(item.hours)}</div>` : ''}
${item.note ? `<div class="emergency-item-note">${escapeHtml(item.note)}</div>` : ''}
</div>
`).join('');
const overlay = document.createElement('div');
overlay.className = 'emergency-overlay';
overlay.innerHTML = `
<div class="emergency-backdrop" onclick="this.closest('.emergency-overlay').remove()"></div>
<div class="emergency-card">
<div class="emergency-header">
<span class="emergency-title">⚠️ Emergency & Practical Info</span>
<button class="emergency-close" onclick="this.closest('.emergency-overlay').remove()">✕</button>
</div>
<div class="emergency-items">${items}</div>
<div class="emergency-footer">Tap outside to dismiss</div>
</div>`;
document.body.appendChild(overlay);
}
function attachEmergencyTrigger(el) {
if (!el) return;
el.addEventListener('touchstart', () => {
_emergencyPressTimer = setTimeout(showEmergencyOverlay, 600);
}, { passive: true });
el.addEventListener('touchend', () => clearTimeout(_emergencyPressTimer));
el.addEventListener('touchmove', () => clearTimeout(_emergencyPressTimer));
// Desktop: right-click or contextmenu
el.addEventListener('contextmenu', e => { e.preventDefault(); showEmergencyOverlay(); });
}
function addEmergencyButton() {
const headerActions = document.querySelector('.header-actions');
if (!headerActions || document.querySelector('.emergency-btn')) return;
const btn = document.createElement('button');
btn.className = 'emergency-btn';
btn.textContent = '⚠️';
btn.title = 'Emergency Info (long press Haven logo)';
btn.onclick = showEmergencyOverlay;
headerActions.insertBefore(btn, headerActions.firstChild);
}
function setupEmergencyTriggers() {
// Attach long-press to the Haven avatar
const avatar = document.querySelector('.header-avatar');
attachEmergencyTrigger(avatar);
// Also attach to wordmark
const wordmark = document.querySelector('.haven-wordmark-sm');
attachEmergencyTrigger(wordmark);
// Add the always-visible button
addEmergencyButton();
}
function renderSurprisesAdmin(panel) {
const list = getSurprises();
const items = list.length === 0
? '<p class="text-muted" style="text-align:center;padding:20px">No surprises yet. Add one below!</p>'
: list.map(s => {
const dt = new Date(s.scheduledAt);
const dtStr = `${dt.toLocaleDateString('en-US', {month:'short',day:'numeric'})} at ${dt.toLocaleTimeString('en-US', {hour:'numeric',minute:'2-digit'})}`;
const statusPill = s.shown
? '<span style="font-size:0.7rem;color:var(--safe);margin-left:0.5rem">✅ Shown</span>'
: '<span style="font-size:0.7rem;color:var(--gold);margin-left:0.5rem">⏳ Pending</span>';
return `
<div class="surprise-admin-item" id="surprise-item-${escapeHtml(s.id)}">
<div style="display:flex;justify-content:space-between;align-items:flex-start">
<div>
<div class="surprise-admin-meta">${dtStr}${statusPill}</div>
<div class="surprise-admin-title">${escapeHtml(s.title)}</div>
<div class="surprise-admin-msg">${escapeHtml(s.message)}</div>
</div>
<div style="display:flex;gap:0.4rem;flex-shrink:0;margin-left:0.5rem">
<button onclick="editSurprise('${escapeHtml(s.id)}')" style="background:rgba(201,168,76,0.15);border:1px solid rgba(201,168,76,0.4);color:var(--gold);border-radius:6px;padding:4px 8px;font-size:0.75rem;cursor:pointer">✏️</button>
<button onclick="deleteSurprise('${escapeHtml(s.id)}')" style="background:rgba(255,80,80,0.1);border:1px solid rgba(255,80,80,0.3);color:#ff6060;border-radius:6px;padding:4px 8px;font-size:0.75rem;cursor:pointer">🗑</button>
</div>
</div>
</div>`;
}).join('');
panel.innerHTML = `
<div class="section-header"><span class="section-title">Anniversary Surprises</span></div>
<p class="text-muted" style="font-size:0.8rem;margin-bottom:0.75rem">Surprises appear as popups for Holly at the scheduled time.</p>
<div class="surprise-admin-list" id="surprise-admin-list">${items}</div>
<div style="margin-top:1rem">
<button onclick="showAddSurpriseForm()" id="add-surprise-btn" class="surprise-add-btn">+ Add Surprise</button>
</div>
<div id="surprise-form-wrap" style="display:none"></div>
`;
}
function showAddSurpriseForm(existingId) {
const list = getSurprises();
const existing = existingId ? list.find(s => s.id === existingId) : null;
// Default scheduledAt: tomorrow at 09:00 local time
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const defaultDt = `${tomorrow.getFullYear()}-${String(tomorrow.getMonth()+1).padStart(2,'0')}-${String(tomorrow.getDate()).padStart(2,'0')}T09:00`;
const formWrap = document.getElementById('surprise-form-wrap');
const addBtn = document.getElementById('add-surprise-btn');
if (!formWrap) return;
formWrap.style.display = 'block';
if (addBtn) addBtn.style.display = 'none';
formWrap.innerHTML = `
<div class="card" style="margin-top:0.75rem">
<div style="font-weight:600;font-size:0.9rem;margin-bottom:0.75rem;color:var(--gold)">${existing ? 'Edit Surprise' : 'New Surprise'}</div>
<div style="margin-bottom:0.5rem">
<label style="font-size:0.75rem;color:var(--text-muted)">Title</label>
<input id="sf-title" type="text" value="${existing ? escapeHtml(existing.title) : ''}" placeholder="Something special tonight 🌅"
style="width:100%;background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.15);border-radius:6px;padding:6px 10px;color:#e0e0e0;font-size:0.875rem;margin-top:2px;box-sizing:border-box">
</div>
<div style="margin-bottom:0.5rem">
<label style="font-size:0.75rem;color:var(--text-muted)">Message</label>
<textarea id="sf-message" rows="3" placeholder="Your message to Holly..."
style="width:100%;background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.15);border-radius:6px;padding:6px 10px;color:#e0e0e0;font-size:0.875rem;margin-top:2px;box-sizing:border-box;resize:vertical">${existing ? escapeHtml(existing.message) : ''}</textarea>
</div>
<div style="margin-bottom:0.75rem">
<label style="font-size:0.75rem;color:var(--text-muted)">When (local time)</label>
<input id="sf-when" type="datetime-local" value="${existing ? existing.scheduledAt.slice(0,16) : defaultDt}"
style="width:100%;background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.15);border-radius:6px;padding:6px 10px;color:#e0e0e0;font-size:0.875rem;margin-top:2px;box-sizing:border-box">
</div>
<div style="display:flex;gap:0.5rem">
<button onclick="saveSurpriseForm('${existing ? escapeHtml(existing.id) : ''}')"
style="flex:1;background:var(--gold);color:#0a0f18;border:none;border-radius:6px;padding:8px;font-size:0.875rem;font-weight:600;cursor:pointer">
${existing ? 'Save Changes' : 'Add Surprise'}
</button>
<button onclick="cancelSurpriseForm()"
style="background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.15);color:var(--text-muted);border-radius:6px;padding:8px 12px;font-size:0.875rem;cursor:pointer">
Cancel
</button>
</div>
</div>
`;
}
function editSurprise(id) {
showAddSurpriseForm(id);
}
function deleteSurprise(id) {
if (!confirm('Delete this surprise?')) return;
const list = getSurprises().filter(s => s.id !== id);
saveSurprises(list);
const panel = document.getElementById('tab-surprises');
if (panel) renderSurprisesAdmin(panel);
}
function saveSurpriseForm(existingId) {
const title = document.getElementById('sf-title')?.value.trim();
const message = document.getElementById('sf-message')?.value.trim();
const when = document.getElementById('sf-when')?.value; // "YYYY-MM-DDTHH:MM"
if (!title || !message || !when) {
showButlerToast('Please fill in all fields.');
return;
}
const list = getSurprises();
if (existingId) {
const idx = list.findIndex(s => s.id === existingId);
if (idx !== -1) {
list[idx] = { ...list[idx], title, message, scheduledAt: when + ':00' };
}
} else {
list.push({
id: 'surprise-' + Date.now(),
title,
message,
scheduledAt: when + ':00',
shown: false
});
}
saveSurprises(list);
showButlerToast(existingId ? 'Surprise updated ✓' : 'Surprise added ✓');
const panel = document.getElementById('tab-surprises');
if (panel) renderSurprisesAdmin(panel);
}
function cancelSurpriseForm() {
const formWrap = document.getElementById('surprise-form-wrap');
const addBtn = document.getElementById('add-surprise-btn');
if (formWrap) { formWrap.style.display = 'none'; formWrap.innerHTML = ''; }
if (addBtn) addBtn.style.display = 'block';
}
// ─── Morning Briefing ─────────────────────────────────────────────
function getTodayBriefing() {
if (!dailyBriefing || !dailyBriefing.briefings) return null;
const now = new Date();
const todayStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
return dailyBriefing.briefings.find(b => b.date === todayStr) || null;
}
// ─── Couples Moment Prompter ──────────────────────────────────────
function getDailyMoments() {
if (!moments || !moments.moments) return [];
const now = new Date();
const hour = now.getHours();
// Determine time of day
const timeOfDay = hour < 12 ? 'morning' : hour < 17 ? 'afternoon' : 'evening';
// Determine day type from itinerary
const dayIdx = getTodayDayIndex();
const dayType = dayIdx >= 0 && itinerary?.days?.[dayIdx]?.type === 'port' ? 'port' : 'sea';
// Date-seeded deterministic selection — same prompts all day, changes at midnight
const today = `${now.getFullYear()}${String(now.getMonth()+1).padStart(2,'0')}${String(now.getDate()).padStart(2,'0')}`;
const seed = parseInt(today);
function seededRandom(s) { let x = Math.sin(s) * 10000; return x - Math.floor(x); }
// Filter to relevant moments (matching timeOfDay or 'any', matching dayType or 'any')
const eligible = moments.moments.filter(m =>
(m.timeOfDay === timeOfDay || m.timeOfDay === 'any') &&
(m.dayType === dayType || m.dayType === 'any')
);
if (eligible.length === 0) return moments.moments.slice(0, 2); // fallback
// Pick 2 deterministically using seed
const idx1 = Math.floor(seededRandom(seed) * eligible.length);
const idx2 = Math.floor(seededRandom(seed + 1) * eligible.length);
const picks = [eligible[idx1]];
if (idx2 !== idx1) picks.push(eligible[idx2]);
return picks;
}
function renderMomentCards() {
if (state.who !== 'fred') return '';
const picks = getDailyMoments();
if (!picks.length) return '';
const cards = picks.map(m => `
<div class="moment-card" data-id="${escapeHtml(m.id)}">
<div class="moment-icon">💫</div>
<div class="moment-text">${escapeHtml(m.text)}</div>
<button class="moment-dismiss" onclick="this.closest('.moment-card').style.display='none'">
Dismiss
</button>
</div>
`).join('');
return `
<div class="moments-section">
<div class="moments-label">Today's moments</div>
${cards}
</div>
`;
}
function renderMorningBriefing(briefing) {
if (!briefing) return '';
const highlightsHtml = briefing.highlights
.map(h => `<div class="briefing-highlight"><span class="briefing-icon">${h.icon}</span><span>${h.text}</span></div>`)
.join('');
return `
<div class="briefing-card">
<div class="briefing-header">
<span class="briefing-gold-title">Good Morning</span>
<span class="briefing-day-label">${briefing.dayLabel}</span>
</div>
<p class="briefing-greeting">${briefing.greeting}</p>
<div class="briefing-highlights">${highlightsHtml}</div>
${briefing.gfTip ? `<div class="briefing-gf-tip">🌾 <strong>GF:</strong> ${briefing.gfTip}</div>` : ''}
${briefing.reminder ? `<div class="briefing-reminder">📌 ${briefing.reminder}</div>` : ''}
</div>
`;
}
function renderPortCountdown(day) {
if (!day.arrivalTime || !day.allAboardTime) return '';
const now = new Date();
// Build Date objects for arrival and all-aboard (treat as local time)
const [arrHr, arrMin] = day.arrivalTime.split(':').map(Number);
const [aabHr, aabMin] = day.allAboardTime.split(':').map(Number);
const arrival = new Date(now.getFullYear(), now.getMonth(), now.getDate(), arrHr, arrMin, 0);
const allAboard = new Date(now.getFullYear(), now.getMonth(), now.getDate(), aabHr, aabMin, 0);
const msUntilArrival = arrival - now;
const msUntilAllAboard = allAboard - now;
// Format countdown
function fmtMs(ms) {
if (ms <= 0) return null;
const h = Math.floor(ms / 3600000);
const m = Math.floor((ms % 3600000) / 60000);
return h > 0 ? `${h}h ${m}m` : `${m}m`;
}
// All-aboard urgency color
let aabClass = 'port-aab-normal';
if (msUntilAllAboard > 0 && msUntilAllAboard < 3600000) aabClass = 'port-aab-red';
else if (msUntilAllAboard > 0 && msUntilAllAboard < 7200000) aabClass = 'port-aab-amber';
const arrivalStr = fmtMs(msUntilArrival);
const allAboardStr = fmtMs(msUntilAllAboard);
const tenderHtml = day.tender
? `<div class="port-tender-yes">⛵ Tender port — allow extra time back to ship</div>`
: `<div class="port-tender-no">🚢 Docked — easy return, no tender</div>`;
let html = `<div class="port-countdown-card">
<div class="port-countdown-title">📍 ${day.port || day.location || 'Port Day'}</div>
${arrivalStr
? `<div class="port-stat"><span class="port-stat-label">Ship arrives</span><span class="port-stat-value">${day.arrivalTime} (${arrivalStr} from now)</span></div>`
: `<div class="port-stat"><span class="port-stat-label">Ship arrived</span><span class="port-stat-value">${day.arrivalTime} ✅</span></div>`}
<div class="port-stat ${aabClass}"><span class="port-stat-label">All aboard</span><span class="port-stat-value">${day.allAboardTime}${allAboardStr ? ` — ${allAboardStr} remaining` : ' — PASSED'}</span></div>
${tenderHtml}
</div>`;
return html;
}
function renderTodayTab(panel) {
const dayIdx = getTodayDayIndex();
const sailing = getSailing();
const day = (itinerary && dayIdx >= 0) ? itinerary.days[dayIdx] : null;
const briefing = getTodayBriefing();
let html = `
<div class="dashboard-grid">
<div class="dashboard-stat">
<div class="dashboard-stat-label">Suite</div>
<div class="dashboard-stat-value" style="font-size:1rem">12846</div>
<div class="dashboard-stat-sub">Haven King H5</div>
</div>
<div class="dashboard-stat">
<div class="dashboard-stat-label">Status</div>
<div class="dashboard-stat-value" style="font-size:0.85rem;color:var(--text)">${sailing.status === 'sailing' ? '⚓' : '🗓'}</div>
<div class="dashboard-stat-sub">${sailing.text}</div>
</div>
</div>`;
// Morning briefing card (if available for today)
html += renderMorningBriefing(briefing);
// Port day countdown (if port day with arrival/all-aboard times)
if (day) {
html += renderPortCountdown(day);
}
// Sunset golden hour widget (shows within 90 min of sunset)