-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
1741 lines (1565 loc) · 74.8 KB
/
Copy pathscript.js
File metadata and controls
1741 lines (1565 loc) · 74.8 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
/* ============================================
THE SWAN STATION — script.js v8.1
DHARMA Initiative Computing System
============================================ */
(function() {
'use strict';
// ── CONFIG ──
const DEFAULT_MINUTES = 108;
const CORRECT_NUMS = [4,8,15,16,23,42];
const WARN_AT = 4 * 60; // seconds
const STORAGE_KEY = 'swan_v3';
const MUTE_KEY = 'swan_muted_v1';
// ── STATE ──
let totalSeconds = DEFAULT_MINUTES * 60;
let remaining = totalSeconds;
let isRunning = false;
let isFailure = false;
let activeNav = 'home';
let soundEnabled = false;
let muted = false; // user-toggled mute via the timer-frame button
let timerInterval = null;
let beepInterval = null; // plays beep.mp3 every 2s when remaining <= 4:00
let alarmLoopInterval = null; // plays alarm.mp3 every 1.5s when remaining <= 1:00
let alarmLoopRate = 0; // current alarm interval in ms (0 = not running)
// ── DIGIT STATE (alt-style: track current char per tile) ──
const flapState = { m1:'1', m2:'0', m3:'8', s1:'0', s2:'0' };
// ── CHAT STATE (Michael/Walt "hello" sequence) ──
let chatActive = false;
// Chat step transitions:
// 0 = waiting for intro reply ("this is michael", "michael", etc.)
// 1 = waiting for "dad?" reply (yes / son / walt / "are you ok")
// 2 = waiting for "are you alone?" reply (yes / yeah / sure / "i am")
// 3 = any reply triggers the cut-off line ("You need to com…")
// 4 = locked; waiting out the 5s pause before auto-returning to home
let chatStep = 0;
let chatTimeoutId = null;
// ── INVALID INPUT TRACKING ──
// Increments on every unknown command / bad code. Reset on any valid input.
// When it reaches 2, we show the lockout warning screen.
let invalidAttempts = 0;
// ── AUDIO (MP3 samples) ──────────────────────────────────────────────
// All sample files live in assets/. Each gets a pool of Audio objects so
// rapid repeated playback (e.g. fast typing) doesn't get cut off.
const SAMPLE_DEFS = {
tick: { src: 'soundfx/tick.mp3', vol: 0.50, pool: 2 },
beep: { src: 'soundfx/beep.mp3', vol: 0.55, pool: 2 },
alarm: { src: 'soundfx/alarm.mp3', vol: 0.10, pool: 2 },
keyboard: { src: 'soundfx/keyboard.mp3', vol: 0.40, pool: 6 },
reset: { src: 'soundfx/reset.mp3', vol: 0.75, pool: 1 },
shuffle: { src: 'soundfx/shuffle.mp3', vol: 0.75, pool: 1 },
menu: { src: 'soundfx/menu.mp3', vol: 0.75, pool: 1 },
sysfail: { src: 'soundfx/sysfail.mp3', vol: 0.90, pool: 1 },
gear: { src: 'soundfx/gear.mp3', vol: 0.99, pool: 1 },
wrong: { src: 'soundfx/wrong.mp3', vol: 0.45, pool: 2 },
transm: { src: 'soundfx/transm.mp3', vol: 0.50, pool: 6 },
};
const samples = {}; // name -> { pool: [Audio,...], idx, vol }
function preloadSamples() {
Object.entries(SAMPLE_DEFS).forEach(([name, def]) => {
const pool = [];
for (let i = 0; i < def.pool; i++) {
const a = new Audio(def.src);
a.preload = 'auto';
a.volume = def.vol;
pool.push(a);
}
samples[name] = { pool, idx: 0, vol: def.vol };
});
}
function playSample(name) {
if (!soundEnabled || muted) return;
const s = samples[name];
if (!s) return;
const audio = s.pool[s.idx];
s.idx = (s.idx + 1) % s.pool.length;
try {
audio.currentTime = 0;
const p = audio.play();
if (p && typeof p.catch === 'function') p.catch(() => { /* autoplay blocked, ignore */ });
} catch (e) { /* swallow */ }
}
// ── Beep / Alarm loops ─────────────────────────────────────────────
// Mutually exclusive: when alarm kicks in (≤1:00), beep stops.
function startBeepLoop() {
if (beepInterval) return;
playSample('beep');
beepInterval = setInterval(() => playSample('beep'), 2250);
}
function stopBeepLoop() {
if (beepInterval) { clearInterval(beepInterval); beepInterval = null; }
}
function startAlarmLoop(intervalMs) {
intervalMs = intervalMs || 1500;
// If already running at the requested rate, do nothing.
if (alarmLoopInterval && alarmLoopRate === intervalMs) return;
// Rate change: clear and restart at new rate (without an immediate
// double-play if we already started recently).
if (alarmLoopInterval) {
clearInterval(alarmLoopInterval);
alarmLoopInterval = null;
} else {
playSample('alarm');
}
alarmLoopRate = intervalMs;
alarmLoopInterval = setInterval(() => playSample('alarm'), intervalMs);
}
function stopAlarmLoop() {
if (alarmLoopInterval) { clearInterval(alarmLoopInterval); alarmLoopInterval = null; }
alarmLoopRate = 0;
}
// Convenience for callers that need to stop everything (resetTimer, triggerFailure).
function stopAlarm() { stopBeepLoop(); stopAlarmLoop(); }
// Called every second from the timer; picks the right loop for current time.
function updateAudioLoops() {
if (isFailure || remaining <= 0 || muted) {
stopBeepLoop();
stopAlarmLoop();
return;
}
if (remaining <= 10) {
stopBeepLoop();
startAlarmLoop(900);
} else if (remaining <= 60) {
stopBeepLoop();
startAlarmLoop(2200);
} else if (remaining <= WARN_AT) {
stopAlarmLoop();
startBeepLoop();
} else {
stopBeepLoop();
stopAlarmLoop();
}
}
function playFailure() {
if (!soundEnabled || muted) return;
// Play sysfail.mp3 three times, spaced so each clip can finish.
// sysfail.mp3 is ~0.5s; 1.2s spacing gives a clear, dramatic cadence.
playSample('sysfail');
setTimeout(() => playSample('sysfail'), 3200);
setTimeout(() => playSample('sysfail'), 6400);
}
// ─────────────────────────────────────────────────────────────────────
// ═══════════════════════════════════════════════════════════════════
// TYPEWRITER — animated rendering of HTML into a DOM element.
//
// Use `typewriter(el, html, options)` to render `html` into `el` one
// character at a time. HTML tags (e.g. <br>, <span class="...">) are
// inserted instantly; only text content is paced. A blinking ▮ cursor
// follows the typing head while active. Animation is cancellable and
// skippable.
//
// Presets are exposed via `typewriter.modes` — pick by name:
// 'type' — chat-style, slow + punctuation pauses + jitter
// 'stream' — page-loading style, fast + cursor
// 'fast' — quick sweep, almost-instant
// 'still' — no animation, render instantly
// ═══════════════════════════════════════════════════════════════════
// Track the current in-flight animation so it can be cancelled or skipped.
let _twActive = null; // { skip: fn(), cancel: fn() } or null
function typewriterCancel() {
if (_twActive) { _twActive.cancel(); _twActive = null; }
}
function typewriterSkip() {
if (_twActive) { _twActive.skip(); _twActive = null; }
}
function typewriterIsActive() { return !!_twActive; }
// Walk an HTML string and produce a flat ordered sequence of "tokens":
// { type: 'char', char: 'A', parents: [openTag, openTag, ...] } ← paced
// { type: 'tag', html: '<br>', parents: [...] } ← instant
// Each token carries the list of currently-open tags so that on skip
// we can rebuild the final markup faithfully.
function tokenizeHtml(html) {
const tokens = [];
let i = 0;
const openTags = []; // stack of tag-open strings, e.g. ['<span class="text-amber">']
while (i < html.length) {
const ch = html[i];
if (ch === '<') {
// Find matching '>'
const end = html.indexOf('>', i);
if (end === -1) { i = html.length; break; }
const tag = html.substring(i, end + 1);
const isClosing = tag.startsWith('</');
const isSelfClosing = /<(br|hr|img|input|meta|link)\b[^>]*\/?>/i.test(tag) || tag.endsWith('/>');
// For closing tags, pop the open stack BEFORE recording parents,
// so the parents snapshot reflects state AFTER this close.
if (isClosing) openTags.pop();
tokens.push({ type: 'tag', html: tag, parents: openTags.slice() });
if (!isClosing && !isSelfClosing) openTags.push(tag);
i = end + 1;
} else if (ch === '&') {
// HTML entity — treat as a single char unit.
const end = html.indexOf(';', i);
if (end !== -1 && end - i < 10) {
tokens.push({ type: 'char', char: html.substring(i, end + 1), parents: openTags.slice() });
i = end + 1;
} else {
tokens.push({ type: 'char', char: ch, parents: openTags.slice() });
i++;
}
} else if (ch === '\n' || ch === '\r') {
// Preserve as instant content (don't pace whitespace between tags).
tokens.push({ type: 'tag', html: ch, parents: openTags.slice() });
i++;
} else {
tokens.push({ type: 'char', char: ch, parents: openTags.slice() });
i++;
}
}
return tokens;
}
// Pause (extra delay) after certain punctuation, in ms.
function punctuationDelay(ch) {
if (ch === '.' || ch === '?' || ch === '!') return 250;
if (ch === ',' || ch === ';' || ch === ':') return 120;
return 0;
}
function typewriter(element, html, options) {
typewriterCancel();
if (!element) return Promise.resolve();
const opts = Object.assign({
speed: 30,
jitter: 0,
punctuationPause: false,
showCursor: true,
cursorChar: '▮',
scrollEl: null,
tickSound: false,
tickEvery: 3, // play tick sample every Nth char
tickSampleName: 'keyboard',
onComplete: null,
}, options || {});
// 'still' mode shortcut — render instantly with no cursor.
if (opts.speed <= 0) {
element.innerHTML = html;
if (opts.scrollEl) opts.scrollEl.scrollTop = opts.scrollEl.scrollHeight;
if (opts.onComplete) opts.onComplete();
return Promise.resolve();
}
const tokens = tokenizeHtml(html);
let idx = 0;
let cancelled = false;
let timeoutId = null;
let charsSinceTick = 0;
// We build the visible markup as a plain string and assign innerHTML
// each step. The cursor is rendered as a string fragment placed at
// the current insertion point — BEFORE any auto-closing tags — so
// it visually follows the typing head inside the correct span(s).
let visibleHtml = '';
const cursorHtml = opts.showCursor
? `<span class="tw-cursor">${opts.cursorChar}</span>`
: '';
element.innerHTML = cursorHtml; // cursor shown immediately
const scrollFn = () => {
if (opts.scrollEl) opts.scrollEl.scrollTop = opts.scrollEl.scrollHeight;
};
return new Promise(resolve => {
function finish() {
element.innerHTML = html; // ensure exact final state, no cursor
scrollFn();
if (_twActive && _twActive._token === token) _twActive = null;
if (opts.onComplete) opts.onComplete();
resolve();
}
function skip() {
cancelled = true;
if (timeoutId) { clearTimeout(timeoutId); timeoutId = null; }
finish();
}
function cancel() {
cancelled = true;
if (timeoutId) { clearTimeout(timeoutId); timeoutId = null; }
// Leave element in whatever state it is — caller will overwrite.
resolve();
}
const token = {}; // identity object for ownership check
_twActive = { skip, cancel, _token: token };
function render() {
// Compute the closing-tag string for any currently-open parents.
const lastTok = tokens[idx - 1];
const parents = lastTok ? lastTok.parents : [];
const openClosers = parents.map(openTag => {
const m = openTag.match(/^<\s*([a-zA-Z][a-zA-Z0-9]*)/);
return m ? `</${m[1]}>` : '';
}).reverse().join('');
// Cursor sits INSIDE the open span(s), right after the last char.
element.innerHTML = visibleHtml + cursorHtml + openClosers;
scrollFn();
}
function step() {
if (cancelled) return;
// Burn through any tag tokens (instant) until the next char.
while (idx < tokens.length && tokens[idx].type === 'tag') {
visibleHtml += tokens[idx].html;
idx++;
}
if (idx >= tokens.length) { finish(); return; }
const tok = tokens[idx++];
visibleHtml += tok.char;
render();
// Sound — every Nth visible char, and only if the char is printable.
if (opts.tickSound && tok.char && tok.char.trim()) {
charsSinceTick++;
if (charsSinceTick >= opts.tickEvery) {
charsSinceTick = 0;
playSample(opts.tickSampleName);
}
}
let delay = opts.speed;
if (opts.jitter) delay += (Math.random() * 2 - 1) * opts.jitter;
if (opts.punctuationPause) delay += punctuationDelay(tok.char);
if (delay < 1) delay = 1;
timeoutId = setTimeout(step, delay);
}
step();
});
}
// Presets — pass any of these names to setScreen via SCREEN_MODES.
typewriter.modes = {
type: { speed: 40, jitter: 15, punctuationPause: true, showCursor: true, tickSound: true, tickEvery: 1 },
stream: { speed: 10, jitter: 0, punctuationPause: false, showCursor: true, tickSound: false },
fast: { speed: 4, jitter: 0, punctuationPause: false, showCursor: true, tickSound: false },
still: { speed: 0, jitter: 0, punctuationPause: false, showCursor: false, tickSound: false },
};
// Per-screen mode mapping.
// null means "do not touch" (screen handles its own rendering)
const SCREEN_MODES = {
home: 'still',
communication: 'still',
instructions: 'stream',
faq: 'fast',
about: 'fast',
lockout: 'stream',
hello: 'still', // intro line types in; chat replies use 'type' separately
orientation: null,
failure: null,
'failure-end': null,
};
// ── PERSISTENCE ──
function saveState() {
try { localStorage.setItem(STORAGE_KEY, JSON.stringify({ totalSeconds, remaining, isRunning, savedAt: Date.now() })); } catch(e){}
}
function loadState() {
try {
const d = JSON.parse(localStorage.getItem(STORAGE_KEY) || 'null');
if (!d) return;
totalSeconds = d.totalSeconds || DEFAULT_MINUTES*60;
if (d.isRunning && d.savedAt) {
remaining = Math.max(0, (d.remaining||totalSeconds) - Math.floor((Date.now()-d.savedAt)/1000));
} else {
remaining = d.remaining || totalSeconds;
}
isRunning = d.isRunning || false;
} catch(e){}
}
// ── FLIP DIGIT (split-flap: top flap folds down to reveal new digit) ──
function flipDigit(id, newChar) {
const tile = document.getElementById(id);
if (!tile) return;
const topHalf = tile.querySelector('.top-half .digit-text');
const bottomHalf = tile.querySelector('.bottom-half .digit-text');
const flap = tile.querySelector('.flap');
const flapText = flap.querySelector('.digit-text');
// 1. Bottom half immediately shows the NEW digit (revealed as flap falls)
bottomHalf.textContent = newChar;
// 2. Top half shows the NEW digit (it's what's "behind" the flap)
topHalf.textContent = newChar;
// 3. Flap shows the OLD digit and folds down over the top half
flapText.textContent = flapState[id.replace('fd-','')];
// Trigger animation
flap.classList.remove('flipping');
void flap.offsetWidth; // reflow
flap.style.display = 'block';
flap.classList.add('flipping');
setTimeout(() => {
flap.classList.remove('flipping');
flap.style.display = 'none';
}, 500);
flapState[id.replace('fd-','')] = newChar;
}
// ── SHUFFLE ENGINE (Deceleration Roulette) ─────────────────────────
// All tiles spin fast then independently decelerate, each locking at
// its own moment. Used for both reset-to-numbers and failure-to-glyphs.
const TILE_IDS = ['fd-m1','fd-m2','fd-m3','fd-s1','fd-s2'];
const TILE_KEYS = ['m1','m2','m3','s1','s2'];
const DIGIT_CHARS = '0123456789';
// Hieroglyph settle order (show-accurate): 4th → 5th → 2nd → 1st → 3rd
// As tile indices: s1=3, s2=4, m2=1, m1=0, m3=2
const GLYPH_ORDER = [3, 4, 1, 0, 2];
// Real Gardiner signs: S29 cloth, Z7 spiral, U29 fire drill, G1 vulture, Z5 stick
const GLYPH_CHARS = ['𓋴','𓍢','𓍘','𓄿','𓏱'];
// First 3 (minutes): red on dark. Last 2 (seconds): black on red.
const GLYPH_TILE_CLASSES = ['glyph-tile','glyph-tile','glyph-tile','glyph-tile-inv','glyph-tile-inv'];
// Per-glyph sizing classes
const GLYPH_SIZE_CLASSES = ['glyph-s29','glyph-z7','glyph-u29','glyph-g1','glyph-z5'];
// Active shuffle state so we can cancel mid-flight.
let shuffleActive = false;
function randomDigitExcept(except) {
let d;
do { d = DIGIT_CHARS[Math.floor(Math.random() * 10)]; } while (d === except);
return d;
}
// Fast flip — same split-flap mechanic but uses the quicker CSS class.
function shuffleFlip(tile, oldChar, newChar) {
const topHalf = tile.querySelector('.top-half .digit-text');
const bottomHalf = tile.querySelector('.bottom-half .digit-text');
const flap = tile.querySelector('.flap');
const flapText = flap.querySelector('.digit-text');
topHalf.textContent = newChar;
bottomHalf.textContent = newChar;
flapText.textContent = oldChar;
flap.classList.remove('flipping', 'flipping-fast');
void flap.offsetWidth;
flap.style.display = 'block';
flap.classList.add('flipping-fast');
setTimeout(() => {
flap.classList.remove('flipping-fast');
flap.style.display = 'none';
}, 170);
}
// Shuffle to target values with deceleration roulette.
// targets: array of 5 chars. duration: ms. onDone: callback.
function shuffleToValue(targets, duration, onDone) {
shuffleActive = true;
const tiles = TILE_IDS.map(id => document.getElementById(id));
const current = TILE_KEYS.map(k => flapState[k]);
const settled = [false,false,false,false,false];
// Settle order for reset: left to right.
const settleOrder = [0, 1, 2, 3, 4];
const settleSpacing = duration * 0.12;
const settleTimes = [];
settleOrder.forEach((tileIdx, orderIdx) => {
settleTimes[tileIdx] = (duration * 0.45) + orderIdx * settleSpacing;
});
// Repeating shuffle sound.
const shuffleInterval = setInterval(() => playSample('shuffle'), 2000);
playSample('shuffle');
const startTime = Date.now();
tiles.forEach((tile, i) => {
let delay = 80;
function tick() {
if (!shuffleActive) return;
if (settled[i]) return;
const elapsed = Date.now() - startTime;
if (elapsed >= settleTimes[i]) {
// Final flip to target value (uses normal-speed flip for the landing).
shuffleFlip(tile, current[i], targets[i]);
current[i] = targets[i];
flapState[TILE_KEYS[i]] = targets[i];
settled[i] = true;
if (settled.every(Boolean)) {
clearInterval(shuffleInterval);
shuffleActive = false;
if (onDone) setTimeout(onDone, 200);
}
return;
}
const next = randomDigitExcept(current[i]);
shuffleFlip(tile, current[i], next);
current[i] = next;
const progress = elapsed / settleTimes[i];
delay = 80 + Math.pow(progress, 2.5) * 250;
setTimeout(tick, delay);
}
setTimeout(tick, Math.random() * 40);
});
}
// Shuffle to hieroglyphs with deceleration roulette.
// Each tile gets .glyph-tile class the moment it locks.
function shuffleToGlyphs(duration, onDone) {
shuffleActive = true;
const tiles = TILE_IDS.map(id => document.getElementById(id));
const current = TILE_KEYS.map(k => flapState[k]);
const settled = [false,false,false,false,false];
// Settle timing spread across duration in GLYPH_ORDER.
const settleSpacing = (duration * 0.5) / (GLYPH_ORDER.length - 1);
const settleStart = duration * 0.4;
const settleTimes = [];
GLYPH_ORDER.forEach((tileIdx, orderIdx) => {
settleTimes[tileIdx] = settleStart + orderIdx * settleSpacing;
});
// Repeating shuffle sound.
const shuffleInterval = setInterval(() => playSample('shuffle'), 1000);
playSample('shuffle');
const startTime = Date.now();
tiles.forEach((tile, i) => {
let delay = 80;
function tick() {
if (!shuffleActive) return;
if (settled[i]) return;
const elapsed = Date.now() - startTime;
if (elapsed >= settleTimes[i]) {
// Mark this tile with its glyph color class and sizing class.
tile.classList.add(GLYPH_TILE_CLASSES[i], GLYPH_SIZE_CLASSES[i]);
shuffleFlip(tile, current[i], GLYPH_CHARS[i]);
current[i] = GLYPH_CHARS[i];
flapState[TILE_KEYS[i]] = GLYPH_CHARS[i];
settled[i] = true;
if (settled.every(Boolean)) {
clearInterval(shuffleInterval);
shuffleActive = false;
if (onDone) setTimeout(onDone, 200);
}
return;
}
const next = randomDigitExcept(current[i]);
shuffleFlip(tile, current[i], next);
current[i] = next;
const progress = elapsed / settleTimes[i];
delay = 80 + Math.pow(progress, 2.5) * 250;
setTimeout(tick, delay);
}
setTimeout(tick, Math.random() * 40);
});
}
// Cancel any in-flight shuffle (used when resetTimer is called during failure).
function cancelShuffle() {
shuffleActive = false;
}
// Remove per-tile glyph styling.
function clearGlyphTiles() {
TILE_IDS.forEach((id, i) => {
const tile = document.getElementById(id);
if (tile) {
tile.classList.remove('glyph-tile', 'glyph-tile-inv');
GLYPH_SIZE_CLASSES.forEach(c => tile.classList.remove(c));
}
});
}
function renderTime(mins, secs) {
const mm = String(Math.max(0,Math.min(999,mins))).padStart(3,'0');
const ss = String(Math.max(0,Math.min(59,secs))).padStart(2,'0');
const target = { m1:mm[0], m2:mm[1], m3:mm[2], s1:ss[0], s2:ss[1] };
Object.entries(target).forEach(([k,v]) => {
if (flapState[k] !== v) flipDigit('fd-'+k, v);
});
// Alarm visual cue at 4:00 — red pulse on the housing.
// (Audio cues are driven by updateAudioLoops on each timer tick.)
const clock = document.getElementById('flip-clock');
if (remaining <= WARN_AT && remaining > 0 && !isFailure) {
clock.classList.add('timer-alarm');
}
}
function renderTimeDirect(mins, secs) {
// Set without animation (initial load) — update both halves directly
const mm = String(Math.max(0,Math.min(999,mins))).padStart(3,'0');
const ss = String(Math.max(0,Math.min(59,secs))).padStart(2,'0');
['m1','m2','m3'].forEach((k,i) => {
const tile = document.getElementById('fd-'+k);
if (tile) {
tile.querySelectorAll('.digit-text').forEach(el => el.textContent = mm[i]);
flapState[k] = mm[i];
}
});
['s1','s2'].forEach((k,i) => {
const tile = document.getElementById('fd-'+k);
if (tile) {
tile.querySelectorAll('.digit-text').forEach(el => el.textContent = ss[i]);
flapState[k] = ss[i];
}
});
}
// ── TIMER ──
function startTimer() {
if (timerInterval) clearInterval(timerInterval);
isRunning = true;
let lastTick = Date.now();
timerInterval = setInterval(() => {
if (!isRunning) return;
const now = Date.now();
const elapsed = Math.floor((now - lastTick) / 1000);
if (elapsed >= 1) {
remaining = Math.max(0, remaining - elapsed);
lastTick += elapsed * 1000;
renderTime(Math.floor(remaining/60), remaining%60);
// Tick once per real second (collapse if multiple seconds elapsed).
if (remaining > 0 && !isFailure) playSample('tick');
// Manage beep / alarm loops based on remaining time.
updateAudioLoops();
saveState();
if (remaining === 0) { clearInterval(timerInterval); triggerFailure(); }
}
}, 250);
}
function resetTimer(secs) {
clearInterval(timerInterval);
timerInterval = null;
cancelShuffle();
// Cancel any in-flight failure-end stream
if (typeof failureStreamTimeouts !== 'undefined') {
failureStreamTimeouts.forEach(id => clearTimeout(id));
failureStreamTimeouts = [];
}
stopAlarm();
isFailure = false;
totalSeconds = secs !== undefined ? secs : totalSeconds;
remaining = totalSeconds;
document.getElementById('flip-clock').classList.remove('timer-alarm');
clearGlyphTiles();
// Build target digits for the new time.
const mm = String(Math.floor(remaining / 60)).padStart(3, '0');
const ss = String(remaining % 60).padStart(2, '0');
const targets = [mm[0], mm[1], mm[2], ss[0], ss[1]];
document.getElementById('timer-info').textContent =
Math.floor(totalSeconds/60) + ':00 ' + (totalSeconds === DEFAULT_MINUTES*60 ? 'DEFAULT' : 'CUSTOM');
// Deceleration roulette shuffle (~2 seconds), then start the timer.
shuffleToValue(targets, 1200, () => {
saveState();
startTimer();
});
}
// ── FAILURE SEQUENCE ──
function triggerFailure() {
isFailure = true;
stopAlarm();
const clock = document.getElementById('flip-clock');
clock.classList.remove('timer-alarm');
// Deceleration roulette to hieroglyphs (~5 seconds).
// Tiles settle in show-accurate order: s1 → s2 → m2 → m1 → m3.
// Glyphs lock silently in the background; the failure overlay timeline
// below runs in parallel.
shuffleToGlyphs(6200);
// Overlay + glitch + screen swap happen on a fixed timeline alongside the shuffle.
const overlay = document.getElementById('failure-overlay');
// Short delay before overlay so the shuffle is underway and dramatic.
setTimeout(() => { overlay.classList.add('active'); }, 2500);
setTimeout(() => { document.getElementById('monitor-screen').classList.add('glitch'); }, 3000);
playFailure();
setTimeout(() => { setScreen('failure'); }, 4000);
setTimeout(() => {
overlay.classList.remove('active');
document.getElementById('monitor-screen').classList.remove('glitch');
setScreen('failure-end');
}, 11000);
}
// ── SCREEN CONTENT ──
const SCREENS = {
home: () => `
<span class="screen-line text-dim">DHARMA INITIATIVE — SWAN STATION</span>
<span class="screen-line text-dim">COMPUTING SYSTEM v2.01 — READY</span>
<span class="screen-line"> </span>
<span class="screen-line"><span class="screen-prompt">>:</span> SYSTEM ONLINE. ALL FUNCTIONS NOMINAL.</span>
<span class="screen-line"> </span>
<span class="screen-line text-amber">PROTOCOL REMINDER:</span>
<span class="screen-line">Every 108 minutes the button must be pushed. Alarm sounds at 4 minutes. You will have 4 minutes to enter code.</span>
<span class="screen-line"> </span>
<span class="screen-line text-dim">Type a command below, or use ≡ menu.</span>
<span class="screen-line text-dim">home · communication · instructions · orientation · faq</span>
<span class="screen-line"> </span>`,
communication: () => `
<span class="screen-line text-amber">// COMMUNICATION LOG — STATION 3 //</span>
<span class="screen-line text-dim">─────────────────────────────────────</span>
<span class="screen-line"> </span>
<span class="screen-line"><span class="text-dim">[DAY 0001]</span> Kelvin: A new partner. Brother, you'll do.</span>
<span class="screen-line"><span class="text-dim">[DAY 0001]</span> Desmond: Where am I? What is this place?</span>
<span class="screen-line"><span class="text-dim">[DAY 0001]</span> Kelvin: Don't ask questions. Just push the button.</span>
<span class="screen-line"><span class="text-dim">[DAY 0014]</span> Desmond: 4 8 15 16 23 42. Execute.</span>
<span class="screen-line"><span class="text-dim">[DAY 0092]</span> Desmond: What does the button DO, brother?</span>
<span class="screen-line"><span class="text-dim">[DAY 0092]</span> Kelvin: It saves the world.</span>
<span class="screen-line"><span class="text-dim">[DAY 0092]</span> Kelvin: That's all you need to know.</span>
<span class="screen-line"><span class="text-dim">[DAY 0301]</span> Desmond: There's blood on the ceiling.</span>
<span class="screen-line"><span class="text-dim">[DAY 0301]</span> Desmond: Who was here before?</span>
<span class="screen-line"><span class="text-dim">[DAY 0301]</span> Kelvin: Radzinsky. He didn't make it. Don't ask.</span>
<span class="screen-line"><span class="text-dim">[DAY 0824]</span> Desmond: I dreamed of Penny again.</span>
<span class="screen-line"><span class="text-dim">[DAY 1093]</span> Kelvin: I'll be in the jungle. Push the button.</span>
<span class="screen-line"><span class="text-dim">[DAY 1094]</span> <span class="text-red">[KELVIN INMAN — DISCONNECTED]</span></span>
<span class="screen-line"><span class="text-dim">[DAY 1094]</span> <span class="text-red">SYSTEM FAILURE.</span></span>
<span class="screen-line"><span class="text-dim">[DAY 1094]</span> <span class="text-amber">[ANOMALY DETECTED — 09:16:00]</span></span>
<span class="screen-line"><span class="text-dim">[DAY 1094]</span> Desmond: I killed them. I killed them all.</span>
<span class="screen-line"><span class="text-dim">[DAY 1136]</span> Locke: We came through the ceiling. What does it DO?</span>
<span class="screen-line"><span class="text-dim">[DAY 1136]</span> Jack: Nothing. Push it anyway.</span>
<span class="screen-line"><span class="text-dim">[DAY 1138]</span> <span class="text-red">[ TRANSMISSION ENDS ]</span></span>
<span class="screen-line"> </span><span class="screen-line text-dim">─────────────────────────────────────</span>`,
instructions: () => `
<span class="screen-line text-amber">// STATION PROTOCOL — READ CAREFULLY //</span>
<span class="screen-line"> </span>
<span class="screen-line">Every 108 minutes, the button must be pushed. From the moment the alarm sounds, you will have four minutes to enter the code into the micro-computer processor.</span>
<span class="screen-line"> </span>
<span class="screen-line">Either you or your partners must input the code. It is recommended that you take alternating shifts.</span>
<span class="screen-line"> </span>
<span class="screen-line">On behalf of the DeGroots, Alvar Hanso, and all of us at the DHARMA Initiative — thank you.</span>
<span class="screen-line"> </span>
<span class="screen-line text-amber">NAMASTE. AND GOOD LUCK.</span>
<span class="screen-line"> </span>`,
orientation: () => `
<div class="orient-fullscreen">
<div class="orient-header">
<span class="orient-header-line text-amber">// ORIENTATION FILM — REEL B //</span>
<span class="orient-header-line text-dim">DR. MARVIN CANDLE — DHARMA INITIATIVE</span>
</div>
<button class="orient-exit-btn" id="orient-exit-btn" title="Exit (Esc)">[× EXIT]</button>
<div class="orient-video-wrap">
<video class="orient-video" id="orient-video" autoplay controls playsinline>
<source src="assets/orientation.mp4" type="video/mp4">
</video>
<div class="orient-fallback" id="video-fallback">
<span class="text-red">> REEL NOT FOUND.</span><br>
<span class="text-dim">Upload to /assets/orientation.mp4</span>
</div>
</div>
</div>`,
faq: () => `
<span class="screen-line text-amber">// ABOUT & FAQ //</span>
<span class="screen-line"> </span>
<span class="screen-line text-dim">Q: What is this?</span>
<span class="screen-line">A: A tribute to ABC's LOST and a functional countdown timer.</span>
<span class="screen-line"> </span>
<span class="screen-line text-dim">Q: How do I push the button?</span>
<span class="screen-line">A: Type <span class="text-amber">4 8 15 16 23 42</span> then EXECUTE. Spaces optional.</span>
<span class="screen-line"> </span>
<span class="screen-line text-dim">Q: Custom timer?</span>
<span class="screen-line">A: Click ⚙ near the timer. Any duration in minutes works.</span>
<span class="screen-line"> </span>
<span class="screen-line text-dim">Q: Terminal commands?</span>
<span class="screen-line">A: home · communication · instructions · orientation · faq</span>
<span class="screen-line"> Type and press EXECUTE or Enter.</span>
<span class="screen-line"> </span>
<span class="screen-line text-dim">Q: What if I don't push it?</span>
<span class="screen-line text-red">A: "You know what happens." — Locke</span>
<span class="screen-line"> </span>`,
failure: () => `
<span class="screen-line text-red blink">████ SYSTEM FAILURE ████</span>
<span class="screen-line"> </span>
<span class="screen-line text-red">ELECTROMAGNETIC EVENT DETECTED</span>
<span class="screen-line text-red">CONTAINMENT PROTOCOL BREACHED</span>
<span class="screen-line"> </span>
<span class="screen-line text-amber">𓋴 𓍢 𓍘 𓄿 𓏱</span>
<span class="screen-line"> </span>
<span class="screen-line text-red blink">SYSTEM FAILURE — SYSTEM FAILURE</span>`,
about: () => `
<span class="screen-line text-amber">// ABOUT THIS PROJECT //</span>
<span class="screen-line"> </span>
<span class="screen-line">The LOSTimer is a fan tribute to ABC's <span class="text-amber">LOST</span> (2004–2010) and a working 108-minute countdown timer. Push the button. Or don't.</span>
<span class="screen-line"> </span>
<span class="screen-line text-amber">// WHY THIS EXISTS //</span>
<span class="screen-line"> </span>
<span class="screen-line">LOST is where my love of TV series began. I was watching shows before, but LOST is the one that revolutionized the medium and me. The DHARMA Initiative, the stations, the counter, the mysterious hieroglyphics... they were the fuel to my curiosity.</span>
<span class="screen-line"> </span>
<span class="screen-line">I always wanted to make the counter for myself. Now that I'm vibe coding and building little pages for things I love, I finally got around to it. An old wish, come true.</span>
<span class="screen-line"> </span>
<span class="screen-line text-amber">// CREDITS & INSPIRATIONS //</span>
<span class="screen-line"> </span>
<span class="screen-line"><span class="text-dim">·</span> LOST (2004–2010). J.J. Abrams & Damon Lindelof</span>
<span class="screen-line"><span class="text-dim">·</span> The DHARMA Initiative (for the clip & octagons)</span>
<span class="screen-line"><span class="text-dim">·</span> <a href="https://lostpedia.fandom.com/" target="_blank" rel="noopener">Lostpedia</a> (for reference material)</span>
<span class="screen-line"><span class="text-dim">·</span> Mark Snow's score (had on loop while building this)</span>
<span class="screen-line"> </span>
<span class="screen-line text-amber">// SUPPORT THE PROJECT //</span>
<span class="screen-line"> </span>
<span class="screen-line">The Swan runs on hobby time, not DHARMA funding. If you enjoyed your shift at the button, you can help keep the station supplied:</span>
<span class="screen-line"> </span>
<span class="screen-line"><span class="text-dim">·</span> <a href="https://www.paypal.com/donate/?hosted_button_id=S3BD5XFBMMWSJ" target="_blank" rel="noopener"><svg class="support-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M15.607 4.653H8.941L6.645 19.251H1.82L4.862 0h7.995c3.754 0 6.375 2.294 6.473 5.513-.648-.478-2.105-.86-3.722-.86m6.57 5.546c0 3.41-3.01 6.853-6.958 6.853h-2.493L11.595 24H6.74l1.845-11.538h3.592c4.208 0 7.346-3.634 7.153-6.949a5.24 5.24 0 0 1 2.848 4.686M9.653 5.546h6.408c.907 0 1.942.222 2.363.541-.195 2.741-2.655 5.483-6.441 5.483H8.714Z"/></svg>Donate via PayPal</a></span>
<span class="screen-line"><span class="text-dim">·</span> <a href="https://www.buymeacoffee.com/kiarashfa" target="_blank" rel="noopener"><svg class="support-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M20.216 6.415l-.132-.666c-.119-.598-.388-1.163-1.001-1.379-.197-.069-.42-.098-.57-.241-.152-.143-.196-.366-.231-.572-.065-.378-.125-.756-.192-1.133-.057-.325-.102-.69-.25-.987-.195-.4-.597-.634-.996-.788a5.723 5.723 0 00-.626-.194c-1-.263-2.05-.36-3.077-.416a25.834 25.834 0 00-3.7.062c-.915.083-1.88.184-2.75.5-.318.116-.646.256-.888.501-.297.302-.393.77-.177 1.146.154.267.415.456.692.58.36.162.737.284 1.123.366 1.075.238 2.189.331 3.287.37 1.218.05 2.437.01 3.65-.118.299-.033.598-.073.896-.119.352-.054.578-.513.474-.834-.124-.383-.457-.531-.834-.473-.466.074-.96.108-1.382.146-1.177.08-2.358.082-3.536.006a22.228 22.228 0 01-1.157-.107c-.086-.01-.18-.025-.258-.036-.243-.036-.484-.08-.724-.13-.111-.027-.111-.185 0-.212h.005c.277-.06.557-.108.838-.147h.002c.131-.009.263-.032.394-.048a25.076 25.076 0 013.426-.12c.674.019 1.347.067 2.017.144l.228.031c.267.04.533.088.798.145.392.085.895.113 1.07.542.055.137.08.288.111.431l.319 1.484a.237.237 0 01-.199.284h-.003c-.037.006-.075.01-.112.015a36.704 36.704 0 01-4.743.295 37.059 37.059 0 01-4.699-.304c-.14-.017-.293-.042-.417-.06-.326-.048-.649-.108-.973-.161-.393-.065-.768-.032-1.123.161-.29.16-.527.404-.675.701-.154.316-.199.66-.267 1-.069.34-.176.707-.135 1.056.087.753.613 1.365 1.37 1.502a39.69 39.69 0 0011.343.376.483.483 0 01.535.53l-.071.697-1.018 9.907c-.041.41-.047.832-.125 1.237-.122.637-.553 1.028-1.182 1.171-.577.131-1.165.2-1.756.205-.656.004-1.31-.025-1.966-.022-.699.004-1.556-.06-2.095-.58-.475-.458-.54-1.174-.605-1.793l-.731-7.013-.322-3.094c-.037-.351-.286-.695-.678-.678-.336.015-.718.3-.678.679l.228 2.185.949 9.112c.147 1.344 1.174 2.068 2.446 2.272.742.12 1.503.144 2.257.156.966.016 1.942.053 2.892-.122 1.408-.258 2.465-1.198 2.616-2.657.34-3.332.683-6.663 1.024-9.995l.215-2.087a.484.484 0 01.39-.426c.402-.078.787-.212 1.074-.518.455-.488.546-1.124.385-1.766zm-1.478.772c-.145.137-.363.201-.578.233-2.416.359-4.866.54-7.308.46-1.748-.06-3.477-.254-5.207-.498-.17-.024-.353-.055-.47-.18-.22-.236-.111-.71-.054-.995.052-.26.152-.609.463-.646.484-.057 1.046.148 1.526.22.577.088 1.156.159 1.737.212 2.48.226 5.002.19 7.472-.14.45-.06.899-.13 1.345-.21.399-.072.84-.206 1.08.206.166.281.188.657.162.974a.544.544 0 01-.169.364zm-6.159 3.9c-.862.37-1.84.788-3.109.788a5.884 5.884 0 01-1.569-.217l.877 9.004c.065.78.717 1.38 1.5 1.38 0 0 1.243.065 1.658.065.447 0 1.786-.065 1.786-.065.783 0 1.434-.6 1.499-1.38l.94-9.95a3.996 3.996 0 00-1.322-.238c-.826 0-1.491.284-2.26.613z"/></svg>Buy Me a Coffee</a></span>
<span class="screen-line"> </span>
<span class="screen-line text-amber">// DISCLAIMER //</span>
<span class="screen-line"> </span>
<span class="screen-line text-dim">This is an unofficial fan tribute. Not affiliated with, endorsed by, or sponsored by ABC, Disney, Bad Robot, or the DHARMA Initiative. All trademarks and copyrights belong to their respective owners.</span>
<span class="screen-line"> </span>
<span class="screen-line text-dim">No island was harmed in the making of this site.</span>
<span class="screen-line"> </span>
<span class="screen-line text-dim">─────────────────────────────────────</span>
<span class="screen-line text-amber">Namaste. And good luck.</span>
<span class="screen-line"> </span>
<span class="screen-line text-dim">Type <span class="text-amber">faq</span> for usage details, or <span class="text-amber">home</span> to return to the station.</span>
<span class="screen-line"> </span>`,
'failure-end': () => `<div id="failure-end-content"></div>`,
hello: () => `
<span class="screen-line text-amber">// INCOMING TRANSMISSION //</span>
<span class="screen-line text-dim">─────────────────────────────────────</span>
<span class="screen-line"><span class="text-dim">></span> Hello. Who is this?</span>
<span class="screen-line"> </span>`,
lockout: () => `
<span class="screen-line text-red blink">⚠ WARNING — STATION 3 PROTOCOL ⚠</span>
<span class="screen-line"> </span>
<span class="screen-line">Do <span class="text-red">NOT</span> attempt to use the computer for anything else other than entering the code. This is its <span class="text-amber">ONLY</span> function.</span>
<span class="screen-line"> </span>
<span class="screen-line">The isolation that attends the duties associated with <span class="text-amber">Station 3</span> may tempt you to try and utilise the computer for communication with the outside world.</span>
<span class="screen-line"> </span>
<span class="screen-line">This is <span class="text-red">strictly forbidden</span>. Attempting to use the computer in this manner will compromise the integrity of the project and, worse, could lead to <span class="text-red">another incident</span>.</span>
<span class="screen-line"> </span>
<span class="screen-line">I repeat — <span class="text-red">DO NOT</span> use the computer for anything other than entering the code.</span>
<span class="screen-line"> </span>
<span class="screen-line text-amber">— DHARMA INITIATIVE</span>
<span class="screen-line"> </span>`,
};
function termInputHTML() {
// The prompt and the input live in one unified row. The native browser
// caret (styled via #code-input { caret-color: var(--green); }) acts as
// the visible cursor while the user types.
return `<div class="term-input-row">
<span class="input-prompt">>:</span> <input type="text" id="code-input"
autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"
maxlength="40">
</div>
<div id="term-response"></div>`;
}
function setScreen(key) {
// Cancel any in-flight typewriter animation immediately.
typewriterCancel();
// If we are leaving the hello screen, terminate any active chat session.
if (chatActive && key !== 'hello') endChat();
// If we are leaving the orientation screen, pause any playing video so
// its audio doesn't continue in the background (innerHTML rewrite usually
// handles this but we're being explicit).
if (activeNav === 'orientation' && key !== 'orientation') {
const prevVideo = document.getElementById('orient-video');
if (prevVideo) { try { prevVideo.pause(); } catch(e) {} }
}
activeNav = key;
const fn = SCREENS[key];
const html = fn ? fn() : SCREENS.home();
const screenContent = document.getElementById('screen-content');
// Pick rendering mode for this screen.
const modeName = SCREEN_MODES.hasOwnProperty(key) ? SCREEN_MODES[key] : 'stream';
if (modeName === null) {
// Screen handles its own rendering (orientation, failure-end).
screenContent.innerHTML = html;
} else {
const mode = typewriter.modes[modeName] || typewriter.modes.stream;
const scrollEl = document.getElementById('screen-scroll');
typewriter(screenContent, html, Object.assign({}, mode, { scrollEl }));
}
// Toggle fullscreen-monitor mode for the orientation film.
const monitor = document.getElementById('monitor-screen');
if (monitor) {
monitor.classList.toggle('monitor-fullscreen', key === 'orientation');
}
// Inject input area (except pure failure screen and fullscreen orientation)
const inputArea = document.getElementById('screen-input-area');
if (key === 'failure' || key === 'orientation') {
inputArea.innerHTML = '';
} else {
inputArea.innerHTML = termInputHTML();
}
// Auto-focus input on screen change.
// On touch devices, suppress the OS keyboard so only our virtual keyboard shows.
setTimeout(() => {
const i = document.getElementById('code-input');
if (!i) return;
if (window.matchMedia('(pointer: coarse)').matches) {
i.setAttribute('readonly', '');
i.setAttribute('inputmode', 'none');
}
i.focus();
}, 40);
// Wire orientation fallback + auto-exit on end
if (key === 'orientation') {
const v = document.getElementById('orient-video');
const fb = document.getElementById('video-fallback');
if (v && fb) {
// Hide fallback by default; only show on error / missing file.
fb.style.display = 'none';
v.addEventListener('error', () => {
v.style.display = 'none';
fb.style.display = 'flex';
});
v.addEventListener('ended', () => {
// Brief "transmission complete" beat, then back to home.
if (activeNav !== 'orientation') return;
const wrap = v.closest('.orient-video-wrap');
if (wrap) {
const done = document.createElement('div');
done.className = 'orient-complete';
done.innerHTML = '<span class="text-amber">// TRANSMISSION COMPLETE //</span>';
wrap.appendChild(done);
}
setTimeout(() => {
if (activeNav === 'orientation') setScreen('home');
}, 1800);
});
setTimeout(() => {
if (!v.duration || isNaN(v.duration)) {
v.style.display = 'none';
fb.style.display = 'flex';
}
}, 2000);
}
}
// Stream failure-end lines one by one for dramatic effect
if (key === 'failure-end') {
streamFailureEnd();
}
// Update nav active
document.querySelectorAll('[data-nav]').forEach(el => {
const li = el.closest('li');
if (li) li.classList.toggle('active', el.dataset.nav === key);
});
// Scroll to bottom after render
const scr = document.getElementById('screen-scroll');
if (scr) setTimeout(() => { scr.scrollTop = scr.scrollHeight; }, 30);
}
function printResponse(html) {
const resp = document.getElementById('term-response');
if (resp) {
resp.innerHTML = html;