beecast-player 0.10.2

The first-party beecast player — a clean-room, dependency-free asciicast (v1/v2/v3) player and VT emulator, exposed as inlinable JS/CSS string constants, with live-follow append for recordings that are still growing.
Documentation
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
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
// beecast-player: the DOM half (see the crate README). Renders controller state,
// builds the default controls, registers <beecast-player>, and keeps BeeCastPlayer.create
// as a compatibility adapter over the same surface.
//
// Clean-room implementation, MIT like the rest of beecast. The time axis is ALWAYS
// recording time: idle compression only changes pacing, never the clock the API speaks.
'use strict';
(function (root) {

const VT = root.BeeCastVT;
const Controller = root.BeeCastController;
const SEEK_STEP_SECS = 5;
const SPEEDS = Controller.SPEEDS;

// Center play affordance: an inline SVG "|>" (bar + chevron, equal height) — crisp at any
// size, no font metrics mismatch between `|` and `>`.
const BIG_PLAY =
  '<svg class="sp-bigplay-icon" viewBox="0 0 80 80" width="1em" height="1em" aria-hidden="true" focusable="false">' +
  '<rect x="10" y="8" width="12" height="64" rx="2" fill="currentColor"/>' +
  '<path d="M32 8 L70 40 L32 72 Z" fill="currentColor"/>' +
  '</svg>';

const ICON_PLAY = '';
const ICON_PAUSE = '';

// ---- rendering -------------------------------------------------------------------------
const ATTR_CLASSES = [
  [VT.A_BOLD, 'sp-b'], [VT.A_DIM, 'sp-d'], [VT.A_ITALIC, 'sp-i'],
  [VT.A_UNDER, 'sp-u'], [VT.A_STRIKE, 'sp-s'],
];

function colorCss(c, bold) {
  if (c == null) return null;
  if (typeof c === 'string') return c;
  const idx = bold && c < 8 ? c + 8 : c;
  return idx < 16 ? 'var(--sp-c' + idx + ')' : VT.color256(idx);
}

function esc(s) {
  return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function runHtml(run, hasCursor, cursorCol) {
  if (hasCursor && run.text.length > 1) {
    const before = { text: run.text.slice(0, cursorCol), fg: run.fg, bg: run.bg, attrs: run.attrs };
    const at = { text: run.text[cursorCol] || ' ', fg: run.fg, bg: run.bg, attrs: run.attrs };
    const after = { text: run.text.slice(cursorCol + 1), fg: run.fg, bg: run.bg, attrs: run.attrs };
    return (before.text ? runHtml(before, false, 0) : '') + runHtml(at, true, 0) +
      (after.text ? runHtml(after, false, 0) : '');
  }
  const inverse = (run.attrs & VT.A_INVERSE) !== 0;
  const bold = (run.attrs & VT.A_BOLD) !== 0;
  let fg = colorCss(run.fg, bold);
  let bg = colorCss(run.bg, false);
  if (inverse) { const t = fg || 'var(--sp-fg)'; fg = bg || 'var(--sp-bg)'; bg = t; }
  const classes = [];
  for (const pair of ATTR_CLASSES) if (run.attrs & pair[0]) classes.push(pair[1]);
  if (hasCursor) classes.push('sp-cur');
  let style = '';
  if (fg) style += 'color:' + fg + ';';
  if (bg) style += 'background:' + bg + ';';
  if (!classes.length && !style) return esc(run.text);
  return '<span' + (classes.length ? ' class="' + classes.join(' ') + '"' : '') +
    (style ? ' style="' + style + '"' : '') + '>' + esc(run.text) + '</span>';
}

function screenHtml(snap) {
  const lines = [];
  for (let y = 0; y < snap.rows.length; y++) {
    let x = 0, html = '';
    for (const run of snap.rows[y]) {
      const cursorHere = snap.cursor.visible && snap.cursor.y === y &&
        snap.cursor.x >= x && snap.cursor.x < x + run.text.length;
      html += runHtml(run, cursorHere, snap.cursor.x - x);
      x += run.text.length;
    }
    lines.push(html);
  }
  return lines.join('\n');
}

function fmtClock(secs) {
  secs = Math.max(0, Math.floor(secs));
  const m = Math.floor(secs / 60), s = secs % 60;
  return m + ':' + String(s).padStart(2, '0');
}

function parseControls(controls) {
  if (controls === false) {
    return { play: false, seek: false, time: false, speed: false, chapters: false, fullscreen: false, live: false };
  }
  const d = { play: true, seek: true, time: true, speed: true, chapters: true, fullscreen: true, live: false };
  if (controls && typeof controls === 'object') {
    for (const k of Object.keys(d)) {
      if (controls[k] != null) d[k] = !!controls[k];
    }
  }
  return d;
}

function dispatchBee(el, name, detail) {
  if (!el || typeof CustomEvent === 'undefined') return;
  try {
    el.dispatchEvent(new CustomEvent(name, {
      detail: detail || {},
      bubbles: true,
      composed: true,
    }));
  } catch (_) {}
}

// ---- player view -----------------------------------------------------------------------
function Player(src, mount, opts) {
  opts = opts || {};
  this.opts = opts;
  this.controlsCfg = parseControls(opts.controls);
  this.fit = opts.fit || null;
  this.fsEl = opts.fullscreenEl || null;
  this.accessibility = opts.accessibility || 'snapshot';
  this.disposed = false;
  this._lastAtEdge = null;

  const data = src && (src.data != null ? src.data : src.cast);
  this.controller = Controller.create({
    data: data,
    source: src && src.source,
    idleTimeLimit: opts.idleTimeLimit,
    markers: opts.markers,
    speed: opts.speed,
    startAt: opts.startAt,
    clock: opts.clock,
  });

  this.buildDom(mount, this.controlsCfg);
  this.bindController();
  this.layout();
  // Compatibility surface: read-only playing getter over controller state.
  Object.defineProperty(this, 'playing', {
    configurable: true,
    enumerable: true,
    get: function () { return this.controller.isPlaying(); },
  });
  // Non-public fields kept readable during the migration window only.
  Object.defineProperty(this, 'pacedPos', {
    configurable: true,
    get: function () { return this.controller.pacedPos; },
  });
  Object.defineProperty(this, 'eventIdx', {
    configurable: true,
    get: function () { return this.controller.eventIdx; },
  });
  Object.defineProperty(this, 'cast', {
    configurable: true,
    get: function () { return this.controller.cast; },
  });
  Object.defineProperty(this, 'speed', {
    configurable: true,
    get: function () { return this.controller.speed; },
    set: function (v) { this.controller.setSpeed(v); },
  });

  if (opts.autoPlay) this.play();
  // Declared-live at mount (growing recordings): park at the edge with no play overlay.
  if (opts.live) this.setLive(true, 'api');
  const self = this;
  if (typeof ResizeObserver !== 'undefined') {
    this.resizeObs = new ResizeObserver(function () {
      if (!self._layouting) self.layout();
    });
    this.resizeObs.observe(this.root.parentNode || this.root);
  }
  this.fsHandler = function () { self.layout(); };
  if (typeof document !== 'undefined') {
    document.addEventListener('fullscreenchange', this.fsHandler);
  }
}

Player.prototype.bindController = function () {
  const self = this;
  this.unsubscribe = this.controller.subscribe(function (state, meta) {
    self.onState(state, meta || {});
  });
};

Player.prototype.onState = function (state, meta) {
  if (this.disposed) return;
  const type = meta.type || 'change';

  if (this.screenEl) {
    if (type === 'ready' || type === 'seek' || type === 'play' || type === 'pause' ||
        type === 'ended' || type === 'timeupdate' || type === 'durationchange' ||
        type === 'change' || meta.terminalChanged || meta.resized) {
      // High-frequency path: still render terminal when it may have changed.
      if (type !== 'timeupdate' || meta.terminalChanged || meta.resized || !this._paintedOnce) {
        this.screenEl.innerHTML = screenHtml(state.terminal);
        this._paintedOnce = true;
        if (this.accessibility === 'snapshot' && this.a11yEl) {
          this.a11yEl.textContent = terminalPlain(state.terminal);
        }
      }
    }
  }

  this.renderBar(state);
  this.syncOverlay(state);
  this.syncChaptersUi(state);
  // Declared-live: the bar pins full-width in the live color (see .sp-islive in the CSS).
  if (this.root) this.root.classList.toggle('sp-islive', !!state.live);
  if (meta.resized) this.layout();
  if (type === 'ready' || type === 'durationchange' || type === 'markerchange') {
    this.layoutMarkers(state);
  }

  // Integration events on the root element (Phase 2).
  const el = this.eventTarget || this.root;
  if (type === 'ready') dispatchBee(el, 'beecast-ready', { state: publicState(state) });
  if (type === 'play') dispatchBee(el, 'beecast-play', { origin: meta.origin, currentTime: state.currentTime });
  if (type === 'pause') dispatchBee(el, 'beecast-pause', { origin: meta.origin, currentTime: state.currentTime });
  if (type === 'ended') dispatchBee(el, 'beecast-ended', { currentTime: state.currentTime, duration: state.duration });
  if (type === 'seek') {
    dispatchBee(el, 'beecast-seek', {
      origin: meta.origin,
      currentTime: state.currentTime,
      duration: state.duration,
    });
  }
  if (type === 'timeupdate') {
    dispatchBee(el, 'beecast-timeupdate', {
      currentTime: state.currentTime,
      duration: state.duration,
      atLiveEdge: state.atLiveEdge,
    });
  }
  if (type === 'speedchange') {
    dispatchBee(el, 'beecast-speedchange', { speed: state.speed, origin: meta.origin });
  }
  if (type === 'durationchange') {
    dispatchBee(el, 'beecast-durationchange', { duration: state.duration });
  }
  if (type === 'livechange') {
    dispatchBee(el, 'beecast-livechange', { live: !!state.live, origin: meta.origin });
  }
  if (this._lastAtEdge != null && this._lastAtEdge !== state.atLiveEdge) {
    dispatchBee(el, 'beecast-liveedgechange', { atLiveEdge: state.atLiveEdge });
  }
  if (type === 'durationchange' || type === 'ready' || type === 'markerchange') {
    dispatchBee(el, 'beecast-markerchange', { markers: state.markers });
  }
  this._lastAtEdge = state.atLiveEdge;
};

function publicState(state) {
  return {
    status: state.status,
    currentTime: state.currentTime,
    duration: state.duration,
    speed: state.speed,
    atLiveEdge: state.atLiveEdge,
    live: state.live,
    canAppend: state.canAppend,
    markers: state.markers,
    dimensions: state.dimensions,
  };
}

function terminalPlain(snap) {
  const lines = [];
  for (let y = 0; y < snap.rows.length; y++) {
    let s = '';
    for (const run of snap.rows[y]) s += run.text;
    lines.push(s.replace(/\s+$/, ''));
  }
  return lines.join('\n');
}

Player.prototype.buildDom = function (mount, cfg) {
  const self = this;
  const root = document.createElement('div');
  root.className = 'beecast-player';
  root.setAttribute('part', 'root');
  root.tabIndex = 0;
  root.setAttribute('role', 'region');
  root.setAttribute('aria-label', 'Terminal recording player');

  let bar = '';
  if (cfg.play || cfg.seek || cfg.time || cfg.speed || cfg.chapters || cfg.fullscreen || cfg.live) {
    bar = '<div class="sp-bar" part="toolbar">';
    if (cfg.play) {
      bar += '<button class="sp-play" type="button" part="play-button" ' +
        'aria-label="Play" title="play/pause (space)">' + ICON_PLAY + '</button>';
    }
    if (cfg.live) {
      bar += '<button class="sp-live" type="button" part="live-button" ' +
        'aria-label="Go live" aria-pressed="false" title="follow the live edge">● Live</button>';
    }
    if (cfg.time) bar += '<span class="sp-time" part="current-time" aria-hidden="true">0:00</span>';
    if (cfg.seek) {
      bar += '<div class="sp-seek" part="seek" role="slider" tabindex="0" ' +
        'aria-label="Seek" aria-valuemin="0" aria-valuemax="0" aria-valuenow="0">' +
        '<div class="sp-fill"></div><div class="sp-markers"></div></div>';
    }
    if (cfg.time) bar += '<span class="sp-dur" part="duration" aria-hidden="true">0:00</span>';
    if (cfg.chapters) {
      bar += '<button class="sp-chapbtn" type="button" part="chapter-button" ' +
        'aria-label="Chapters" aria-expanded="false" title="chapters (c)" hidden>☰</button>';
    }
    if (cfg.speed) {
      bar += '<span class="sp-speedwrap">' +
        '<button class="sp-speed" type="button" part="speed-button" ' +
        'aria-label="Playback speed" aria-haspopup="menu" aria-expanded="false" ' +
        'title="speed (&lt; / &gt;)">1×</button>' +
        '<div class="sp-speedmenu" part="speed-menu" role="menu" hidden></div></span>';
    }
    if (cfg.fullscreen) {
      bar += '<button class="sp-fs" type="button" part="fullscreen-button" ' +
        'aria-label="Fullscreen" title="fullscreen (f)">⛶</button>';
    }
    bar += '</div>';
  }

  // Stage wraps the terminal + chapter panel so fullscreen can center the pair above
  // the control bar (without margin-auto gaps between the terminal and the bar), and
  // so a tall/wide mount can dock chapters beside the terminal instead of overlaying it.
  root.innerHTML =
    '<div class="sp-stage" part="stage">' +
    '<div class="sp-screen-box" part="screen-box">' +
    '<pre class="sp-screen" part="screen" aria-hidden="true"></pre>' +
    (this.accessibility === 'snapshot'
      ? '<pre class="sp-a11y" part="terminal-text"></pre>'
      : '') +
    '<div class="sp-overlay" part="overlay" hidden role="button" tabindex="0" ' +
    'aria-label="Play recording"><span class="sp-bigplay" aria-hidden="true">' + BIG_PLAY + '</span></div>' +
    '<div class="sp-toast" part="toast" role="status"></div>' +
    '</div>' +
    '<div class="sp-chapters" part="chapter-panel" role="menu" hidden></div>' +
    '</div>' + bar;

  mount.appendChild(root);
  this.root = root;
  this.stageEl = root.querySelector('.sp-stage');
  this.screenEl = root.querySelector('.sp-screen');
  this.a11yEl = root.querySelector('.sp-a11y');
  this.playBtn = root.querySelector('.sp-play');
  this.liveBtn = root.querySelector('.sp-live');
  this.timeEl = root.querySelector('.sp-time');
  this.durEl = root.querySelector('.sp-dur');
  this.seekEl = root.querySelector('.sp-seek');
  this.fillEl = root.querySelector('.sp-fill');
  this.speedBtn = root.querySelector('.sp-speed');
  this.speedMenuEl = root.querySelector('.sp-speedmenu');
  this.chapBtn = root.querySelector('.sp-chapbtn');
  this.chaptersEl = root.querySelector('.sp-chapters');
  this.fsBtn = root.querySelector('.sp-fs');
  this.overlayEl = root.querySelector('.sp-overlay');
  this.marksEl = root.querySelector('.sp-markers');
  this.toastEl = root.querySelector('.sp-toast');
  this._chaptersUserClosed = false;
  this._chaptersAutoOpened = false;

  if (this.playBtn) {
    this.playBtn.addEventListener('click', function () { self.toggle('pointer'); });
  }
  if (this.liveBtn) {
    this.liveBtn.addEventListener('click', function (ev) {
      ev.stopPropagation();
      // Go live (or leave live). Going live parks at the edge — no play(), no overlay.
      self.setLive(!self.controller.getState().live, 'pointer');
      try { root.focus({ preventScroll: true }); } catch (_) { root.focus(); }
    });
  }
  if (this.overlayEl) {
    const playFromOverlay = function (ev) {
      ev.stopPropagation();
      self.play('pointer');
      try { root.focus({ preventScroll: true }); } catch (_) { root.focus(); }
    };
    this.overlayEl.addEventListener('click', playFromOverlay);
    this.overlayEl.addEventListener('keydown', function (ev) {
      if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); playFromOverlay(ev); }
    });
  }
  if (this.speedBtn) {
    this.speedBtn.addEventListener('click', function (ev) {
      ev.stopPropagation();
      self.toggleSpeedMenu();
    });
  }
  if (this.chapBtn) {
    this.chapBtn.addEventListener('click', function () { self.toggleChapters(); });
  }
  if (this.fsBtn) {
    this.fsBtn.addEventListener('click', function () { self.toggleFullscreen(); });
  }
  if (this.seekEl) {
    const seekTo = function (ev, origin) {
      const r = self.seekEl.getBoundingClientRect();
      const frac = Math.min(1, Math.max(0, (ev.clientX - r.left) / (r.width || 1)));
      const dur = self.controller.cast.duration;
      self.seek(frac * dur, origin || 'pointer');
    };
    this.seekEl.addEventListener('pointerdown', function (ev) {
      if (ev.button !== 0) return;
      ev.preventDefault();
      seekTo(ev, 'pointer');
      self.seekEl.setPointerCapture(ev.pointerId);
      const move = function (e) { if (e.pointerId === ev.pointerId) seekTo(e, 'pointer'); };
      const up = function (e) {
        if (e.pointerId !== ev.pointerId) return;
        self.seekEl.removeEventListener('pointermove', move);
        self.seekEl.removeEventListener('pointerup', up);
        self.seekEl.removeEventListener('pointercancel', up);
      };
      self.seekEl.addEventListener('pointermove', move);
      self.seekEl.addEventListener('pointerup', up);
      self.seekEl.addEventListener('pointercancel', up);
    });
    this.seekEl.addEventListener('keydown', function (ev) {
      const dur = self.controller.cast.duration;
      const now = self.getCurrentTime();
      let t = null;
      if (ev.key === 'ArrowLeft') t = now - SEEK_STEP_SECS;
      else if (ev.key === 'ArrowRight') t = now + SEEK_STEP_SECS;
      else if (ev.key === 'PageDown') t = now - 30;
      else if (ev.key === 'PageUp') t = now + 30;
      else if (ev.key === 'Home') t = 0;
      else if (ev.key === 'End') t = dur;
      else return;
      ev.preventDefault();
      self.seek(t, 'keyboard');
    });
  }
  this.keyHandler = function (ev) { self.onKey(ev); };
  root.addEventListener('keydown', this.keyHandler);
  root.addEventListener('click', function (ev) {
    if (ev.target !== root && !ev.target.closest('.sp-stage')) return;
    try { root.focus({ preventScroll: true }); } catch (_) { root.focus(); }
  });
};

Player.prototype.syncOverlay = function (state) {
  if (!this.overlayEl) return;
  // Show whenever playback is not running (start, paused mid-cast, ended) so the
  // big glyph is the obvious "press play" affordance — not only at t = 0.
  // Declared-live is following the growing edge: no play overlay (that would invite
  // play(), which drops live and replays from the top).
  const show = !state.live && state.status !== 'playing' && state.duration > 0;
  this.overlayEl.hidden = !show;
};

Player.prototype.renderBar = function (state) {
  if (this.timeEl) this.timeEl.textContent = fmtClock(state.currentTime);
  if (this.durEl) this.durEl.textContent = fmtClock(state.duration);
  if (this.fillEl) {
    this.fillEl.style.width = (state.duration > 0
      ? Math.min(100, (state.currentTime / state.duration) * 100)
      : 0) + '%';
  }
  if (this.seekEl) {
    this.seekEl.setAttribute('aria-valuemin', '0');
    this.seekEl.setAttribute('aria-valuemax', String(Math.floor(state.duration)));
    this.seekEl.setAttribute('aria-valuenow', String(Math.floor(state.currentTime)));
    this.seekEl.setAttribute('aria-valuetext', fmtClock(state.currentTime) + ' of ' + fmtClock(state.duration));
  }
  if (this.playBtn) {
    const playing = state.status === 'playing';
    this.playBtn.textContent = playing ? ICON_PAUSE : ICON_PLAY;
    this.playBtn.setAttribute('aria-label', playing ? 'Pause' : 'Play');
    this.playBtn.setAttribute('aria-pressed', playing ? 'true' : 'false');
  }
  if (this.liveBtn) {
    const live = !!state.live;
    this.liveBtn.classList.toggle('on', live);
    this.liveBtn.setAttribute('aria-pressed', live ? 'true' : 'false');
    this.liveBtn.setAttribute('aria-label', live ? 'Live (following)' : 'Go live');
    this.liveBtn.title = live ? 'following the live edge (seek back to leave)' : 'follow the live edge';
  }
  if (this.speedBtn) {
    this.speedBtn.textContent = String(state.speed).replace(/\.0$/, '') + '\u00d7';
  }
};

Player.prototype.layoutMarkers = function (state) {
  if (!this.marksEl) return;
  this.marksEl.innerHTML = '';
  if (!(state.duration > 0)) return;
  for (const m of state.markers) {
    const tick = document.createElement('div');
    tick.className = 'sp-marker' + (m.type === 'annotation' ? ' sp-marker-ann' : '');
    tick.style.left = Math.min(100, (m.time / state.duration) * 100) + '%';
    if (m.color) tick.style.background = m.color;
    tick.title = fmtClock(m.time) + (m.label ? ' ' + m.label : '');
    this.marksEl.appendChild(tick);
  }
};

Player.prototype.hasChapters = function () {
  const markers = this.controller && this.controller.getState().markers;
  return !!(markers && markers.length);
};

Player.prototype.toggleChapters = function (force, opts) {
  if (!this.chaptersEl) return;
  // A missing chapter set is not an empty menu. Keyboard `c` and the public toggle are
  // genuine no-ops until markers exist; an explicit close remains allowed so a live
  // player can retract a panel if an updated metadata document removes its chapters.
  if (!this.hasChapters() && force !== false) return;
  opts = opts || {};
  // Explicit toggle: open when hidden, close when visible — `c` must close as well as open.
  const show = force != null ? !!force : !!this.chaptersEl.hidden;
  // Focus must be checked BEFORE hiding: hiding the focused row silently moves
  // focus to <body>, and the ☰ button would never get it back.
  const hadFocus = !show && typeof document !== 'undefined' &&
    this.chaptersEl.contains(document.activeElement);
  this.chaptersEl.hidden = !show;
  if (this.chapBtn) this.chapBtn.setAttribute('aria-expanded', show ? 'true' : 'false');
  if (show) {
    this._chaptersRenderKey = null;
    this.renderChapters(this.controller.getState());
    if (opts.auto) this._chaptersAutoOpened = true;
    else {
      this._chaptersUserClosed = false;
      this._chaptersAutoOpened = false;
    }
    if (!opts.silent) {
      const current = this.chaptersEl.querySelector('.sp-chap-on') || this.chaptersEl.querySelector('.sp-chap');
      if (current) try { current.focus({ preventScroll: true }); } catch (_) { current.focus(); }
    }
  } else {
    if (!opts.auto) {
      this._chaptersUserClosed = true;
      this._chaptersAutoOpened = false;
    }
    if (hadFocus && this.chapBtn) {
      try { this.chapBtn.focus({ preventScroll: true }); } catch (_) {}
    }
  }
  // A docked panel shares the stage width with the terminal: opening/closing it changes
  // the width budget, and the mount itself does not resize (so no ResizeObserver tick).
  if (!this._layouting) this.layout();
};

Player.prototype.renderChapters = function (state) {
  if (!this.chaptersEl) return;
  const self = this;
  this.chaptersEl.innerHTML = '';
  const markers = state.markers || [];
  this._chaptersRenderKey = markers.map(function (m) {
    return m.id + '\0' + m.time + '\0' + (m.label || '');
  }).join('\n');
  const now = state.currentTime;
  let currentId = null;
  for (let i = 0; i < markers.length; i++) {
    if (markers[i].time <= now + 1e-9) currentId = markers[i].id;
  }
  for (let i = 0; i < markers.length; i++) {
    const m = markers[i];
    const row = document.createElement('button');
    row.type = 'button';
    row.className = 'sp-chap' + (m.id === currentId ? ' sp-chap-on' : '') +
      (m.type === 'annotation' ? ' sp-chap-ann' : '');
    row.setAttribute('role', 'menuitem');
    row.dataset.markerId = String(m.id);
    const stateEl = document.createElement('span');
    stateEl.className = 'sp-chap-state';
    const ico = document.createElement('span');
    ico.className = 'sp-chap-ico';
    ico.setAttribute('aria-hidden', 'true');
    ico.textContent = m.id === currentId ? '\u2713' : '\u00B7';
    const lab = document.createElement('span');
    lab.className = 'sp-chap-state-label';
    lab.textContent = m.id === currentId ? 'NOW' : ('CH ' + (i + 1));
    stateEl.appendChild(ico);
    stateEl.appendChild(document.createTextNode(' '));
    stateEl.appendChild(lab);
    const id = document.createElement('span');
    id.className = 'sp-chap-id';
    id.textContent = m.label || fmtClock(m.time);
    const meta = document.createElement('span');
    meta.className = 'sp-chap-meta';
    meta.textContent = fmtClock(m.time);
    row.appendChild(stateEl);
    row.appendChild(id);
    row.appendChild(meta);
    row.addEventListener('click', (function (marker) {
      return function (ev) {
        ev.preventDefault();
        ev.stopPropagation();
        const el = self.eventTarget || self.root;
        // Cancellable marker selection (Phase 5).
        let cancelled = false;
        if (el && typeof CustomEvent !== 'undefined') {
          try {
            const ce = new CustomEvent('beecast-markerselect', {
              detail: { marker: marker },
              bubbles: true,
              composed: true,
              cancelable: true,
            });
            cancelled = !el.dispatchEvent(ce);
          } catch (_) {}
        }
        if (cancelled) return;
        // Seek only — chapter picks must not start playback (same as [ ] / ←→).
        self.seek(marker.time, 'marker');
        self.chapterToast(marker);
        // Overlay mode closes after a pick; docked side panel stays open.
        if (!self.root.classList.contains('sp-chapters-dock')) self.toggleChapters(false);
      };
    })(m));
    this.chaptersEl.appendChild(row);
  }
};

Player.prototype.markCurrentChapter = function (state) {
  if (!this.chaptersEl) return;
  const markers = state.markers || [];
  let currentId = null;
  for (let i = 0; i < markers.length; i++) {
    if (markers[i].time <= state.currentTime + 1e-9) currentId = markers[i].id;
  }
  const rows = this.chaptersEl.querySelectorAll('.sp-chap');
  for (let i = 0; i < rows.length; i++) {
    const on = rows[i].dataset.markerId === String(currentId);
    rows[i].classList.toggle('sp-chap-on', on);
    const ico = rows[i].querySelector('.sp-chap-ico');
    const lab = rows[i].querySelector('.sp-chap-state-label');
    if (ico) ico.textContent = on ? '\u2713' : '\u00B7';
    if (lab) lab.textContent = on ? 'NOW' : ('CH ' + (i + 1));
  }
};

// Dock chapters beside the terminal when the mount is tall and wide enough; otherwise
// keep the classic right-edge overlay (manual `c` / ☰). Most session-browser and
// fullscreen layouts clear this bar; phones and short embeds do not.
Player.prototype.canDockChapters = function () {
  if (!this.root || !this.chaptersEl || !this.controlsCfg.chapters) return false;
  const markers = this.controller.getState().markers;
  if (!markers || !markers.length) return false;
  return this.root.clientHeight >= 420 && this.root.clientWidth >= 640;
};

Player.prototype.syncChaptersLayout = function () {
  if (!this.root || !this.chaptersEl) return;
  const dock = this.canDockChapters();
  const wasDock = this.root.classList.contains('sp-chapters-dock');
  this.root.classList.toggle('sp-chapters-dock', dock);
  if (dock) {
    if (!this._chaptersUserClosed && this.chaptersEl.hidden) {
      this.toggleChapters(true, { silent: true, auto: true });
    }
  } else if (wasDock && this._chaptersAutoOpened && !this.chaptersEl.hidden) {
    this.toggleChapters(false, { auto: true });
    this._chaptersAutoOpened = false;
  }
};

Player.prototype.syncChaptersUi = function (state) {
  if (this.chapBtn) this.chapBtn.hidden = !(state.markers && state.markers.length);
  this.syncChaptersLayout();
  if (!this.chaptersEl || this.chaptersEl.hidden) return;
  // Rebuilding the list on every playback tick destroys the buttons mid-click — only
  // rebuild when the marker set changes; otherwise refresh the current-chapter highlight.
  const markers = state.markers || [];
  const key = markers.map(function (m) {
    return m.id + '\0' + m.time + '\0' + (m.label || '');
  }).join('\n');
  if (key !== this._chaptersRenderKey) this.renderChapters(state);
  else this.markCurrentChapter(state);
};

Player.prototype.toggleSpeedMenu = function (force) {
  if (!this.speedMenuEl) return;
  const show = force != null ? force : this.speedMenuEl.hidden;
  if (show === !this.speedMenuEl.hidden) return;
  const self = this;
  if (show) {
    this.renderSpeedMenu();
    this.speedMenuEl.hidden = false;
    if (this.speedBtn) this.speedBtn.setAttribute('aria-expanded', 'true');
    const current = this.speedMenuEl.querySelector('.sp-on') || this.speedMenuEl.querySelector('button');
    if (current) try { current.focus({ preventScroll: true }); } catch (_) { current.focus(); }
    this.speedAway = function () { self.toggleSpeedMenu(false); };
    document.addEventListener('click', this.speedAway);
  } else {
    this.speedMenuEl.hidden = true;
    if (this.speedBtn) {
      this.speedBtn.setAttribute('aria-expanded', 'false');
      try { this.speedBtn.focus({ preventScroll: true }); } catch (_) {}
    }
    if (this.speedAway) { document.removeEventListener('click', this.speedAway); this.speedAway = null; }
  }
};

Player.prototype.renderSpeedMenu = function () {
  if (!this.speedMenuEl) return;
  const self = this;
  const speed = this.controller.speed;
  this.speedMenuEl.innerHTML = '';
  for (let i = SPEEDS.length - 1; i >= 0; i--) {
    const v = SPEEDS[i];
    const b = document.createElement('button');
    b.type = 'button';
    b.className = 'sp-speedopt' + (v === speed ? ' sp-on' : '');
    b.setAttribute('role', 'menuitemradio');
    b.setAttribute('aria-checked', v === speed ? 'true' : 'false');
    b.textContent = String(v).replace(/\.0$/, '') + '×';
    b.addEventListener('click', (function (s) {
      return function (ev) {
        ev.stopPropagation();
        self.setSpeed(s, 'pointer');
        self.toggleSpeedMenu(false);
      };
    })(v));
    this.speedMenuEl.appendChild(b);
  }
};

Player.prototype.onKey = function (ev) {
  if (ev.metaKey || ev.ctrlKey || ev.altKey) return;
  // Escape closes menus first.
  if (ev.key === 'Escape') {
    if (this.speedMenuEl && !this.speedMenuEl.hidden) {
      this.toggleSpeedMenu(false);
      ev.preventDefault();
      return;
    }
    if (this.chaptersEl && !this.chaptersEl.hidden) {
      this.toggleChapters(false);
      ev.preventDefault();
      return;
    }
  }
  // Speed-menu focus travel only — chapter arrows are chapter jumps (below), not menu nav.
  const speedMenu = this.speedMenuEl && !this.speedMenuEl.hidden ? this.speedMenuEl : null;
  if (speedMenu && ['ArrowUp', 'ArrowDown', 'Home', 'End'].indexOf(ev.key) !== -1) {
    const items = Array.prototype.slice.call(speedMenu.querySelectorAll('button:not([hidden])'));
    if (!items.length) return;
    let index = items.indexOf(document.activeElement);
    if (ev.key === 'Home') index = 0;
    else if (ev.key === 'End') index = items.length - 1;
    else index = (index + (ev.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length;
    items[index].focus();
    ev.preventDefault();
    ev.stopPropagation();
    return;
  }
  // Chapters panel: Home/End still move focus among rows; Up/Down jump chapters.
  const chapMenu = this.chaptersEl && !this.chaptersEl.hidden ? this.chaptersEl : null;
  if (chapMenu && (ev.key === 'Home' || ev.key === 'End')) {
    const items = Array.prototype.slice.call(chapMenu.querySelectorAll('button:not([hidden])'));
    if (!items.length) return;
    items[ev.key === 'Home' ? 0 : items.length - 1].focus();
    ev.preventDefault();
    ev.stopPropagation();
    return;
  }
  const k = ev.key;
  if (k === ' ') this.toggle('keyboard');
  else if (k === 'ArrowLeft') this.seek(this.getCurrentTime() - SEEK_STEP_SECS, 'keyboard');
  else if (k === 'ArrowRight') this.seek(this.getCurrentTime() + SEEK_STEP_SECS, 'keyboard');
  else if (k === 'ArrowUp') this.chapterToast(this.controller.jumpMarker(-1, 'keyboard'));
  else if (k === 'ArrowDown') this.chapterToast(this.controller.jumpMarker(1, 'keyboard'));
  else if (k === '<' || k === ',') this.controller.cycleSpeed(-1, 'keyboard');
  else if (k === '>' || k === '.') this.controller.cycleSpeed(1, 'keyboard');
  else if (k === '[') this.chapterToast(this.controller.jumpMarker(-1, 'keyboard'));
  else if (k === ']') this.chapterToast(this.controller.jumpMarker(1, 'keyboard'));
  else if (k.length === 1 && k >= '0' && k <= '9') this.jumpChapterIndex(k.charCodeAt(0) - 48, 'keyboard');
  else if (k === 'c' || k === 'C') {
    if (!this.hasChapters()) return;
    this.toggleChapters();
  }
  else if (k === 'f' || k === 'F') this.toggleFullscreen();
  else return;
  ev.preventDefault();
  ev.stopPropagation();
};

// True when `mount`'s height does not depend on `box` — i.e. the embedding page gave the
// mount a definite height (%, vh, flex/grid stretch, …). A content-sized mount shrinks when
// the box does; vertical fit against that height is a ResizeObserver shrink ratchet.
Player.prototype.mountHeightIsDefinite = function (mount, box) {
  if (!mount || !box) return false;
  const prev = box.style.height;
  const before = mount.clientHeight;
  box.style.height = '0px';
  const after = mount.clientHeight;
  box.style.height = prev;
  return before > 0 && before === after;
};

Player.prototype.layout = function () {
  if (!this.fit || !this.root || this._layouting) return;
  this._layouting = true;
  try {
    this.syncChaptersLayout();
    const box = this.root.querySelector('.sp-screen-box');
    if (!box || !this.screenEl) return;
    this.screenEl.style.transform = '';
    this.screenEl.style.marginLeft = '';
    const rect = this.screenEl.getBoundingClientRect();
    const naturalW = rect.width, naturalH = rect.height;
    if (!(naturalW > 0 && naturalH > 0)) return;

    const fs = typeof document !== 'undefined' ? document.fullscreenElement : null;
    const rootFs = fs === this.root;
    const wrapFs = !!(this.fsEl && fs === this.fsEl);
    const bar = this.root.querySelector('.sp-bar');
    const barH = bar ? Math.max(bar.offsetHeight, Math.ceil(bar.getBoundingClientRect().height)) : 0;

    // Width budget: the screen pane, falling back to the mount/fullscreen host.
    let availW = box.clientWidth;
    if (!(availW > 0)) {
      const host = rootFs ? this.root : (wrapFs ? this.fsEl : this.root.parentNode);
      availW = host ? host.clientWidth : 0;
    }
    // A fullscreen host page can let max-content children blow the pane out sideways
    // (e.g. a grid wrapper without minmax(0,1fr)): the box then measures wider than the
    // screen itself and no horizontal scale is applied. In fullscreen nothing may budget
    // wider than the fullscreen element, minus a visible docked chapter panel.
    const fsHost = rootFs ? this.root : (wrapFs ? this.fsEl : null);
    let fsCap = 0;
    if (fsHost && fsHost.clientWidth > 0) {
      let cap = fsHost.clientWidth;
      if (this.root.classList.contains('sp-chapters-dock') && this.chaptersEl && !this.chaptersEl.hidden) {
        cap -= this.chaptersEl.offsetWidth;
      }
      if (cap > 40) {
        fsCap = cap;
        availW = availW > 0 ? Math.min(availW, cap) : cap;
      }
    }
    let scale = availW > 0 && naturalW > availW ? availW / naturalW : 1;

    // fit:'both' honors a definite mount height only. Fullscreen hosts are definite by
    // construction; a content-sized parent (scsh's live dashboard pane, etc.) must not
    // drive vertical scale — measure→scale→write→ResizeObserver would ratchet forever.
    if (this.fit === 'both') {
      let availH = 0;
      let definite = false;
      if (rootFs) {
        availH = this.root.clientHeight - barH;
        definite = true;
      } else if (wrapFs && this.fsEl) {
        // Prefer the mount (.cast-player) height: the fullscreen host may also include a
        // page toolbar above the player (scsh). Measuring fsEl and only subtracting our
        // own bar over-stated availH, then a later ResizeObserver tick corrected it —
        // the visible "grows after a second and clips 1×" jump.
        const mount = this.root.parentNode;
        const hostH = (mount && mount.clientHeight > 0) ? mount.clientHeight : this.fsEl.clientHeight;
        availH = hostH - barH;
        definite = true;
      } else if (this.root.parentNode) {
        const mount = this.root.parentNode;
        definite = this.mountHeightIsDefinite(mount, box);
        if (definite) availH = mount.clientHeight - barH;
      }
      // Docked chapters sit beside the terminal inside the stage; the height budget is
      // the stage (root minus bar), same as fullscreen.
      if (definite && this.root.classList.contains('sp-chapters-dock') && this.stageEl) {
        const stageH = this.stageEl.clientHeight;
        if (stageH > 40) availH = stageH;
      }
      if (definite && availH > 40 && naturalH * scale > availH) {
        scale = Math.min(scale, availH / naturalH);
      }
    }

    const displayH = naturalH * scale;
    const displayW = naturalW * scale;
    const transform = scale < 1 ? 'scale(' + scale + ')' : '';
    const height = displayH + 'px';
    // Center within the VISIBLE pane: on a host that lets the pane overflow the
    // fullscreen element, box.clientWidth is a lie and would center off-screen.
    let paneW = box.clientWidth || availW;
    if (fsCap > 0) paneW = Math.min(paneW, fsCap);
    const margin = paneW > displayW ? (paneW - displayW) / 2 + 'px' : '';
    // Idempotent: skip style writes that would only re-arm ResizeObserver.
    if (this._layoutScale === scale && this.screenEl.style.transform === transform &&
        box.style.height === height && this.screenEl.style.marginLeft === margin) {
      return;
    }
    this._layoutScale = scale;
    this.screenEl.style.transform = transform;
    // The layout box must match the DISPLAY size: scale() does not shrink layout, and a
    // taller box was what pushed the control bar off-screen in fullscreen.
    box.style.height = height;
    this.screenEl.style.marginLeft = margin;
  } finally {
    this._layouting = false;
  }
};

Player.prototype.toggleFullscreen = function () {
  const el = this.fsEl || this.root;
  if (!el) return;
  if (document.fullscreenElement === el) {
    if (document.exitFullscreen) document.exitFullscreen();
  } else if (el.requestFullscreen) {
    el.requestFullscreen();
  }
};

// A [ / ] / ↑ / ↓ jump (or a digit 0–9 pick) names the chapter it landed on in a brief
// bottom-center toast that fades on its own; role="status" lets screen readers announce it.
// Visual language matches scsh job-graph cards (left accent, state / title / meta).
Player.prototype.chapterToast = function (target) {
  if (!target || !this.toastEl) return;
  const markers = this.controller.getState().markers;
  let index = -1;
  for (let i = 0; i < markers.length; i++) {
    if (markers[i].time === target.time) { index = i; break; }
  }
  const landed = index >= 0 ? markers[index] : target;
  const name = landed.label || fmtClock(landed.time);
  const meta = index >= 0
    ? (index + 1) + '/' + markers.length + ' · ' + fmtClock(landed.time)
    : fmtClock(landed.time);
  this.showToastCard({ state: 'CHAPTER', title: name, meta: meta });
};

// Jump to the chapter at 0-based `index` (digit keys 0–9). Seek only — no autoplay.
Player.prototype.jumpChapterIndex = function (index, origin) {
  const markers = this.controller.getState().markers;
  if (!markers.length || index < 0 || index >= markers.length) return null;
  const marker = markers[index];
  this.seek(marker.time, origin || 'keyboard');
  this.chapterToast(marker);
  return marker;
};

Player.prototype.showToastCard = function (bits) {
  const el = this.toastEl;
  if (!el || !bits) return;
  const self = this;
  el.textContent = '';
  const state = document.createElement('span');
  state.className = 'sp-toast-state';
  const ico = document.createElement('span');
  ico.className = 'sp-toast-ico';
  ico.setAttribute('aria-hidden', 'true');
  ico.textContent = '\u2713';
  const lab = document.createElement('span');
  lab.className = 'sp-toast-state-label';
  lab.textContent = bits.state || 'CHAPTER';
  state.appendChild(ico);
  state.appendChild(document.createTextNode(' '));
  state.appendChild(lab);
  const id = document.createElement('span');
  id.className = 'sp-toast-id';
  id.textContent = bits.title || '';
  const meta = document.createElement('span');
  meta.className = 'sp-toast-meta';
  meta.textContent = bits.meta || '';
  el.appendChild(state);
  el.appendChild(id);
  el.appendChild(meta);
  el.classList.remove('sp-toast-show');
  // Retrigger the transition when the same chapter fires twice in a row.
  void el.offsetWidth;
  el.classList.add('sp-toast-show');
  clearTimeout(this.toastTimer);
  this.toastTimer = setTimeout(function () {
    if (self.toastEl) self.toastEl.classList.remove('sp-toast-show');
  }, 2000);
};

Player.prototype.play = function (origin) { this.controller.play(origin); };
Player.prototype.pause = function (origin) { this.controller.pause(origin); };
Player.prototype.toggle = function (origin) { this.controller.toggle(origin); };
Player.prototype.seek = function (t, origin) {
  this.controller.seek(t, { origin: origin || 'api' });
};
Player.prototype.setSpeed = function (v, origin) { this.controller.setSpeed(v, origin); };
Player.prototype.getCurrentTime = function () { return this.controller.getCurrentTime(); };
Player.prototype.getState = function () { return this.controller.getState(); };
Player.prototype.append = function (text) { this.controller.append(text); };
Player.prototype.setLive = function (on, origin) { this.controller.setLive(on, origin || 'api'); };
Player.prototype.subscribe = function (fn) { return this.controller.subscribe(fn); };

Player.prototype.dispose = function () {
  if (this.disposed) return;
  this.disposed = true;
  if (this.unsubscribe) { this.unsubscribe(); this.unsubscribe = null; }
  clearTimeout(this.toastTimer);
  this.controller.dispose();
  if (this.speedAway) { document.removeEventListener('click', this.speedAway); this.speedAway = null; }
  if (this.resizeObs) { try { this.resizeObs.disconnect(); } catch (_) {} this.resizeObs = null; }
  if (this.fsHandler) {
    try { document.removeEventListener('fullscreenchange', this.fsHandler); } catch (_) {}
    this.fsHandler = null;
  }
  if (this.root && this.root.parentNode) this.root.parentNode.removeChild(this.root);
  this.root = null;
};

// ---- Web Component ---------------------------------------------------------------------
// Preferred browser integration. Light DOM so the embedding page's inlined PLAYER_CSS
// styles the controls (Shadow DOM would require shipping CSS inside the JS bundle).
// part attributes mark stable styling hooks for when an open shadow root is added later.
function registerComponent() {
  if (typeof customElements === 'undefined' || typeof HTMLElement === 'undefined') return;
  if (customElements.get('beecast-player')) return;

  class BeeCastPlayerElement extends HTMLElement {
    static get observedAttributes() {
      // Only the attributes that are live after mount; the rest are read at mount time.
      return ['fit', 'speed', 'theme'];
    }

    constructor() {
      super();
      this._player = null;
      this._pending = {};
      this._connected = false;
    }

    connectedCallback() {
      this._connected = true;
      this.style.display = this.style.display || 'block';
      if (!this._player) this._mountPlayer();
    }

    disconnectedCallback() {
      this._connected = false;
      if (this._player) {
        this._player.dispose();
        this._player = null;
      }
    }

    attributeChangedCallback(name, oldV, newV) {
      if (oldV === newV || !this._player) return;
      if (name === 'speed') this._player.setSpeed(Number(newV) || 1);
      if (name === 'fit') { this._player.fit = newV || null; this._player.layout(); }
      if (name === 'theme' && this._player.root) {
        if (newV) this._player.root.setAttribute('data-theme', newV);
        else this._player.root.removeAttribute('data-theme');
      }
    }

    _optsFromAttributes() {
      const opts = {};
      if (this.hasAttribute('fit')) opts.fit = this.getAttribute('fit');
      if (this.hasAttribute('autoplay')) opts.autoPlay = this.getAttribute('autoplay') !== 'false';
      if (this.hasAttribute('idle-time-limit')) {
        opts.idleTimeLimit = Number(this.getAttribute('idle-time-limit'));
      }
      if (this.hasAttribute('speed')) opts.speed = Number(this.getAttribute('speed'));
      if (this.hasAttribute('start-at')) opts.startAt = this.getAttribute('start-at');
      if (this.hasAttribute('controls')) {
        opts.controls = this.getAttribute('controls') === 'false' ? false : true;
      }
      if (this.hasAttribute('accessibility')) {
        opts.accessibility = this.getAttribute('accessibility');
      }
      if (this._pending.markers) opts.markers = this._pending.markers;
      if (this._pending.speed != null) opts.speed = this._pending.speed;
      if (this._pending.startAt != null) opts.startAt = this._pending.startAt;
      if (this._pending.fit != null) opts.fit = this._pending.fit;
      if (this._pending.controls != null) opts.controls = this._pending.controls;
      if (this._pending.autoPlay != null) opts.autoPlay = this._pending.autoPlay;
      if (this._pending.idleTimeLimit != null) opts.idleTimeLimit = this._pending.idleTimeLimit;
      if (this._pending.fullscreenEl) opts.fullscreenEl = this._pending.fullscreenEl;
      if (this._pending.clock) opts.clock = this._pending.clock;
      if (this._pending.accessibility) opts.accessibility = this._pending.accessibility;
      return opts;
    }

    _mountPlayer() {
      while (this.firstChild) this.removeChild(this.firstChild);
      const data = this._pending.cast != null ? this._pending.cast
        : (this._pending.data != null ? this._pending.data : '');
      const opts = this._optsFromAttributes();
      const player = new Player({ data: data, source: this._pending.source }, this, opts);
      player.eventTarget = this;
      this._player = player;
      const theme = this.getAttribute('theme') || this._pending.theme;
      if (theme && player.root) player.root.setAttribute('data-theme', theme);
    }

    load(opts) {
      opts = opts || {};
      if (opts.cast != null) this._pending.cast = opts.cast;
      if (opts.data != null) this._pending.cast = opts.data;
      if (opts.metadata) this._pending.metadata = opts.metadata;
      if (opts.markers) this._pending.markers = opts.markers;
      if (opts.source) this._pending.source = opts.source;
      if (opts.speed != null) this._pending.speed = opts.speed;
      if (opts.startAt != null) this._pending.startAt = opts.startAt;
      if (opts.autoPlay != null) this._pending.autoPlay = opts.autoPlay;
      if (!this._connected) return;
      if (this._player) {
        this._player.controller.load({
          data: this._pending.cast,
          markers: this._pending.markers,
          startAt: this._pending.startAt,
          autoPlay: this._pending.autoPlay,
        });
        if (opts.speed != null) this._player.setSpeed(opts.speed);
      } else {
        this._mountPlayer();
      }
    }

    play() { if (this._player) this._player.play('api'); }
    pause() { if (this._player) this._player.pause('api'); }
    toggle() { if (this._player) this._player.toggle('api'); }
    seek(t) { if (this._player) this._player.seek(t, 'api'); }
    setSpeed(v) { if (this._player) this._player.setSpeed(v, 'api'); }
    append(t) { if (this._player) this._player.append(t); }
    getCurrentTime() { return this._player ? this._player.getCurrentTime() : 0; }
    dispose() {
      if (this._player) { this._player.dispose(); this._player = null; }
    }

    get state() { return this._player ? publicState(this._player.getState()) : null; }
    get cast() { return this._pending.cast; }
    set cast(v) { this._pending.cast = v; if (this._player) this.load({ cast: v }); }
    get markers() { return this._pending.markers; }
    set markers(v) {
      this._pending.markers = v;
      if (this._player) this._player.controller.setMarkers(v);
    }
    get speed() {
      return this._player ? this._player.controller.speed : Number(this.getAttribute('speed')) || 1;
    }
    set speed(v) { this._pending.speed = v; if (this._player) this._player.setSpeed(v); }
  }

  try {
    customElements.define('beecast-player', BeeCastPlayerElement);
    root.BeeCastPlayerElement = BeeCastPlayerElement;
  } catch (_) {
    // Legacy create() still works without custom elements.
  }
}

registerComponent();

// ---- public API ------------------------------------------------------------------------
// BeeCastPlayer.create remains the compatibility factory: a thin Player over the controller.
// New integrations should prefer <beecast-player> or BeeCastController directly.
root.BeeCastPlayer = {
  create: function (src, mount, opts) { return new Player(src, mount, opts); },
  Player: Player,
  elementName: 'beecast-player',
  SPEEDS: SPEEDS,
  // Documented public surface snapshot for compatibility fixtures (Phase 0).
  publicMethods: [
    'create', 'play', 'pause', 'toggle', 'seek', 'getCurrentTime', 'append', 'dispose',
    'setSpeed', 'getState', 'subscribe',
  ],
  supportedCssVariables: [
    '--beecast-color-surface',
    '--beecast-color-surface-raised',
    '--beecast-color-text',
    '--beecast-color-text-muted',
    '--beecast-color-accent',
    '--beecast-color-focus',
    '--beecast-color-marker',
    '--beecast-color-error',
    '--beecast-control-height',
    '--beecast-radius',
    '--beecast-font-ui',
    '--beecast-font-terminal',
    '--sp-bg', '--sp-fg',
    '--sp-c0', '--sp-c1', '--sp-c2', '--sp-c3', '--sp-c4', '--sp-c5', '--sp-c6', '--sp-c7',
    '--sp-c8', '--sp-c9', '--sp-c10', '--sp-c11', '--sp-c12', '--sp-c13', '--sp-c14', '--sp-c15',
  ],
  // Readable during migration but not public API — do not depend on these.
  nonPublicFields: ['playing', 'pacedPos', 'eventIdx', 'cast', 'term', 'pacing', 'raf'],
};

})(typeof window !== 'undefined' ? window : globalThis);