File size: 38,866 Bytes
79d96da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae4fd15
79d96da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae4fd15
79d96da
ae4fd15
0e2abae
 
 
79d96da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae4fd15
79d96da
ae4fd15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e2abae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79d96da
ae4fd15
79d96da
ae4fd15
 
 
79d96da
ae4fd15
79d96da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae4fd15
 
79d96da
 
 
ae4fd15
79d96da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae4fd15
79d96da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae4fd15
 
 
 
 
 
 
 
 
 
79d96da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e2abae
79d96da
 
 
 
 
 
 
 
 
0e2abae
79d96da
 
 
 
 
0e2abae
 
 
 
 
 
 
79d96da
 
 
 
 
 
 
0e2abae
79d96da
 
 
 
 
0e2abae
79d96da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae4fd15
 
0e2abae
79d96da
ae4fd15
 
79d96da
 
 
 
ae4fd15
0e2abae
ae4fd15
 
79d96da
 
 
 
ae4fd15
0e2abae
79d96da
 
 
 
 
ae4fd15
0e2abae
 
 
 
 
 
 
79d96da
 
ae4fd15
 
 
 
 
0e2abae
 
 
 
ae4fd15
0e2abae
 
 
 
ae4fd15
 
0e2abae
 
 
79d96da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
/* ==========================================================================
   app.js — Player, Web Audio FFT / Beat-Clock Fallback, Lyric Sync & HUD
   ========================================================================== */

(function () {
  'use strict';

  // Built-in fallback dataset (used only if assets/lyrics-sync.js is not yet present)
  const FALLBACK_DATA = {
    title: "I'm The Software Engineer (:q!)",
    artist: 'Lyria 3.5',
    audioFile: 'assets/song.mp3',
    duration: 160.0,
    bpm: 128,
    sections: [
      { id: 'verse1', label: 'Verse 1', start: 0.0, end: 26.0, mood: 'terminal-dark' },
      { id: 'prechorus', label: 'Pre-Chorus', start: 26.0, end: 44.0, mood: 'assembly-heat' },
      { id: 'chorus1', label: 'Chorus', start: 44.0, end: 68.0, mood: 'vibe-glitch' },
      { id: 'verse2', label: 'Verse 2', start: 68.0, end: 94.0, mood: 'manpage-bloat' },
      { id: 'bridge', label: 'Bridge', start: 94.0, end: 116.0, mood: 'synth-arp' },
      { id: 'solo', label: '140 WPM Solo', start: 116.0, end: 138.0, mood: 'mech-140wpm' },
      { id: 'outro', label: 'Outro', start: 138.0, end: 160.0, mood: 'root-micdrop' }
    ],
    lines: [
      { start: 3.0, end: 6.8, section: 'verse1', text: 'Sitting in the dark with the terminal bright', highlight: ['terminal'] },
      { start: 6.8, end: 10.6, section: 'verse1', text: 'Compiling all the kernels in the middle of the night', highlight: ['kernels'] },
      { start: 10.6, end: 14.4, section: 'verse1', text: 'I can write the code by hand using the vi editor', highlight: ['vi'] },
      { start: 14.4, end: 18.2, section: 'verse1', text: "Who said emacs? Come on, don't be a competitor", highlight: ['emacs'] },
      { start: 18.2, end: 22.0, section: 'verse1', text: 'Memorized the flags, :wq to save the day', highlight: [':wq'] },
      { start: 22.0, end: 25.8, section: 'verse1', text: 'Doing everything the old-school, bare-metal way', highlight: ['bare-metal'] },

      { start: 26.2, end: 30.5, section: 'prechorus', text: 'I mastered every pointer, every memory leak', highlight: ['pointer', 'memory leak'] },
      { start: 30.5, end: 34.8, section: 'prechorus', text: 'Optimized the loops so the latency is weak', highlight: ['latency'] },
      { start: 34.8, end: 39.2, section: 'prechorus', text: 'From assembly down to C, yeah, I paid my dues', highlight: ['assembly', 'C'] },
      { start: 39.2, end: 43.8, section: 'prechorus', text: "Now I'm scrolling through my timeline reading tech industry news...", highlight: ['tech industry news'] },

      { start: 44.2, end: 48.0, section: 'chorus1', text: 'Wait—now you say vibe coding? Are you kidding me?', highlight: ['vibe coding'] },
      { start: 48.0, end: 52.0, section: 'chorus1', text: 'Just talking to a prompt and letting AI set you free?', highlight: ['prompt', 'AI'] },
      { start: 52.0, end: 56.0, section: 'chorus1', text: "I'm the software engineer, I built this from the ground", highlight: ['software engineer'] },
      { start: 56.0, end: 60.0, section: 'chorus1', text: 'While you\'re hitting "Tab" to accept whatever\'s found!', highlight: ['Tab'] },
      { start: 60.0, end: 64.0, section: 'chorus1', text: "Yeah, I'm the software engineer, surviving every trend", highlight: ['software engineer'] },
      { start: 64.0, end: 67.8, section: 'chorus1', text: 'From raw Vim macros to whatever comes around the bend!', highlight: ['Vim macros'] },

      { start: 68.2, end: 72.4, section: 'verse2', text: 'Used to read the man pages cover to cover', highlight: ['man pages'] },
      { start: 72.4, end: 76.8, section: 'verse2', text: 'Debugging race conditions like a jealous lover', highlight: ['race conditions'] },
      { start: 76.8, end: 81.0, section: 'verse2', text: 'Now the junior dev is shipping full-stack apps in ten', highlight: ['full-stack'] },
      { start: 81.0, end: 85.4, section: 'verse2', text: 'Saying "Bro, I haven\'t touched a semicolon since when?"', highlight: ['semicolon'] },
      { start: 85.4, end: 89.6, section: 'verse2', text: 'Zero dependencies, single-file clean', highlight: ['Zero dependencies'] },
      { start: 89.6, end: 93.8, section: 'verse2', text: 'While their node_modules folder eats the whole machine', highlight: ['node_modules'] },

      { start: 94.5, end: 99.5, section: 'bridge', text: 'Okay, fine, I tried the prompt... it actually ran', highlight: ['prompt'] },
      { start: 99.5, end: 104.8, section: 'bridge', text: 'Passed the unit tests on the very first scan', highlight: ['unit tests'] },
      { start: 104.8, end: 110.2, section: 'bridge', text: "Maybe there's a place for the machine and the mind", highlight: ['machine', 'mind'] },
      { start: 110.2, end: 115.6, section: 'bridge', text: 'As long as someone knows how it works behind...', highlight: ['works behind'] },

      { start: 116.5, end: 137.5, section: 'solo', text: '[ 140 WPM MECHANICAL KEYBOARD SOLO ]', highlight: ['140 WPM'] },

      { start: 138.2, end: 142.0, section: 'outro', text: "I'm the software engineer!", highlight: ['software engineer'] },
      { start: 142.0, end: 147.2, section: 'outro', text: 'Still got ESC mapped to Caps Lock, crystal clear!', highlight: ['ESC', 'Caps Lock'] },
      { start: 147.2, end: 152.5, section: 'outro', text: "You can keep your vibes, I'll keep my root access right here", highlight: ['root access'] },
      { start: 152.5, end: 156.5, section: 'outro', text: ':q!', highlight: [':q!'] },
      { start: 156.5, end: 159.8, section: 'outro', text: '(Mic drop)', highlight: ['Mic drop'] }
    ]
  };

  const KEYCAP_TOKENS = new Set(['tab', 'esc', 'caps lock', ':wq', ':q!', 'vi', 'emacs', '140 wpm']);

  // Merge loaded window.MUSIC_VIDEO_DATA with fallback safely
  const rawData = window.MUSIC_VIDEO_DATA && typeof window.MUSIC_VIDEO_DATA === 'object'
    ? window.MUSIC_VIDEO_DATA
    : FALLBACK_DATA;

  const DATA = {
    title: rawData.title || FALLBACK_DATA.title,
    artist: rawData.artist || FALLBACK_DATA.artist,
    audioFile: rawData.audioFile || FALLBACK_DATA.audioFile,
    duration: Number(rawData.duration) > 0 ? Number(rawData.duration) : FALLBACK_DATA.duration,
    bpm: Number(rawData.bpm) > 0 ? Number(rawData.bpm) : FALLBACK_DATA.bpm,
    sections: Array.isArray(rawData.sections) && rawData.sections.length > 0 ? rawData.sections : FALLBACK_DATA.sections,
    lines: Array.isArray(rawData.lines) && rawData.lines.length > 0 ? rawData.lines : FALLBACK_DATA.lines
  };

  // Locate the :q! mic-drop line dynamically so visual scenes never hardcode its timestamp
  const QUIT_LINE = DATA.lines.find((l) => l && typeof l.text === 'string' && l.text.toLowerCase().includes(':q!')) || null;

  // DOM Elements
  const canvas = document.getElementById('stage-canvas');
  let audioEl = document.getElementById('audio-player');
  const launchOverlay = document.getElementById('launch-overlay');
  const btnLaunch = document.getElementById('btn-launch');
  const launchNotice = document.getElementById('launch-notice');

  const trackTitleHud = document.getElementById('track-title-hud');
  const sectionLabelHud = document.getElementById('section-label-hud');
  const audioModePill = document.getElementById('audio-mode-pill');
  const bpmPill = document.getElementById('bpm-pill');
  const moodPill = document.getElementById('mood-pill');

  const sectionBanner = document.getElementById('section-banner');
  const lyricPrev = document.getElementById('lyric-prev');
  const lyricCurrent = document.getElementById('lyric-current');
  const lyricCurrentText = lyricCurrent.querySelector('.lyric-text');
  const lyricNext = document.getElementById('lyric-next');

  const sectionPillsEl = document.getElementById('section-pills');
  const timelineWrap = document.getElementById('timeline-wrap');
  const timelineBuffer = document.getElementById('timeline-buffer');
  const timelineProgress = document.getElementById('timeline-progress');
  const timelineMarkers = document.getElementById('timeline-markers');
  const timelineThumb = document.getElementById('timeline-thumb');
  const timelineTooltip = document.getElementById('timeline-tooltip');

  const btnPlay = document.getElementById('btn-play');
  const iconPlay = document.getElementById('icon-play');
  const iconPause = document.getElementById('icon-pause');
  const timeCurrentEl = document.getElementById('time-current');
  const timeDurationEl = document.getElementById('time-duration');
  const miniEqBars = Array.from(document.querySelectorAll('#mini-eq span'));

  const btnMute = document.getElementById('btn-mute');
  const iconVolOn = document.getElementById('icon-vol-on');
  const iconVolOff = document.getElementById('icon-vol-off');
  const volumeSlider = document.getElementById('volume-slider');
  const btnCrt = document.getElementById('btn-crt');
  const btnFullscreen = document.getElementById('btn-fullscreen');

  // Engine & State
  const engine = new window.SceneEngine(canvas);

  const state = {
    launched: false,
    playing: false,
    demoClockMode: false, // Used only if audio file is unavailable
    demoTime: 0,
    lastTick: performance.now(),
    duration: DATA.duration,
    isScrubbing: false,
    activeSectionId: null,
    activeLineIdx: -2,
    prevLineIdx: -2,
    nextLineIdx: -2,
    bannerTimer: null,
    hudTimer: null,
    audioReady: false,

    // Web Audio API
    audioCtx: null,
    analyser: null,
    freqData: null,
    timeData: null,
    fftActive: false,
    fftEverNonZero: false,
    fftZeroSeconds: 0,
    webAudioDisabled: false,
    corsFallbackAttempted: false,
    corsFallbackInProgress: false,
    pendingPlay: false,

    // Reusable reactive audio snapshot passed to SceneEngine
    audioSnapshot: {
      bass: 0,
      mid: 0,
      treble: 0,
      energy: 0,
      peak: 0,
      beatPhase: 0,
      isBeat: false,
      bins: new Float32Array(48),
      waveform: new Float32Array(96)
    }
  };

  /* ------------------------------------------------------------------------
     Helpers
     ------------------------------------------------------------------------ */
  function formatTime(sec) {
    if (!Number.isFinite(sec) || sec < 0) sec = 0;
    const m = Math.floor(sec / 60);
    const s = Math.floor(sec % 60);
    return `${m}:${s < 10 ? '0' : ''}${s}`;
  }

  function escapeHtml(str) {
    return String(str)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }

  function escapeRegex(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  }

  function renderHighlightedLyric(text, highlights) {
    if (!text) return '';
    let safe = escapeHtml(text);
    if (!Array.isArray(highlights) || highlights.length === 0) return safe;

    // Sort longest first to avoid partial nested replacements
    const sorted = [...highlights]
      .filter((h) => typeof h === 'string' && h.trim().length > 0)
      .sort((a, b) => b.length - a.length);

    if (sorted.length === 0) return safe;

    const pattern = sorted.map((h) => escapeRegex(escapeHtml(h.trim()))).join('|');
    const regex = new RegExp(`(${pattern})`, 'gi');

    return safe.replace(regex, (match) => {
      const normalized = match.replace(/&quot;/g, '').replace(/^["']|["']$/g, '').toLowerCase();
      if (KEYCAP_TOKENS.has(normalized)) {
        return `<kbd class="kw-keycap">${match}</kbd>`;
      }
      return `<span class="kw-highlight">${match}</span>`;
    });
  }

  function getCurrentTime() {
    if (state.demoClockMode) return state.demoTime;
    return Number.isFinite(audioEl.currentTime) ? audioEl.currentTime : 0;
  }

  function setCurrentTime(t) {
    const clamped = Math.max(0, Math.min(state.duration, t));
    if (state.demoClockMode) {
      state.demoTime = clamped;
    } else if (Number.isFinite(audioEl.duration) && audioEl.duration > 0) {
      audioEl.currentTime = Math.min(clamped, audioEl.duration - 0.05);
    } else {
      audioEl.currentTime = clamped;
    }
  }

  function getSectionAt(t) {
    for (let i = 0; i < DATA.sections.length; i++) {
      const s = DATA.sections[i];
      if (t >= s.start && t < s.end) return s;
    }
    return DATA.sections[DATA.sections.length - 1];
  }

  /* ------------------------------------------------------------------------
     Web Audio API Setup (strict CORS / opaque-origin safety + recovery)
     ------------------------------------------------------------------------ */
  function isOpaqueOrLocalOrigin() {
    const proto = window.location && window.location.protocol;
    if (proto !== 'http:' && proto !== 'https:') return true;
    const winOrigin = window.origin;
    const locOrigin = window.location.origin;
    return !winOrigin || winOrigin === 'null' || !locOrigin || locOrigin === 'null';
  }

  function canUseWebAudioFFT() {
    if (state.webAudioDisabled || state.demoClockMode) return false;
    if (isOpaqueOrLocalOrigin()) return false;

    // Verify resolved audio URL is strictly same-origin so Chrome never taints
    // MediaElementAudioSource (which would output zeroes and mute <audio>).
    const rawSrc = audioEl.currentSrc || audioEl.getAttribute('src') || DATA.audioFile;
    if (!rawSrc) return false;

    try {
      const resolved = new URL(rawSrc, window.location.href);
      if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') return false;
      if (resolved.origin !== window.location.origin) return false;
    } catch {
      return false;
    }

    return true;
  }

  function recoverFromTaintedWebAudio() {
    if (state.webAudioDisabled) return;
    state.webAudioDisabled = true;
    state.fftActive = false;

    const oldEl = audioEl;
    const resumeTime = Number.isFinite(oldEl.currentTime) ? oldEl.currentTime : 0;
    const vol = oldEl.volume;
    const muted = oldEl.muted;
    const wasPlaying = state.playing && !oldEl.paused;

    if (state.audioCtx) {
      state.audioCtx.close().catch(() => {});
      state.audioCtx = null;
      state.analyser = null;
      state.freqData = null;
      state.timeData = null;
    }

    // Replace the <audio> element with a fresh one unbound from MediaElementAudioSource
    // so native playback is never silently muted by a CORS-tainted Web Audio graph.
    oldEl.pause();
    oldEl.removeAttribute('src');
    oldEl.load();

    const freshEl = document.createElement('audio');
    freshEl.id = 'audio-player';
    freshEl.preload = 'auto';
    freshEl.volume = vol;
    freshEl.muted = muted;
    oldEl.replaceWith(freshEl);
    audioEl = freshEl;

    bindAudioElementEvents(freshEl);
    freshEl.src = DATA.audioFile;

    const resumePlayback = () => {
      if (resumeTime > 0 && Number.isFinite(freshEl.duration) && resumeTime < freshEl.duration) {
        freshEl.currentTime = resumeTime;
      }
      if (wasPlaying) {
        freshEl.play().catch(() => {});
      }
    };

    if (freshEl.readyState >= 1) {
      resumePlayback();
    } else {
      freshEl.addEventListener('loadedmetadata', resumePlayback, { once: true });
    }

    audioModePill.textContent = 'BEAT_SYNC (SAFE)';
  }

  function fallbackFromCorsError() {
    if (state.corsFallbackAttempted) return false;
    state.corsFallbackAttempted = true;
    state.corsFallbackInProgress = true;
    state.webAudioDisabled = true;
    state.fftActive = false;
    audioModePill.textContent = 'BEAT_SYNC (SAFE)';

    const shouldResume = state.playing || state.pendingPlay;
    const oldEl = audioEl;
    const vol = oldEl.volume;
    const muted = oldEl.muted;

    if (state.audioCtx) {
      // MediaElementAudioSource was already bound to oldEl; replace <audio>
      // with a clean native element so Web Audio cannot silently mute it.
      state.audioCtx.close().catch(() => {});
      state.audioCtx = null;
      state.analyser = null;
      state.freqData = null;
      state.timeData = null;

      oldEl.pause();
      oldEl.removeAttribute('src');
      oldEl.load();

      const freshEl = document.createElement('audio');
      freshEl.id = 'audio-player';
      freshEl.preload = 'auto';
      freshEl.volume = vol;
      freshEl.muted = muted;
      oldEl.replaceWith(freshEl);
      audioEl = freshEl;
      bindAudioElementEvents(freshEl);
    } else {
      audioEl.removeAttribute('crossorigin');
    }

    const targetEl = audioEl;
    targetEl.src = DATA.audioFile;
    targetEl.load();

    const finishFallback = () => {
      if (targetEl !== audioEl) return;
      state.corsFallbackInProgress = false;
      if (shouldResume) {
        const p = targetEl.play();
        if (p && typeof p.then === 'function') {
          p.then(() => {
            state.playing = true;
            state.pendingPlay = false;
            syncPlayButtons();
            showHudTemporarily();
          }).catch(() => {
            state.pendingPlay = false;
            enterDemoMode('Audio file unavailable — running in synchronized visual preview mode.');
            state.playing = true;
            syncPlayButtons();
            showHudTemporarily();
          });
        } else {
          state.playing = true;
          state.pendingPlay = false;
          syncPlayButtons();
          showHudTemporarily();
        }
      }
    };

    if (shouldResume) {
      if (targetEl.readyState >= 1) {
        finishFallback();
      } else {
        targetEl.addEventListener('loadedmetadata', finishFallback, { once: true });
      }
    } else {
      state.corsFallbackInProgress = false;
    }

    return true;
  }

  function initWebAudio() {
    if (state.audioCtx || state.demoClockMode || state.webAudioDisabled) return;

    if (!canUseWebAudioFFT()) {
      // On file://, sandboxed/opaque origin (window.origin === 'null'), or cross-origin media,
      // never call createMediaElementSource so <audio> plays natively at full volume.
      state.fftActive = false;
      audioModePill.textContent = isOpaqueOrLocalOrigin() ? 'BEAT_SYNC (LOCAL)' : 'BEAT_SYNC (SAFE)';
      return;
    }

    const AudioCtx = window.AudioContext || window.webkitAudioContext;
    if (!AudioCtx) {
      state.fftActive = false;
      audioModePill.textContent = 'BEAT_SYNC';
      return;
    }

    try {
      const ctx = new AudioCtx();
      const source = ctx.createMediaElementSource(audioEl);
      const analyser = ctx.createAnalyser();
      analyser.fftSize = 256;
      analyser.smoothingTimeConstant = 0.8;

      source.connect(analyser);
      analyser.connect(ctx.destination);

      state.audioCtx = ctx;
      state.analyser = analyser;
      state.freqData = new Uint8Array(analyser.frequencyBinCount);
      state.timeData = new Uint8Array(analyser.fftSize);
      state.fftActive = true;
      state.fftEverNonZero = false;
      state.fftZeroSeconds = 0;
      audioModePill.textContent = 'AUDIO_FFT';
    } catch (err) {
      state.fftActive = false;
      state.webAudioDisabled = true;
      audioModePill.textContent = 'BEAT_SYNC';
    }
  }

  function sampleAudio(t, dt, mood) {
    const snap = state.audioSnapshot;
    const beatSec = 60 / DATA.bpm;
    const beatPos = (t / beatSec) % 1;
    const prevPhase = snap.beatPhase;
    snap.beatPhase = beatPos;
    snap.isBeat = state.playing && beatPos < prevPhase;

    // 1. Try real Web Audio FFT if active & playing
    if (state.fftActive && state.analyser && state.playing) {
      state.analyser.getByteFrequencyData(state.freqData);
      state.analyser.getByteTimeDomainData(state.timeData);

      let sum = 0;
      for (let i = 0; i < state.freqData.length; i++) sum += state.freqData[i];

      if (sum > 8) {
        state.fftEverNonZero = true;
        state.fftZeroSeconds = 0;
        const n = state.freqData.length;
        let bass = 0, mid = 0, treble = 0;
        const bassEnd = Math.max(4, Math.floor(n * 0.12));
        const midEnd = Math.floor(n * 0.48);

        for (let i = 0; i < bassEnd; i++) bass += state.freqData[i];
        for (let i = bassEnd; i < midEnd; i++) mid += state.freqData[i];
        for (let i = midEnd; i < n; i++) treble += state.freqData[i];

        snap.bass = bass / (bassEnd * 255);
        snap.mid = mid / ((midEnd - bassEnd) * 255);
        snap.treble = treble / ((n - midEnd) * 255);
        snap.energy = snap.bass * 0.45 + snap.mid * 0.35 + snap.treble * 0.2;
        snap.peak = Math.max(snap.bass, snap.mid, snap.treble);

        for (let i = 0; i < snap.bins.length; i++) {
          const idx = Math.floor((i / snap.bins.length) * (n * 0.85));
          snap.bins[i] = state.freqData[idx] / 255;
        }
        for (let i = 0; i < snap.waveform.length; i++) {
          const idx = Math.floor((i / snap.waveform.length) * state.timeData.length);
          snap.waveform[i] = (state.timeData[idx] - 128) / 128;
        }
        return snap;
      }

      // Runtime safety guard: if FFT outputs only zeroes during active non-muted playback
      // (e.g. unexpected cross-origin redirect tainting MediaElementAudioSource), detach
      // Web Audio and swap in a fresh native <audio> element so audio is never silently muted.
      if (!audioEl.paused && !audioEl.muted && audioEl.volume > 0.05 && t > 1.5 && t < state.duration - 6.0) {
        state.fftZeroSeconds += dt;
        if (!state.fftEverNonZero && state.fftZeroSeconds > 2.5) {
          recoverFromTaintedWebAudio();
        } else if (state.fftZeroSeconds > 1.5) {
          audioModePill.textContent = 'BEAT_SYNC';
        }
      }
    }

    // 2. Musical Beat-Clock Reactive Synthesizer (works offline, on file://, and when idle)
    const intensityByMood = {
      'terminal-dark': 0.58,
      'assembly-heat': 0.78,
      'vibe-glitch': 0.96,
      'manpage-bloat': 0.74,
      'synth-arp': 0.52,
      'mech-140wpm': 1.0,
      'root-micdrop': 0.84
    };
    const mult = state.playing ? (intensityByMood[mood] || 0.7) : 0.16;
    const kick = Math.pow(1 - beatPos, 3.2);
    const snare = Math.pow(1 - ((beatPos + 0.5) % 1), 4.0);
    const arp = 0.5 + 0.5 * Math.sin(t * (DATA.bpm / 60) * Math.PI * 4);
    const flutter = 0.5 + 0.5 * Math.sin(t * 23.5) * Math.cos(t * 13.1);

    snap.bass = Math.min(1, (0.18 + kick * 0.78) * mult);
    snap.mid = Math.min(1, (0.2 + snare * 0.55 + arp * 0.25) * mult);
    snap.treble = Math.min(1, (0.15 + flutter * 0.55 + arp * 0.28) * mult);
    snap.energy = snap.bass * 0.45 + snap.mid * 0.35 + snap.treble * 0.2;
    snap.peak = Math.max(snap.bass, snap.mid, snap.treble);

    for (let i = 0; i < snap.bins.length; i++) {
      const f = i / snap.bins.length;
      const wave =
        (1 - f) * snap.bass * (0.7 + 0.3 * Math.sin(t * 8 + i * 0.4)) +
        Math.sin(f * Math.PI) * snap.mid * (0.65 + 0.35 * Math.cos(t * 11 - i * 0.5)) +
        f * snap.treble * (0.6 + 0.4 * Math.sin(t * 19 + i * 0.9));
      snap.bins[i] = Math.max(0.03, Math.min(1, wave));
    }

    for (let i = 0; i < snap.waveform.length; i++) {
      const p = i / snap.waveform.length;
      const env = Math.sin(p * Math.PI);
      snap.waveform[i] = env * mult * (
        Math.sin(p * Math.PI * 6 + t * 14) * (0.35 + snap.bass * 0.55) +
        Math.sin(p * Math.PI * 18 - t * 24) * (0.18 + snap.treble * 0.35)
      );
    }

    return snap;
  }

  /* ------------------------------------------------------------------------
     HUD & Section Markers Setup
     ------------------------------------------------------------------------ */
  function buildSectionUI() {
    trackTitleHud.textContent = DATA.title;
    bpmPill.textContent = `${Math.round(DATA.bpm)} BPM`;
    timeDurationEl.textContent = formatTime(state.duration);

    sectionPillsEl.innerHTML = '';
    timelineMarkers.innerHTML = '';

    DATA.sections.forEach((sec) => {
      // Quick-jump pill button
      const pill = document.createElement('button');
      pill.type = 'button';
      pill.className = 'section-pill';
      pill.dataset.sectionId = sec.id;
      pill.textContent = sec.label;
      pill.title = `Jump to ${sec.label} (${formatTime(sec.start)})`;
      pill.addEventListener('click', () => {
        setCurrentTime(sec.start + 0.05);
        if (!state.playing && state.launched) togglePlay(true);
        showHudTemporarily();
      });
      sectionPillsEl.appendChild(pill);

      // Vertical marker on timeline track
      if (sec.start > 0.2 && state.duration > 0) {
        const marker = document.createElement('div');
        marker.className = 'timeline-marker';
        marker.style.left = `${(sec.start / state.duration) * 100}%`;
        timelineMarkers.appendChild(marker);
      }
    });
  }

  function triggerSectionBanner(label) {
    sectionBanner.textContent = label;
    sectionBanner.classList.add('visible');
    if (state.bannerTimer) clearTimeout(state.bannerTimer);
    state.bannerTimer = setTimeout(() => {
      sectionBanner.classList.remove('visible');
    }, 2600);
  }

  function showHudTemporarily() {
    document.body.classList.remove('hud-hidden');
    if (state.hudTimer) clearTimeout(state.hudTimer);
    if (state.playing && state.launched) {
      state.hudTimer = setTimeout(() => {
        if (state.playing && !state.isScrubbing) {
          document.body.classList.add('hud-hidden');
        }
      }, 2800);
    }
  }

  /* ------------------------------------------------------------------------
     Playback Control
     ------------------------------------------------------------------------ */
  function syncPlayButtons() {
    iconPlay.hidden = state.playing;
    iconPause.hidden = !state.playing;
    document.body.classList.toggle('is-playing', state.playing);
  }

  function togglePlay(forcePlay) {
    const shouldPlay = typeof forcePlay === 'boolean' ? forcePlay : !state.playing;

    if (shouldPlay) {
      if (state.demoClockMode) {
        if (state.demoTime >= state.duration - 0.1) state.demoTime = 0;
        state.playing = true;
        syncPlayButtons();
        showHudTemporarily();
        return;
      }

      state.pendingPlay = true;
      initWebAudio();
      if (state.audioCtx && state.audioCtx.state === 'suspended') {
        state.audioCtx.resume().catch(() => {});
      }

      const playPromise = audioEl.play();
      if (playPromise && typeof playPromise.then === 'function') {
        playPromise
          .then(() => {
            state.pendingPlay = false;
            state.playing = true;
            syncPlayButtons();
            showHudTemporarily();
          })
          .catch(() => {
            // If a CORS-mode load failed (e.g. redirect to a CDN without ACAO),
            // let the CORS fallback strip crossorigin and replay natively instead of demo mode.
            if (state.corsFallbackInProgress) return;
            if (audioEl.crossOrigin === 'anonymous' && !state.corsFallbackAttempted) {
              if (fallbackFromCorsError()) return;
            }
            state.pendingPlay = false;
            // Audio file missing or blocked: seamlessly enter Demo Clock mode so visuals still run
            enterDemoMode('Audio file unavailable — running in synchronized visual preview mode.');
            state.playing = true;
            syncPlayButtons();
            showHudTemporarily();
          });
      } else {
        state.pendingPlay = false;
        state.playing = true;
        syncPlayButtons();
        showHudTemporarily();
      }
    } else {
      state.pendingPlay = false;
      if (!state.demoClockMode) {
        audioEl.pause();
      }
      state.playing = false;
      syncPlayButtons();
      document.body.classList.remove('hud-hidden');
    }
  }

  function enterDemoMode(msg) {
    state.demoClockMode = true;
    audioModePill.textContent = 'PREVIEW_CLOCK';
    if (msg && launchNotice) {
      launchNotice.textContent = msg;
      launchNotice.hidden = false;
    }
  }

  function launchExperience() {
    state.launched = true;
    launchOverlay.classList.add('hidden');
    togglePlay(true);
  }

  /* ------------------------------------------------------------------------
     Lyric Synchronization
     ------------------------------------------------------------------------ */
  function updateLyrics(t) {
    const lines = DATA.lines;
    let activeIdx = -1;
    let nextIdx = -1;

    for (let i = 0; i < lines.length; i++) {
      if (t >= lines[i].start && t <= lines[i].end) {
        activeIdx = i;
        nextIdx = i + 1 < lines.length ? i + 1 : -1;
        break;
      }
      if (t < lines[i].start) {
        nextIdx = i;
        break;
      }
    }

    const prevIdx = activeIdx > 0
      ? activeIdx - 1
      : activeIdx === -1
        ? (nextIdx > 0 ? nextIdx - 1 : (nextIdx === -1 && lines.length > 0 ? lines.length - 1 : -1))
        : -1;

    if (prevIdx !== state.prevLineIdx) {
      state.prevLineIdx = prevIdx;
      lyricPrev.textContent = prevIdx >= 0 ? lines[prevIdx].text : '';
    }

    if (nextIdx !== state.nextLineIdx) {
      state.nextLineIdx = nextIdx;
      lyricNext.textContent = nextIdx >= 0 ? lines[nextIdx].text : '';
    }

    if (activeIdx !== state.activeLineIdx) {
      state.activeLineIdx = activeIdx;

      if (activeIdx >= 0) {
        const line = lines[activeIdx];
        lyricCurrentText.innerHTML = renderHighlightedLyric(line.text, line.highlight);
        lyricCurrent.classList.remove('line-enter');
        // Force reflow to retrigger entrance animation
        void lyricCurrent.offsetWidth;
        lyricCurrent.classList.add('line-enter');
      } else {
        lyricCurrentText.innerHTML = '';
      }
    }

    // Update smooth line progress bar fill
    if (activeIdx >= 0) {
      const line = lines[activeIdx];
      const span = Math.max(0.1, line.end - line.start);
      const pct = Math.max(0, Math.min(100, ((t - line.start) / span) * 100));
      document.documentElement.style.setProperty('--line-progress', `${pct.toFixed(1)}%`);
      return line.text;
    } else {
      document.documentElement.style.setProperty('--line-progress', '0%');
      return '';
    }
  }

  /* ------------------------------------------------------------------------
     Main 60fps Animation Loop
     ------------------------------------------------------------------------ */
  function tick(now) {
    const dt = Math.min((now - state.lastTick) / 1000, 0.05);
    state.lastTick = now;

    if (state.demoClockMode && state.playing) {
      state.demoTime += dt;
      if (state.demoTime >= state.duration) {
        state.demoTime = state.duration;
        state.playing = false;
        syncPlayButtons();
        document.body.classList.remove('hud-hidden');
      }
    }

    const t = getCurrentTime();
    const sec = getSectionAt(t);
    const mood = sec ? sec.mood : 'terminal-dark';
    const secSpan = sec ? Math.max(0.1, sec.end - sec.start) : 1;
    const secProgress = sec ? Math.max(0, Math.min(1, (t - sec.start) / secSpan)) : 0;

    // Update mood & active section pill when section changes
    if (sec && sec.id !== state.activeSectionId) {
      state.activeSectionId = sec.id;
      document.body.setAttribute('data-mood', mood);
      sectionLabelHud.textContent = sec.label;
      moodPill.textContent = mood;
      if (state.launched) {
        triggerSectionBanner(sec.label);
      }

      const pills = sectionPillsEl.querySelectorAll('.section-pill');
      pills.forEach((p) => {
        p.classList.toggle('active', p.dataset.sectionId === sec.id);
      });
    }

    // Sample audio FFT or Beat-Clock fallback
    const audioSnap = sampleAudio(t, dt, mood);

    // Subtle kinetic beat scale on active lyric
    const beatScale = state.playing ? (1 + audioSnap.bass * 0.032) : 1;
    document.documentElement.style.setProperty('--beat-scale', beatScale.toFixed(4));

    // Update lyrics
    const currentLineText = updateLyrics(t);

    // Render 60fps Canvas Visual Engine
    engine.render({
      time: t,
      duration: state.duration,
      playing: state.playing,
      mood,
      sectionProgress: secProgress,
      audio: audioSnap,
      currentLineText,
      quitLine: QUIT_LINE
    });

    // Update HUD timeline & mini EQ bars
    if (!state.isScrubbing && state.duration > 0) {
      const pct = Math.max(0, Math.min(100, (t / state.duration) * 100));
      timelineProgress.style.width = `${pct}%`;
      timelineThumb.style.left = `${pct}%`;
      timelineWrap.setAttribute('aria-valuenow', Math.round(pct));
    }
    timeCurrentEl.textContent = formatTime(t);

    for (let i = 0; i < miniEqBars.length; i++) {
      const val = audioSnap.bins[i * 6] || 0;
      const px = Math.max(3, Math.round(3 + val * 15));
      miniEqBars[i].style.height = `${px}px`;
    }

    requestAnimationFrame(tick);
  }

  /* ------------------------------------------------------------------------
     Event Listeners
     ------------------------------------------------------------------------ */
  function bindAudioElementEvents(el) {
    el.addEventListener('loadedmetadata', () => {
      if (el !== audioEl) return;
      state.audioReady = true;
      if (Number.isFinite(el.duration) && el.duration > 0) {
        state.duration = el.duration;
        buildSectionUI();
      }
    });

    el.addEventListener('progress', () => {
      if (el !== audioEl) return;
      if (el.buffered.length > 0 && state.duration > 0) {
        const end = el.buffered.end(el.buffered.length - 1);
        timelineBuffer.style.width = `${Math.min(100, (end / state.duration) * 100)}%`;
      }
    });

    el.addEventListener('ended', () => {
      if (el !== audioEl) return;
      state.playing = false;
      syncPlayButtons();
      document.body.classList.remove('hud-hidden');
    });

    el.addEventListener('error', () => {
      if (el !== audioEl) return;
      if (el.crossOrigin === 'anonymous' && !state.corsFallbackAttempted) {
        fallbackFromCorsError();
        return;
      }
      state.corsFallbackInProgress = false;
      state.pendingPlay = false;
      enterDemoMode('Audio track not found yet — click Play for visual preview mode.');
    });
  }

  function bindEvents() {
    window.addEventListener('resize', () => engine.resize());

    // Request audio with CORS ('anonymous') BEFORE setting src whenever Web Audio FFT
    // is eligible (http/https non-opaque origin). This allows cross-origin 302 redirects
    // (e.g. Hugging Face Static Spaces LFS/XetHub CDN with ACAO: *) to stay untainted
    // while same-origin servers without ACAO continue to work cleanly.
    bindAudioElementEvents(audioEl);
    if (canUseWebAudioFFT()) {
      audioEl.crossOrigin = 'anonymous';
    } else {
      audioEl.removeAttribute('crossorigin');
      audioModePill.textContent = isOpaqueOrLocalOrigin() ? 'BEAT_SYNC (LOCAL)' : 'BEAT_SYNC (SAFE)';
    }
    audioEl.src = DATA.audioFile;
    audioEl.load();
    audioEl.volume = parseFloat(volumeSlider.value);

    // Launch button
    btnLaunch.addEventListener('click', launchExperience);

    // Play/Pause button
    btnPlay.addEventListener('click', () => togglePlay());

    // Timeline scrubbing & hover preview
    function seekFromClientX(clientX, commit) {
      const rect = timelineWrap.getBoundingClientRect();
      const frac = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
      const targetTime = frac * state.duration;
      const sec = getSectionAt(targetTime);

      timelineTooltip.style.left = `${frac * 100}%`;
      timelineTooltip.textContent = `${formatTime(targetTime)}${sec ? ' • ' + sec.label : ''}`;

      if (commit) {
        timelineProgress.style.width = `${frac * 100}%`;
        timelineThumb.style.left = `${frac * 100}%`;
        setCurrentTime(targetTime);
      }
    }

    timelineWrap.addEventListener('pointerdown', (e) => {
      state.isScrubbing = true;
      timelineWrap.classList.add('scrubbing');
      timelineWrap.setPointerCapture(e.pointerId);
      seekFromClientX(e.clientX, true);
    });

    timelineWrap.addEventListener('pointermove', (e) => {
      seekFromClientX(e.clientX, state.isScrubbing);
    });

    timelineWrap.addEventListener('pointerup', (e) => {
      if (state.isScrubbing) {
        seekFromClientX(e.clientX, true);
        state.isScrubbing = false;
        timelineWrap.classList.remove('scrubbing');
      }
    });

    // Volume & Mute
    function updateVolumeUI() {
      const muted = audioEl.muted || audioEl.volume === 0;
      iconVolOn.hidden = muted;
      iconVolOff.hidden = !muted;
    }

    volumeSlider.addEventListener('input', () => {
      const v = parseFloat(volumeSlider.value);
      audioEl.volume = v;
      audioEl.muted = v === 0;
      updateVolumeUI();
    });

    btnMute.addEventListener('click', () => {
      audioEl.muted = !audioEl.muted;
      if (!audioEl.muted && audioEl.volume === 0) {
        audioEl.volume = 0.8;
        volumeSlider.value = '0.8';
      }
      updateVolumeUI();
    });

    // CRT FX Toggle
    function toggleCrt() {
      const isOn = document.body.classList.toggle('crt-on');
      document.body.classList.toggle('crt-off', !isOn);
      btnCrt.classList.toggle('active', isOn);
      btnCrt.setAttribute('aria-pressed', String(isOn));
    }
    btnCrt.addEventListener('click', toggleCrt);

    // Fullscreen Toggle
    function toggleFullscreen() {
      if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen().catch(() => {});
      } else {
        document.exitFullscreen().catch(() => {});
      }
    }
    btnFullscreen.addEventListener('click', toggleFullscreen);

    // Auto-hide HUD on mouse/touch movement
    ['mousemove', 'pointerdown', 'touchstart'].forEach((evt) => {
      window.addEventListener(evt, showHudTemporarily, { passive: true });
    });

    // Keyboard Shortcuts
    window.addEventListener('keydown', (e) => {
      if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return;

      if (e.code === 'Space') {
        e.preventDefault();
        if (!state.launched) launchExperience();
        else togglePlay();
      } else if (e.code === 'ArrowLeft') {
        e.preventDefault();
        setCurrentTime(getCurrentTime() - 5);
        showHudTemporarily();
      } else if (e.code === 'ArrowRight') {
        e.preventDefault();
        setCurrentTime(getCurrentTime() + 5);
        showHudTemporarily();
      } else if (e.key === 'f' || e.key === 'F') {
        e.preventDefault();
        toggleFullscreen();
      } else if (e.key === 'm' || e.key === 'M') {
        e.preventDefault();
        btnMute.click();
      } else if (e.key === 'c' || e.key === 'C') {
        e.preventDefault();
        toggleCrt();
      }
    });
  }

  /* ------------------------------------------------------------------------
     Bootstrap
     ------------------------------------------------------------------------ */
  buildSectionUI();
  bindEvents();
  requestAnimationFrame(tick);
})();