aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/music-player.js
blob: 5f2e33c59b373361061df2d0eec9829f413502c1 (plain) (blame)
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
import {
  html, useState, useEffect, useReducer, useRef, useCallback,
} from './vendor/htm-preact.js';
import { queueReducer, emptyQueue } from './queue-ops.js';
import { t } from './i18n.js';
import { Icon } from './icon.js';
import { useStickyBand } from './sticky.js';
import { CHUNK_SIZE, pipelinedDownload } from './file-utils.js';

/**
 * The Music app's persistent player bar (docs/MESHBAY_DESIGN.md §9.8).
 *
 * Owned and rendered by app.js — the router's parent — so playback survives
 * navigating between groups, search, and other pages. Both group-page.js
 * and search-page.js trigger playback by calling `onPlayQueue(tracks,
 * startIndex)`, which flows up to app.js.
 *
 * Each track carries a `groupId`; the player calls `getConnection(groupId)`
 * per track to obtain the right transport — a pool-based lazy connection
 * that transparently handles single-group and cross-group queues.
 *
 * No streaming, no MSE, no node-side transcode pool for the common case: a
 * track is a few megabytes, so it is downloaded and decrypted once through
 * the same chunk pipeline Files already uses (file-utils.js's
 * pipelinedDownload), then played from a blob URL — the deliberate
 * simplification recorded in docs/MESHBAY_DESIGN.md §9.8. WMA and Musepack are
 * the one exception (`NEEDS_TRANSCODE_RE` below): neither decodes in a
 * browser's <audio> element at all, tagged correctly or not, so those two go
 * through `transport.requestAudioTranscode` first — a node-side,
 * cached-after-once AAC/M4A conversion — before the same download/blob path
 * runs.
 */

const MIME_BY_EXT = {
  mp3: 'audio/mpeg', flac: 'audio/flac', ogg: 'audio/ogg', opus: 'audio/opus',
  wav: 'audio/wav', aac: 'audio/aac', m4a: 'audio/mp4',
};

// The same two formats as the node's BROWSER_INCOMPATIBLE_AUDIO_EXTS
// (webrtc_server.py), which is the one that decides: the node refuses a
// transcode request for anything else. This is here so the player does not
// ask for one it knows will be refused — not because it enforces the rule.
// It used to be the only thing that did, and a member's own message never
// passed through it.
const NEEDS_TRANSCODE_RE = /\.(wma|mpc)$/i;

function guessMime(name) {
  const ext = (name || '').split('.').pop().toLowerCase();
  return MIME_BY_EXT[ext] || 'audio/mpeg';
}

function formatTime(seconds) {
  if (!isFinite(seconds) || seconds < 0) return '0:00';
  const total = Math.floor(seconds);
  const m = Math.floor(total / 60);
  const s = total % 60;
  return `${m}:${String(s).padStart(2, '0')}`;
}

// Bounded: only the currently playing track plus the read-ahead window are
// ever worth holding in memory. Older blob URLs are revoked, not merely
// dropped — otherwise every track played in a session leaks its object URL.
// Sized for the largest read-ahead prefetchDepth() can return (currently
// playing + 5 on Wi-Fi) — a smaller run on cellular just evicts sooner.
const MAX_CACHED_BLOBS = 6;

/**
 * How many tracks to warm the cache for, ahead of the one playing.
 *
 * A prefetched track needs no live connection to play — it is exactly what
 * buys time through a screen-lock network gap (see transport.js's
 * auto-reconnect) — so the more of a mobile-data budget it is safe to spend
 * on tracks that might not even get listened to, the better the odds a lock
 * of ordinary length is fully covered by tracks already sitting in
 * blobCacheRef. Wi-Fi is effectively free and usually fast, so 5; a metered
 * connection (or one this API cannot see at all) gets 3 — enough to matter,
 * not so much it burns a noticeable chunk of a data plan on an album that
 * might get abandoned after track one.
 *
 * `navigator.connection` is Chromium-only (Chrome, Edge, Electron) — plain
 * `undefined` on Firefox and Safari, where this must fall through to the
 * conservative tier exactly as it would for a cellular connection it could
 * name. Never assume "fast" from the absence of a signal that says so.
 */
function prefetchDepth() {
  const conn = navigator.connection;
  if (conn && conn.type === 'wifi') return 5;
  return 3;
}

function loadVolume() {
  try {
    const v = parseFloat(localStorage.getItem('meshbay_music_volume'));
    return isFinite(v) && v >= 0 && v <= 1 ? v : 1;
  } catch { return 1; }
}
function saveVolume(v) {
  try { localStorage.setItem('meshbay_music_volume', String(v)); } catch { /* per-device only */ }
}
function loadShuffle() {
  try { return localStorage.getItem('meshbay_music_shuffle') === '1'; } catch { return false; }
}
function saveShuffle(v) {
  try { localStorage.setItem('meshbay_music_shuffle', v ? '1' : '0'); } catch { /* per-device only */ }
}
function loadRepeat() {
  try {
    const v = localStorage.getItem('meshbay_music_repeat');
    return v === 'all' || v === 'one' ? v : 'off';
  } catch { return 'off'; }
}
function saveRepeat(v) {
  try { localStorage.setItem('meshbay_music_repeat', v); } catch { /* per-device only */ }
}

// The current queue, tracklist form -- "go back to what's playing" without
// switching tabs or hunting for the album/folder it came from. Works the
// same regardless of how the queue was built (an album, a consolidated
// misc/loose bucket, a single standalone track).
//
// The header alone ("Playing now") named the *panel*, not the track — on a
// long queue the highlighted row can be scrolled out of view entirely, so
// opening this told you nothing you didn't already know. It now shows the
// current track's own title/artist right under the header, and scrolls the
// highlighted row into view on open rather than leaving it to be found.
function QueuePanel({ tracks, order, pos, onSelect, onClose, onSaveAsPlaylist }) {
  const activeRowRef = useRef(null);
  useEffect(() => {
    if (activeRowRef.current) {
      activeRowRef.current.scrollIntoView({ block: 'center' });
    }
  }, []);

  const current = tracks[order[pos]];

  return html`
    <div class="video-overlay" onClick=${(e) => {
      if (e.target.classList.contains('video-overlay')) onClose();
    }}>
      <div class="music-detail">
        <div class="video-top-bar">
          <span class="video-title">${t('music.queue_title')}</span>
          ${/* "Save the current queue as a playlist" lives here rather than in
                Music's toolbar menu, because this panel is where the current
                queue is a thing the reader can actually see — and because the
                queue is the player's own state, which a menu in a different
                component would have to have lifted out of it. */''}
          ${onSaveAsPlaylist && html`
            <button class="video-close" title=${t('playlists.save_queue')}
              onClick=${() => onSaveAsPlaylist(order.map((i) => tracks[i]))}>
              <${Icon} name="playlist" /></button>
          `}
          <button class="video-close" onClick=${onClose} title=${t('video.close')}>
            <${Icon} name="close" /></button>
        </div>
        ${current && html`
          <div class="music-queue-now-playing">
            <span class="music-queue-now-playing-title">
              ${current.display_title || current.name}</span>
            ${current.artist && html`
              <span class="music-queue-now-playing-artist"> — ${current.artist}</span>`}
          </div>
        `}
        <div class="music-detail-body">
          <div class="music-tracklist">
            ${order.map((idx, i) => html`
              <button class="music-track-row ${i === pos ? 'active' : ''}" key=${tracks[idx].id}
                ref=${i === pos ? activeRowRef : null}
                onClick=${() => { onSelect(i); onClose(); }}>
                <span class="music-track-no">${i + 1}</span>
                <span class="music-track-title">${tracks[idx].display_title || tracks[idx].name}</span>
                <span class="music-track-duration">${formatTime(tracks[idx].duration || 0)}</span>
              </button>
            `)}
          </div>
        </div>
      </div>
    </div>
  `;
}

function MusicPlayerBar({ getConnection, queue, onClose, userPrefs, onSaveQueue }) {
  // Pinned to the bottom of the window, over the bottom of the sidebar; the
  // sidebar subtracts this so its last entry is not underneath.
  const barBand = useStickyBand('--music-bar-h');
  const audioRef = useRef(null);
  const blobCacheRef = useRef(new Map()); // file id -> { url, order: insertion index }
  const blobInsertRef = useRef(0);
  const loadTokenRef = useRef(0);

  // The queue: every entry, the play order over it, and where in that order
  // we are (docs/playlists.md §9.3). One reducer rather than three useStates
  // because "add to queue" derives its new indices from the current track
  // count, and two appends batched into one tick cannot both see it.
  const [queueState, dispatch] = useReducer(queueReducer, null, emptyQueue);
  const { tracks, order, pos } = queueState;
  const [playing, setPlaying] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [shuffle, setShuffle] = useState(loadShuffle);
  const [repeat, setRepeat] = useState(loadRepeat); // 'off' | 'all' | 'one'
  const [volume, setVolume] = useState(loadVolume);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [showQueue, setShowQueue] = useState(false);
  // A broken source file (truncated download, a format the browser has no
  // decoder for) must not stall a "play all" queue on the one track that
  // failed — found live against a real library: a corrupt few-hundred-byte
  // file with no audio stream at all, sitting between two good tracks.
  // Bounded so a queue that turns out to be *entirely* bad (every file the
  // same unsupported format) fails once, visibly, rather than burning
  // through the whole list in an instant.
  const consecutiveFailuresRef = useRef(0);
  const MAX_CONSECUTIVE_FAILURES = 5;
  const prefetchAfterInsertRef = useRef(false);
  // Groups that did not answer this session. A playlist crosses groups, and
  // one of them being off is a property of that group rather than of each of
  // its tracks in turn — see advancePastFailure below (docs/playlists.md §11.3).
  const downGroupsRef = useRef(new Set());

  const currentTrack = tracks[order[pos]] || null;

  /**
   * Move past a track that will not play.
   *
   * Two failures, and they are properties of different things:
   *
   * A **decode** failure belongs to that file — a truncated download, a format
   * with no decoder. The bounded counter is right for it: a queue that turns
   * out to be entirely bad fails once, visibly, rather than burning through
   * the whole list in an instant.
   *
   * A **connection** failure belongs to that *group*. The same bound applied
   * to it is a regression playlists introduce into code that is correct today:
   * a playlist whose next six tracks all come from one node that is off stops
   * at the sixth, with an error, and the reader sees "the playlist is broken".
   * So the group is marked down and every one of its queued tracks is skipped
   * in one step, with the counter reset — which is what the bound was
   * protecting in the first place.
   */
  const advancePastFailure = useCallback((groupDown) => {
    if (order.length <= 1) return;
    let next = pos + 1;
    if (groupDown) {
      downGroupsRef.current.add(groupDown);
      consecutiveFailuresRef.current = 0;
      while (next < order.length
             && downGroupsRef.current.has(tracks[order[next]]
                                          && tracks[order[next]].groupId)) {
        next += 1;
      }
    } else {
      consecutiveFailuresRef.current += 1;
      if (consecutiveFailuresRef.current > MAX_CONSECUTIVE_FAILURES) return;
    }
    if (next < order.length) { dispatch({ type: 'skipTo', pos: next }); return; }
    if (repeat === 'all') dispatch({ type: 'skipTo', pos: 0 });
    // Nothing left that can play. Stopping once, with the error already on
    // screen, is the honest end — and is what the bound above exists to reach.
  }, [tracks, order, pos, repeat]);

  // Stops playback the moment this bar goes away for any reason -- the
  // close button below, or the shell tearing it down on its own (leaving
  // the group, switching to a different one). A component removed from the
  // DOM should already stop an <audio> element, but that's the browser's
  // behaviour to rely on, not this app's to assert; pausing explicitly, and
  // releasing every cached blob URL rather than leaving them for the tab's
  // lifetime, costs nothing and isn't optional either way.
  useEffect(() => () => {
    const audio = audioRef.current;
    if (audio) { audio.pause(); audio.src = ''; }
    for (const { url } of blobCacheRef.current.values()) URL.revokeObjectURL(url);
  }, []);

  // Screen Wake Lock, opt-in only (Settings → music_keep_screen_on) and only
  // while a track is actually playing — off by default because the ordinary
  // expectation, matching Spotify/Deezer, is that the phone locks on its own
  // idle timer while listening (docs/MESHBAY_DESIGN.md §9.8). Unlike the video
  // player's unconditional lock, this must not fight that default for
  // everyone who never asked for it; it exists for whoever explicitly wants
  // to trade battery for riding out the WebRTC screen-lock reconnect gap
  // without waiting on it at all.
  useEffect(() => {
    if (!playing) return;
    if (!(userPrefs && userPrefs.music_keep_screen_on === 'true')) return;
    if (!('wakeLock' in navigator)) return;
    let sentinel = null;
    let cancelled = false;
    const acquire = async () => {
      try {
        const wl = await navigator.wakeLock.request('screen');
        if (cancelled) { try { wl.release(); } catch { /* ignore */ } return; }
        sentinel = wl;
        wl.addEventListener('release', () => { sentinel = null; });
      } catch (e) {
        // Battery saver, no permission, an insecure context — playback has
        // never depended on this, so there is nothing to fall back to.
        console.warn('[MeshBay] Wake lock request failed:', e.message);
      }
    };
    acquire();
    // Released automatically the moment the page goes hidden (spec
    // behaviour) — re-requested here so it holds again once foregrounded,
    // same as the video player's handling of the same event.
    const onVisibility = () => {
      if (document.visibilityState === 'visible' && !sentinel) acquire();
    };
    document.addEventListener('visibilitychange', onVisibility);
    return () => {
      cancelled = true;
      document.removeEventListener('visibilitychange', onVisibility);
      if (sentinel) { try { sentinel.release(); } catch { /* already released */ } }
    };
  }, [playing, userPrefs && userPrefs.music_keep_screen_on]);

  const evictOldBlobs = useCallback(() => {
    const cache = blobCacheRef.current;
    while (cache.size > MAX_CACHED_BLOBS) {
      let oldestId = null, oldestOrder = Infinity;
      for (const [id, v] of cache) {
        if (v.order < oldestOrder) { oldestOrder = v.order; oldestId = id; }
      }
      if (oldestId == null) break;
      URL.revokeObjectURL(cache.get(oldestId).url);
      cache.delete(oldestId);
    }
  }, []);

  const fetchTrackBlob = useCallback(async (entry) => {
    const cached = blobCacheRef.current.get(entry.id);
    if (cached) return cached.url;
    // A group that does not answer is marked as such, so the queue can skip
    // all of its tracks at once rather than one failure at a time.
    const groupDown = () => {
      const e = new Error(t('music.err_transport'));
      e.isGroupDown = true;
      return e;
    };
    let transport;
    let gek;
    try {
      ({ transport, gek } = await getConnection(entry.groupId));
    } catch {
      throw groupDown();
    }
    if (!transport) throw groupDown();
    if (!transport.connected) await transport.waitForReconnect();
    if (!transport.connected) throw groupDown();

    let downloadId = entry.id;
    let downloadSize = entry.size;
    let mime = guessMime(entry.name);
    if (NEEDS_TRANSCODE_RE.test(entry.name)) {
      let info;
      try {
        info = await transport.requestAudioTranscode(entry.id);
      } catch (err) {
        throw new Error(t('music.err_transcode'));
      }
      downloadId = info.hash;
      downloadSize = info.size;
      mime = info.mime || 'audio/mp4';
    }

    const totalChunks = Math.ceil(downloadSize / CHUNK_SIZE);
    const chunks = await pipelinedDownload(transport, gek, downloadId, totalChunks);
    const blob = new Blob(chunks, { type: mime });
    const url = URL.createObjectURL(blob);
    blobCacheRef.current.set(entry.id, { url, order: blobInsertRef.current++ });
    evictOldBlobs();
    return url;
  }, [getConnection, evictOldBlobs]);

  // Silently warms the cache for the next tracks so pressing "next" doesn't
  // visibly wait (docs/MESHBAY_DESIGN.md §9.8) — best-effort, never surfaces
  // an error.
  //
  // More than one: a screen lock can cost the transport several minutes (see
  // the WebRTC auto-reconnect in transport.js — this is the other half of
  // the same fix). A track already sitting in blobCacheRef needs no
  // connection at all to play, so whatever got fetched *before* the lock
  // started plays through it regardless of what the connection is doing
  // afterward — see prefetchDepth() for how far ahead that runway goes.
  const prefetchNext = useCallback((fromPos) => {
    const ahead = prefetchDepth();
    const playingGroup = tracks[order[fromPos]] && tracks[order[fromPos]].groupId;
    for (let i = 1; i <= ahead; i++) {
      const nextEntry = tracks[order[fromPos + i]];
      if (!nextEntry || blobCacheRef.current.has(nextEntry.id)) continue;
      // Only what this queue is already connected to. For an album these five
      // share one connection and nothing changes; for a shuffled cross-group
      // playlist they may want five *different* node dials of up to ten
      // seconds each, against a pool of twelve — to warm tracks the reader may
      // never reach (docs/playlists.md §9.5). The rest warm when the queue
      // gets to them and the dial has to happen anyway.
      if (nextEntry.groupId !== playingGroup) continue;
      if (downGroupsRef.current.has(nextEntry.groupId)) continue;
      fetchTrackBlob(nextEntry).catch(() => {});
    }
  }, [tracks, order, fetchTrackBlob]);

  // (Re)initialize the queue whenever the shell hands over a new one.
  // `queue.nonce` changes on every call to onPlayQueue, including "play the
  // same album again from track 0" — a fresh Date.now() each time, so this
  // effect always re-runs rather than bailing out on reference equality.
  useEffect(() => {
    if (!queue) return;
    const op = queue.op || 'replace';
    dispatch({
      type: op === 'next' ? 'insertNext' : op === 'append' ? 'append' : 'replace',
      tracks: queue.tracks,
      startIndex: queue.startIndex,
      shuffle,
    });
    // A deliberate queue change is new material to try, so the runaway bound
    // starts over; the bound exists to stop an automatic advance burning
    // through a bad queue, not to hold a user's own action against them.
    consecutiveFailuresRef.current = 0;
    if (op === 'replace') {
      setError('');
    } else {
      // Nothing that is playing changed, so the play effect below will not
      // run and will not warm anything — but "play next" just put a track at
      // pos + 1 that nobody has fetched. Flagged here, acted on once `order`
      // has actually been rebuilt.
      prefetchAfterInsertRef.current = true;
    }
    // Playback itself starts from the effect below, keyed on [tracks, order, pos].
  }, [queue]);

  useEffect(() => {
    if (!prefetchAfterInsertRef.current) return;
    prefetchAfterInsertRef.current = false;
    if (order.length) prefetchNext(pos);
    // Deliberately not keyed on `pos`: this runs for a queue edit, and the
    // ordinary advance is already covered where the current track loads.
    // eslint-disable-next-line
  }, [order]);

  // Loads and plays whatever `pos` now points to. Runs after the queue
  // effect above (pos/order/tracks all just changed together) and also
  // after skipNext/skipPrev/onEnded update `pos` alone.
  useEffect(() => {
    if (!currentTrack) return;
    const myToken = ++loadTokenRef.current;
    setLoading(true);
    setError('');
    (async () => {
      try {
        const url = await fetchTrackBlob(currentTrack);
        if (loadTokenRef.current !== myToken) return; // superseded by a newer skip
        const audio = audioRef.current;
        if (!audio) return;
        audio.src = url;
        audio.currentTime = 0;
        await audio.play();
        consecutiveFailuresRef.current = 0;
        setPlaying(true);
        prefetchNext(pos);
      } catch (err) {
        if (loadTokenRef.current !== myToken) return;
        setError(err.message || String(err));
        setPlaying(false);
        // `fetchTrackBlob` throws `err_transport` when no node answered for
        // this track's group; anything else is about the file itself.
        advancePastFailure(err.isGroupDown ? currentTrack.groupId : null);
      } finally {
        if (loadTokenRef.current === myToken) setLoading(false);
      }
    })();
    // eslint-disable-next-line
  }, [currentTrack && currentTrack.id]);

  // Belt and suspenders alongside the catch block above: `.play()` rejecting
  // is the common path for a source the browser can't decode at all, but a
  // decode failure can also surface later, asynchronously, as an `error`
  // event on the element itself rather than a rejected promise — found live
  // to matter (a truncated file with a valid-looking header but no audio
  // stream). Both paths converge on the same bounded advance, so whichever
  // fires first, the queue moves on exactly once.
  const handleMediaError = useCallback(() => {
    const audio = audioRef.current;
    const mediaError = audio && audio.error;
    setError((mediaError && mediaError.message) || t('music.err_playback'));
    setPlaying(false);
    advancePastFailure();
  }, [advancePastFailure]);

  useEffect(() => {
    const audio = audioRef.current;
    if (audio) audio.volume = volume;
    saveVolume(volume);
  }, [volume]);

  const skipTo = useCallback((newPos) => dispatch({ type: 'skipTo', pos: newPos }), []);

  const skipNext = useCallback(() => {
    if (order.length === 0) return;
    if (pos + 1 < order.length) { skipTo(pos + 1); return; }
    if (repeat === 'all') { skipTo(0); return; }
    setPlaying(false); // end of queue, nothing to repeat
  }, [pos, order.length, repeat, skipTo]);

  const skipPrev = useCallback(() => {
    if (order.length === 0) return;
    // A few seconds in: restart the current track, the way most players do,
    // rather than always jumping to the previous one.
    const audio = audioRef.current;
    if (audio && audio.currentTime > 3) { audio.currentTime = 0; return; }
    if (pos > 0) { skipTo(pos - 1); return; }
    if (repeat === 'all') { skipTo(order.length - 1); }
  }, [pos, order.length, repeat, skipTo]);

  const onEnded = useCallback(() => {
    if (repeat === 'one') {
      const audio = audioRef.current;
      if (audio) { audio.currentTime = 0; audio.play().catch(() => {}); }
      return;
    }
    skipNext();
  }, [repeat, skipNext]);

  const togglePlaying = useCallback(() => {
    const audio = audioRef.current;
    if (!audio) return;
    if (playing) { audio.pause(); setPlaying(false); }
    else { audio.play().then(() => setPlaying(true)).catch(() => {}); }
  }, [playing]);

  // Reshuffling keeps the currently playing track in place — turning shuffle
  // on mid-album must not interrupt what's already playing. Which track that
  // is, is `order[pos]`; see queue-ops.js on why it is not looked up by id.
  const toggleShuffle = useCallback(() => {
    const next = !shuffle;
    setShuffle(next);
    saveShuffle(next);
    dispatch({ type: 'reshuffle', shuffle: next });
  }, [shuffle]);

  const cycleRepeat = useCallback(() => {
    setRepeat((prev) => {
      const next = prev === 'off' ? 'all' : prev === 'all' ? 'one' : 'off';
      saveRepeat(next);
      return next;
    });
  }, []);

  const seek = useCallback((e) => {
    const audio = audioRef.current;
    if (audio && isFinite(audio.duration)) audio.currentTime = parseFloat(e.target.value);
  }, []);

  const handleClose = useCallback(() => {
    const audio = audioRef.current;
    if (audio) audio.pause();
    if (onClose) onClose();
  }, [onClose]);

  if (!currentTrack) return null;

  const title = currentTrack.display_title || currentTrack.name;
  const repeatLabel = repeat === 'off' ? t('music.player_repeat_off')
    : repeat === 'all' ? t('music.player_repeat_all') : t('music.player_repeat_one');

  return html`
    <div class="music-player-bar" ref=${barBand}>
      <audio ref=${audioRef}
        onTimeUpdate=${(e) => setCurrentTime(e.target.currentTime)}
        onDurationChange=${(e) => setDuration(e.target.duration)}
        onEnded=${onEnded} onError=${handleMediaError} />
      <div class="music-player-info">
        <${Icon} name="music" cls="music-player-icon" />
        <div class="music-player-text">
          <div class="music-player-title">${title}</div>
          <div class="music-player-sub">
            ${[currentTrack.artist, currentTrack.album].filter(Boolean).join(' · ')}
          </div>
        </div>
      </div>
      <div class="music-player-transport">
        <button class="music-player-btn ${shuffle ? 'active' : ''}"
          title=${t('music.player_shuffle')} onClick=${toggleShuffle}>
          <${Icon} name="shuffle" />
        </button>
        <button class="music-player-btn" title=${t('music.player_prev')} onClick=${skipPrev}>
          <${Icon} name="skip-prev" />
        </button>
        <button class="music-player-btn music-player-play" title=${playing ? t('music.player_pause') : t('music.player_play')}
          onClick=${togglePlaying} disabled=${loading}>
          ${loading ? html`<span class="spinner"></span>` : html`<${Icon} name=${playing ? 'pause' : 'play'} />`}
        </button>
        <button class="music-player-btn" title=${t('music.player_next')} onClick=${skipNext}>
          <${Icon} name="skip-next" />
        </button>
        <button class="music-player-btn ${repeat !== 'off' ? 'active' : ''} music-player-repeat-${repeat}"
          title=${repeatLabel} onClick=${cycleRepeat}>
          <${Icon} name="repeat" />
          ${repeat === 'one' && html`<span class="music-repeat-badge">1</span>`}
        </button>
      </div>
      <div class="music-player-seek">
        <span class="music-player-time">${formatTime(currentTime)}</span>
        <input type="range" min="0" max=${duration || 0} step="1" value=${currentTime}
          disabled=${!duration} onInput=${seek} />
        <span class="music-player-time">${formatTime(duration)}</span>
      </div>
      <div class="music-player-volume">
        <${Icon} name="volume" />
        <input type="range" min="0" max="1" step="0.05" value=${volume}
          title=${t('music.player_volume')}
          onInput=${(e) => setVolume(parseFloat(e.target.value))} />
      </div>
      <div class="music-player-extra">
        <button class="music-player-btn" title=${t('music.player_queue')} onClick=${() => setShowQueue(true)}>
          <${Icon} name="menu" />
        </button>
        <button class="music-player-btn" title=${t('music.player_close')} onClick=${handleClose}>
          <${Icon} name="close" />
        </button>
      </div>
      ${error && html`<div class="music-player-error">${error}</div>`}
    </div>
    ${showQueue && html`
      <${QueuePanel} tracks=${tracks} order=${order} pos=${pos}
        onSelect=${skipTo} onClose=${() => setShowQueue(false)}
        ${/* Saved in **play order**, which is what this panel is showing: if
              shuffle is on, that freezes the shuffle, and that is what "save
              what I am listening to" means. */''}
        onSaveAsPlaylist=${onSaveQueue && ((rows) => {
          setShowQueue(false);
          onSaveQueue(rows);
        })} />
    `}
  `;
}

export { MusicPlayerBar, formatTime };