summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/video-app.js
blob: 19b0f0f1b2321a64f9db6ccdcf19368efe1fb13a (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
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
import {
  html, useState, useEffect, useRef, useMemo, useCallback,
} from './vendor/htm-preact.js';
import { t } from './i18n.js';
import { Icon } from './icon.js';
import { formatSize, pipelinedDownload } from './file-utils.js';

// ── Videos ───────────────────────────────────────────────────────────────────
//
// A poster-grid (TMDB-enriched) or flat (thumbnail-only) browser for a
// group's video files, per docs/mediacenter.md. Grouping: one card per movie,
// one card per show — shows are grouped by `display_title` (already
// resolved/corroborated at index time, §3.4), not by folder path, since a
// client-side path convention would have to guess how many roots/subfolders
// deep a show folder sits, which display_title already settled once.
//
// TMDB metadata is fetched lazily, only for a tile once it is actually
// visible (LazyTile below) — apps.md §5's virtualization requirement for a
// grid of many tiles. Thumbnails go through the same `file_req`/chunk path
// as a real file (docs/mediacenter.md §5.3) via MediaThumb, reusing
// chat-app.js's ChatImage pattern.

const VIEW_MODE_KEY = 'meshbay_video_view_mode';

function loadViewMode() {
  try { return localStorage.getItem(VIEW_MODE_KEY) === 'flat' ? 'flat' : 'poster'; }
  catch { return 'poster'; }
}
function saveViewMode(mode) {
  try { localStorage.setItem(VIEW_MODE_KEY, mode); } catch { /* per-device convenience only */ }
}

function formatDuration(seconds) {
  if (!seconds) return '';
  const total = Math.round(seconds);
  const h = Math.floor(total / 3600);
  const m = Math.floor((total % 3600) / 60);
  return h > 0 ? `${h}h${String(m).padStart(2, '0')}` : `${m}min`;
}

function formatResolution(width, height) {
  if (!width || !height) return '';
  if (height >= 2100) return '4K';
  if (height >= 1000) return `${height}p`;
  return `${width}x${height}`;
}

function yearOf(dateStr) {
  return dateStr ? String(dateStr).slice(0, 4) : '';
}

// ── grouping ─────────────────────────────────────────────────────────────────

// Nothing shows until an operator has actually chosen a root in Settings
// (§5.6/V-whatever this is now): the node itself runs no TMDB/thumbnail
// work for this group before that either (daemon.py's
// _enrich_new_video_entries), so falling back to "the whole index" here
// would just show files nothing has enriched.
function underVideoRoot(entry, videoRoot) {
  if (!videoRoot) return false;
  const p = entry.path || '';
  return p === videoRoot || p.startsWith(videoRoot + '/');
}

function buildSeasons(episodes) {
  const sorted = [...episodes].sort((a, b) => (a.season - b.season) || (a.episode - b.episode));
  const bySeason = new Map();
  for (const ep of sorted) {
    if (!bySeason.has(ep.season)) bySeason.set(ep.season, []);
    bySeason.get(ep.season).push(ep);
  }
  return [...bySeason.entries()].sort((a, b) => a[0] - b[0])
    .map(([season, seasonEpisodes]) => ({ season, episodes: seasonEpisodes }));
}

// The season a show's detail modal opens on.
//
// Deliberately not the representative episode's. `repEntry` is picked for its
// *thumbnail* — `episodes.find((e) => e.thumb_hash)` in the poster grid, so
// the card has a fallback frame when TMDB has no poster — which makes its
// season an accident of which files the node has managed to thumbnail so far.
// Found live on a show whose early seasons had none: the modal opened on
// season 6. The two uses of "representative" were never the same thing, and
// only one of them is about what the reader is looking at.
//
// Specials first is not what anyone means by the beginning of a show, so
// season 0 wins only when it is all there is.
function defaultSeason(show) {
  if (!show || !show.seasons.length) return null;
  // The lowest number rather than the first entry: `buildSeasons` does sort
  // ascending, but reading the answer off that ordering makes this quietly
  // depend on a caller keeping it, and there is nothing to gain by that.
  const numbers = show.seasons.map((s) => s.season);
  const real = numbers.filter((n) => n !== 0);
  return Math.min(...(real.length ? real : numbers));
}

function groupVideoEntries(entries, videoRoot) {
  const movies = [];
  const showsByTitle = new Map();
  for (const e of entries) {
    if (e.type !== 'video') continue;
    if (!underVideoRoot(e, videoRoot)) continue;
    if (e.season != null && e.episode != null) {
      const title = e.display_title || e.name;
      if (!showsByTitle.has(title)) showsByTitle.set(title, { title, episodes: [] });
      showsByTitle.get(title).episodes.push(e);
    } else {
      movies.push(e);
    }
  }
  movies.sort((a, b) => (a.display_title || a.name).localeCompare(b.display_title || b.name));
  const shows = [...showsByTitle.values()].sort((a, b) => a.title.localeCompare(b.title));
  for (const show of shows) {
    show.episodes.sort((a, b) => (a.season - b.season) || (a.episode - b.episode));
    show.seasons = buildSeasons(show.episodes);
  }
  return { movies, shows };
}

// ── lazy-mount tile (apps.md §5 virtualization) ─────────────────────────────

const LAZY_TILE_MARGIN = 300;

function LazyTile({ cls = 'video-tile-slot', children }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (visible || !ref.current) return;
    // A tile that is already on screen (or within the margin) the moment
    // it mounts — the overwhelmingly common case, since a merge (§V6) or a
    // tab revisit mounts tiles into a grid that was already scrolled to
    // wherever the operator was looking — doesn't need to wait for
    // IntersectionObserver's own first callback at all: that first
    // delivery is only a *microtask/next-paint* guarantee, not an
    // immediate one, and was observed live taking upwards of 30 seconds
    // (matching the browser's own periodic intersection-computation
    // cadence exactly) — which read as "the poster never finishes
    // loading" even though every fetch behind it had already completed.
    // Checked synchronously so a genuinely below-the-fold tile still only
    // mounts once actually scrolled near.
    const rect = ref.current.getBoundingClientRect();
    const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
    const alreadyNear = rect.bottom >= -LAZY_TILE_MARGIN && rect.top <= viewportHeight + LAZY_TILE_MARGIN;
    if (alreadyNear) { setVisible(true); return; }
    const obs = new IntersectionObserver((obsEntries) => {
      if (obsEntries.some((oe) => oe.isIntersecting)) { setVisible(true); obs.disconnect(); }
    }, { rootMargin: `${LAZY_TILE_MARGIN}px` });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, [visible]);

  return html`<div ref=${ref} class=${cls}>${visible ? children : null}</div>`;
}

// ── thumbnail/poster image, decrypted via the chunk path ────────────────────
//
// Cached per session by thumb_hash (a content hash, so it never goes stale):
// the same poster reused across a season's worth of episode tiles is
// decrypted once, not once per tile. Blob URLs are not revoked — the number
// of distinct thumbnails one session ever visits is bounded by the library
// size, and reference-counting revocation across many tile mounts/unmounts
// would cost real complexity for a benefit that only matters in a very long
// session.
const _thumbBlobCache = new Map();

function MediaThumb({
  thumbHash, transportRef, gekRef, alt, cls = 'video-thumb', onReady, emptyIcon = 'video',
  reloadKey,
}) {
  const [blobUrl, setBlobUrl] = useState(() => _thumbBlobCache.get(thumbHash) || null);
  const [retryToken, setRetryToken] = useState(0);

  useEffect(() => {
    const listener = () => setRetryToken((n) => n + 1);
    _thumbRetryListeners.add(listener);
    return () => _thumbRetryListeners.delete(listener);
  }, []);

  // Re-checks the cache by the CURRENT thumbHash on every change rather than
  // trusting the `blobUrl` state variable — a PosterCard swaps this same
  // component instance's thumbHash prop from the raw fallback frame to the
  // TMDB poster once metadata resolves, and gating on "is blobUrl already
  // set" (from the *previous* hash) would leave the fallback frame on
  // screen forever instead of ever fetching the poster.
  //
  // `onReady` fires exactly once per settled thumbHash — cache hit, fetch
  // success, fetch failure, or no hash at all — so a caller that hides this
  // component until its image has actually arrived (PosterCard) always
  // gets unstuck, even when there's nothing to show.
  useEffect(() => {
    const cached = _thumbBlobCache.get(thumbHash);
    if (cached) { setBlobUrl(cached); if (onReady) onReady(cached); return; }
    setBlobUrl(null);
    if (!thumbHash) { if (onReady) onReady(null); return; }
    let cancelled = false;
    (async () => {
      const transport = transportRef.current;
      if (!transport || !transport.connected) { if (onReady) onReady(null); return; }
      try {
        const chunks = await pipelinedDownload(transport, gekRef.current, thumbHash, 1);
        if (cancelled) return;
        const url = URL.createObjectURL(new Blob(chunks, { type: 'image/jpeg' }));
        _thumbBlobCache.set(thumbHash, url);
        setBlobUrl(url);
        if (onReady) onReady(url);
      } catch {
        /* leave the placeholder — a transient fetch failure isn't an error state */
        if (!cancelled && onReady) onReady(null);
      }
    })();
    return () => { cancelled = true; };
    // `reloadKey` — bumped by the caller when the transport behind `transportRef`
    // was replaced (a search-page pool reconnect). Without it, a thumb whose
    // first fetch hit a not-yet-connected transport and bailed above would stay
    // an empty placeholder for good, since neither `thumbHash` nor `retryToken`
    // changes when only the connection does.
  }, [thumbHash, retryToken, reloadKey]);

  if (!blobUrl) return html`<div class="${cls} video-thumb-empty"><${Icon} name=${emptyIcon} /></div>`;
  return html`<img class=${cls} src=${blobUrl} alt=${alt || ''} loading="lazy" />`;
}

// ── TMDB metadata, fetched once per visible tile ────────────────────────────

// An operator correcting a wrong match (TmdbSearchOverlay below) changes
// what `media_meta_req` returns for a file every already-mounted tile/modal
// already has cached in its own useMediaMeta state — nothing would ever
// refetch otherwise, since fileId/active don't change. Bumping this and
// telling every subscribed hook to redo its fetch is simpler than trying to
// know which files a given override actually affects (that's server-side
// knowledge — display_title grouping — this module doesn't have).
const _mediaMetaListeners = new Set();
function bumpMediaMetaGeneration() {
  for (const fn of _mediaMetaListeners) fn();
}

const _thumbRetryListeners = new Set();
function bumpThumbGeneration() {
  for (const fn of _thumbRetryListeners) fn();
}

// `enrichSig` — a value that changes when the entry's index-time
// enrichment lands (display_title fills in). The node answers confidence 0
// for a not-yet-enriched video (it can't tell it apart from a movie and
// would otherwise storm TMDB with its raw filename), so the client must
// refetch once the enriched fields arrive on an index delta — the fileId
// (a content hash) never changes, so nothing else would trigger it.
// `reloadKey` — an optional value the caller bumps when the transport behind
// `transportRef` was swapped out (search-page's connection pool evicted and
// later rebuilt this group's connection). The first fetch after a mount onto a
// not-yet-connected transport returns early below; nothing else here would ever
// re-run it, so the tile would sit on a spinner for good. Threading the group's
// `_connGen` in as `reloadKey` is what unsticks it.
function useMediaMeta(transportRef, fileId, active, enrichSig, reloadKey) {
  const [meta, setMeta] = useState(null);
  const [refetchToken, setRefetchToken] = useState(0);

  useEffect(() => {
    // Clears immediately (so the spinner shows right away, not only once
    // the new fetch resolves) and bumps the token, which re-runs the fetch
    // effect below regardless of whether fileId/active changed at all.
    const listener = () => { setMeta(null); setRefetchToken((n) => n + 1); };
    _mediaMetaListeners.add(listener);
    return () => _mediaMetaListeners.delete(listener);
  }, []);

  useEffect(() => {
    if (!active || !fileId) return;
    let cancelled = false;
    (async () => {
      const transport = transportRef.current;
      if (!transport || !transport.connected) return;
      try {
        const resp = await transport.fetchMediaMeta(fileId);
        if (!cancelled) setMeta(resp);
      } catch { if (!cancelled) setMeta({ confidence: 0 }); }
    })();
    return () => { cancelled = true; };
  }, [fileId, active, refetchToken, enrichSig, reloadKey]);
  return meta;
}

// ── per-season TMDB metadata (overview/air_date/poster), season-tab view ───
//
// Found live: a show's own tmdb_meta.overview is one static field that does
// not necessarily describe every season alike (a season-3-specific
// promotional summary read as the synopsis for all three seasons). Cached
// for the session by tmdb_id+season, mirroring _thumbBlobCache — the same
// season is revisited every time its tab is reselected.
const _seasonMetaCache = new Map();

function useSeasonMeta(transportRef, tmdbId, season, active) {
  const cacheKey = active && tmdbId != null && season != null ? `${tmdbId}:${season}` : null;
  const [meta, setMeta] = useState(() => (cacheKey ? _seasonMetaCache.get(cacheKey) || null : null));
  useEffect(() => {
    if (!cacheKey) return;
    const cached = _seasonMetaCache.get(cacheKey);
    if (cached) { setMeta(cached); return; }
    setMeta(null);
    let cancelled = false;
    (async () => {
      const transport = transportRef.current;
      if (!transport || !transport.connected) return;
      try {
        const resp = await transport.fetchSeasonMeta(tmdbId, season);
        if (cancelled) return;
        _seasonMetaCache.set(cacheKey, resp);
        setMeta(resp);
      } catch { if (!cancelled) setMeta({ confidence: 0 }); }
    })();
    return () => { cancelled = true; };
  }, [cacheKey]);
  return meta;
}

// ── Mode A: poster grid ──────────────────────────────────────────────────────

function PosterCard({
  title, subtitle, repEntry, transportRef, gekRef, onOpen, groupKey, onMetaResolved, onNeedConn,
}) {
  const tRef = repEntry._tRef || transportRef;
  const gRef = repEntry._gRef || gekRef;

  // Search view only: ask for this group's connection the moment the tile
  // actually mounts (it is inside a LazyTile, so that means "scrolled near").
  // Groups the pre-connect walk did not reach light up here instead of never.
  // A no-op in a single-group page — there is no groupId and no onNeedConn.
  useEffect(() => {
    if (onNeedConn && repEntry.groupId) {
      Promise.resolve(onNeedConn(repEntry.groupId)).catch(() => {});
    }
  }, [onNeedConn, repEntry.groupId]);

  const meta = useMediaMeta(
    tRef, repEntry.id, true, repEntry.display_title || '', repEntry._connGen);
  const confident = Boolean(meta && meta.confidence && meta.tmdb_id);
  const metaReady = meta !== null;

  // Reports this tile's own resolution upward so PosterGrid can notice two
  // differently-parsed folders (a show split across release groups that
  // named its seasons inconsistently, §3.4/V6) resolving to the same TMDB
  // id, and merge them into one card — never required for the generic
  // per-folder display to work, only an enhancement once it's known safe.
  useEffect(() => {
    if (meta && onMetaResolved) onMetaResolved(groupKey, meta);
  }, [meta, groupKey]);

  const posterHash = confident && meta.poster_thumb_hash ? meta.poster_thumb_hash : repEntry.thumb_hash;

  // Which hash MediaThumb has actually confirmed ready — compared against
  // the *current* posterHash below, rather than a separate boolean reset
  // by its own effect on posterHash change. That second-writer shape had a
  // real bug: the instant metaReady flips true, posterHash jumps from the
  // raw fallback frame to the resolved poster in the very same commit that
  // mounts MediaThumb for it — and when that poster's bytes are already in
  // MediaThumb's session cache (a revisit within the same tab, no reload),
  // its onReady fires synchronously from that same mount effect. Effects
  // run children-first, so the "reset on posterHash change" effect fired
  // *after* it, in the same commit, unconditionally setting the flag back
  // to false — with no later event left to ever set it true again. The
  // card stayed a spinner forever despite the image already being loaded.
  // Deriving readiness from a direct comparison has no such ordering to
  // get wrong: whichever of the two fires, in whichever order, the render
  // that follows sees the same answer.
  const [readyHash, setReadyHash] = useState(null);
  const handleImageReady = useCallback(() => setReadyHash(posterHash), [posterHash]);
  const imageReady = readyHash === posterHash;

  // Nothing is shown until BOTH the TMDB lookup and the final chosen image
  // (the poster once matched, the file's own frame otherwise) have
  // actually settled. Revealing the raw per-file frame first and swapping
  // it for the poster a moment later — or showing a card that a moment
  // later gets absorbed into a neighbour once §V6's merge kicks in — was
  // exactly the flash an operator flagged as hard on the eyes. A slow
  // lookup (a big, freshly-scanned library) just means the spinner stays a
  // little longer, never a partially-drawn card.
  const ready = metaReady && imageReady;

  return html`
    <div class="video-card ${ready && !confident ? 'video-card-unmatched' : ''}" onClick=${onOpen}>
      ${!ready && html`
        <div class="video-poster video-poster-loading"><span class="spinner"></span></div>
      `}
      <div class="video-poster-slot" style=${ready ? '' : 'display:none'}>
        ${metaReady && html`
          <${MediaThumb} thumbHash=${posterHash} alt=${title}
            cls="video-poster" transportRef=${tRef} gekRef=${gRef}
            reloadKey=${repEntry._connGen}
            onReady=${handleImageReady} />
        `}
      </div>
      ${ready && html`
        <div class="video-card-info">
          <div class="video-card-title">
            ${(confident && meta.title) || title}
            ${!confident && html`<span class="video-card-flag" title=${t('video.no_match')}>?</span>`}
          </div>
          <div class="video-card-sub">
            ${confident && meta.release_date ? yearOf(meta.release_date) : ''}
            ${confident && meta.first_air_date ? yearOf(meta.first_air_date) : ''}
            ${subtitle ? ` · ${subtitle}` : ''}
          </div>
          ${repEntry.groupName && html`
            <div class="video-card-group">${repEntry.groupName}</div>
          `}
        </div>
      `}
    </div>
  `;
}

// ── the synopsis, at a fixed height ──────────────────────────────────────────
//
// Clamped to three lines, the third cut short by the "read more" link floated
// into it — the float is what shortens that one line box, which is why the
// link is written *before* the text and the CSS reserves the two lines above
// it with a zero-width float of its own. There is no way to ask for this in
// `-webkit-line-clamp`, which only ever puts its ellipsis at the end of the
// last line.
//
// `reserve` pins the same three lines from below, so a multi-season show's
// synopsis is a constant height rather than a range: TMDB writes two lines
// for one season and twelve for the next, and the season menu underneath has
// to stay put across that.
//
// Whether three lines is all of it depends on how wide the modal is, so it is
// measured rather than counted, and re-measured on a resize.

function OverviewText({ text, reserve }) {
  const [expanded, setExpanded] = useState(false);
  const [overflows, setOverflows] = useState(false);
  const ref = useRef(null);

  // A different season is a different synopsis: re-collapse, or a long
  // season read expanded leaves the next one's two lines expanded too.
  useEffect(() => { setExpanded(false); }, [text]);

  // Only the clamped element can be measured — expanded, scrollHeight and
  // clientHeight agree and the "show less" link would remove itself.
  useEffect(() => {
    if (expanded) return undefined;
    const measure = () => {
      const el = ref.current;
      if (el) setOverflows(el.scrollHeight > el.clientHeight + 1);
    };
    measure();
    window.addEventListener('resize', measure);
    return () => window.removeEventListener('resize', measure);
  }, [text, expanded]);

  const showToggle = !expanded && overflows;
  const cls = ['video-detail-overview',
               expanded ? '' : 'clamped',
               showToggle ? 'has-more' : '',
               reserve && !expanded ? 'reserved' : ''].filter(Boolean).join(' ');
  return html`
    <div class="video-overview-wrap">
      <p class=${cls} ref=${ref}>
        ${showToggle && html`
          <button class="video-overview-toggle" onClick=${() => setExpanded(true)}>
            … ${t('video.read_more')}
          </button>
        `}
        ${text}
      </p>
      ${expanded && html`
        <button class="video-overview-toggle standalone"
          onClick=${() => setExpanded(false)}>${t('video.read_less')}</button>
      `}
    </div>
  `;
}

// ── season picker (docs/mediacenter.md §5.4's fix for a mis-scoped overview) ─
//
// A row of tabs, which this was, scrolls horizontally once a show has more
// seasons than fit — a scrollbar nobody finds, hiding the seasons that matter
// most on the narrowest screens. One trigger and a menu is a fixed height
// whether the show ran three seasons or twenty-five, which is also what keeps
// the episode list below from moving when the season changes.

// Where the panel goes, measured from the trigger. It cannot simply be an
// absolutely positioned child: the modal clips (`overflow: hidden`, for its
// rounded corners), and a show with a dozen seasons opens a panel taller than
// the room left under the picker on anything but a tall window — the last
// seasons then sit outside the modal where no scroll can reach them. Fixed to
// the viewport and measured, it also flips above the trigger when that is
// where the space is.
const SEASON_PANEL_MAX = 320;
const SEASON_PANEL_MIN = 120;
const SEASON_PANEL_GAP = 12;

function placeSeasonPanel(el) {
  if (!el) return null;
  const r = el.getBoundingClientRect();
  const below = window.innerHeight - r.bottom - SEASON_PANEL_GAP;
  const above = r.top - SEASON_PANEL_GAP;
  const down = below >= Math.min(SEASON_PANEL_MAX, above);
  const room = Math.max(SEASON_PANEL_MIN, Math.min(SEASON_PANEL_MAX, down ? below : above));
  return {
    left: `${r.left}px`,
    width: `${r.width}px`,
    top: down ? `${r.bottom + 4}px` : 'auto',
    bottom: down ? 'auto' : `${window.innerHeight - r.top + 4}px`,
    maxHeight: `${room}px`,
  };
}

function SeasonMenu({ seasons, selected, selectedYear, onSelect }) {
  const [open, setOpen] = useState(false);
  const [pos, setPos] = useState(null);
  const ref = useRef(null);

  useEffect(() => {
    if (!open) return undefined;
    // Same shape as app.js's UserMenu: the trigger's own click is inside
    // `ref`, so toggling still works with this listener on the document.
    const close = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    };
    // Esc closes the menu and stops there — the detail modal behind it must
    // not take the same keystroke as "close the modal".
    const onKey = (e) => {
      if (e.key !== 'Escape') return;
      e.stopPropagation();
      setOpen(false);
    };
    // Nothing scrolls under an open panel — the detail body does not scroll
    // for a show (only its episode list does) and the page behind the overlay
    // cannot — so a resize is the only thing that can invalidate the
    // measurement taken when it opened.
    const replace = () => setPos(placeSeasonPanel(ref.current));
    document.addEventListener('click', close);
    document.addEventListener('keydown', onKey, true);
    window.addEventListener('resize', replace);
    return () => {
      document.removeEventListener('click', close);
      document.removeEventListener('keydown', onKey, true);
      window.removeEventListener('resize', replace);
    };
  }, [open]);

  // Measured in the click, not in an effect after it: an effect would render
  // the panel once at the wrong place and move it on the next frame.
  const toggle = useCallback(() => {
    setOpen((wasOpen) => {
      if (!wasOpen) setPos(placeSeasonPanel(ref.current));
      return !wasOpen;
    });
  }, []);

  const label = (n) => (n === 0 ? t('video.specials') : t('video.season_n', { n }));

  return html`
    <div class="video-season-menu" ref=${ref}>
      <button class="video-season-trigger" aria-haspopup="listbox"
        aria-expanded=${open ? 'true' : 'false'}
        onClick=${toggle}>
        <span class="video-season-current">
          ${label(selected)}${selectedYear ? ` · ${selectedYear}` : ''}
        </span>
        <${Icon} name="chevron" cls="video-season-caret ${open ? 'flip' : ''}" />
      </button>
      ${open && pos && html`
        <div class="video-season-options" role="listbox" style=${pos}>
          ${seasons.map((s) => html`
            <button key=${s.season} role="option"
              aria-selected=${s.season === selected ? 'true' : 'false'}
              class="video-season-option ${s.season === selected ? 'active' : ''}"
              onClick=${() => { onSelect(s.season); setOpen(false); }}>
              <span class="video-season-option-name">${label(s.season)}</span>
              <span class="video-season-option-count">
                ${t('video.n_episodes', { n: s.episodes.length })}
              </span>
            </button>
          `)}
        </div>
      `}
    </div>
  `;
}

// ── operator: correct a wrong automatic TMDB match ──────────────────────────

// Same shape as group-settings.js's own signFn construction (setVideoRoot,
// setTmdbConfig, ...) — there is no group-wide "sign this" helper to share,
// each caller builds one from the connection it already has.
function buildSignFn(transportRef) {
  const transport = transportRef.current;
  const sk = transport && transport.sessionKeys && transport.sessionKeys.skEdB64;
  return (sk && window.MeshBayKeys)
    ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
    : null;
}

function TmdbSearchOverlay({
  initialQuery, mediaType, fileId, transportRef, gekRef, onClose, onApplied,
}) {
  const [query, setQuery] = useState(initialQuery || '');
  const [results, setResults] = useState(null); // null = not searched yet
  const [searching, setSearching] = useState(false);
  const [applying, setApplying] = useState(false);
  const [error, setError] = useState('');

  const runSearch = useCallback(async (e) => {
    if (e) e.preventDefault();
    const q = query.trim();
    if (!q || searching) return;
    setSearching(true);
    setError('');
    try {
      const transport = transportRef.current;
      const resp = await transport.searchTmdb(mediaType, q);
      setResults(resp.results || []);
    } catch (err) {
      setError(err.message);
      setResults([]);
    } finally {
      setSearching(false);
    }
  }, [query, mediaType, transportRef, searching]);

  const apply = useCallback(async (tmdbId) => {
    if (applying) return;
    setApplying(true);
    setError('');
    try {
      const signFn = buildSignFn(transportRef);
      await transportRef.current.overrideTmdbMatch(fileId, tmdbId, mediaType, signFn);
      bumpMediaMetaGeneration();
      onApplied();
    } catch (err) {
      setError(err.message);
      setApplying(false);
    }
  }, [applying, fileId, mediaType, transportRef, onApplied]);

  return html`
    <div class="video-overlay video-search-overlay" onClick=${(e) => {
      if (e.target.classList.contains('video-search-overlay')) onClose();
    }}>
      <div class="video-detail video-search-panel">
        <div class="video-top-bar">
          <span class="video-title">${t('video.search_title')}</span>
          <button class="video-close" onClick=${onClose} title=${t('video.close')}>
            <${Icon} name="close" /></button>
        </div>
        <div class="video-detail-body">
          <form class="video-search-form" onSubmit=${runSearch}>
            <input type="text" value=${query} autofocus
              placeholder=${t('video.search_placeholder')}
              onInput=${(e) => setQuery(e.target.value)} />
            <button class="admin-btn" type="submit" disabled=${searching || !query.trim()}>
              ${searching ? html`<span class="spinner"></span>` : t('video.search_button')}
            </button>
          </form>
          <p class="video-search-hint">
            ${mediaType === 'tv' ? t('video.search_apply_hint') : t('video.search_apply_hint_movie')}
          </p>
          ${error && html`<p class="video-search-error">${error}</p>`}
          ${results && results.length === 0 && !searching && html`
            <p class="page-message">${t('video.search_no_results')}</p>
          `}
          ${results && results.length > 0 && html`
            <div class="video-search-results">
              ${results.map((r) => html`
                <button class="video-search-result" key=${r.tmdb_id}
                  disabled=${applying}
                  onClick=${() => apply(r.tmdb_id)}>
                  <div class="video-search-result-thumb">
                    <${MediaThumb} thumbHash=${r.poster_thumb_hash} alt=${r.title}
                      cls="video-search-result-poster" transportRef=${transportRef} gekRef=${gekRef} />
                  </div>
                  <div class="video-flat-info">
                    <div class="video-flat-title">${r.title}</div>
                    <div class="video-flat-sub">${r.year}</div>
                  </div>
                </button>
              `)}
            </div>
          `}
        </div>
      </div>
    </div>
  `;
}

function VideoDetailModal({
  title, meta, repEntry, show, transportRef, gekRef, onClose, onPlay, isNodeAdmin,
}) {
  const confident = Boolean(meta && meta.confidence && meta.tmdb_id);
  const [searching, setSearching] = useState(false);
  const [rematching, setRematching] = useState(false);
  const mediaType = show ? 'tv' : 'movie';

  // §10.1/V13: drop this file's cached match on the node and let it
  // re-resolve with the current matcher — the one-click alternative to the
  // full search-and-pick flow above.
  const doRematch = useCallback(async () => {
    if (rematching) return;
    setRematching(true);
    try {
      await transportRef.current.rematchTmdbMatch(repEntry.id, buildSignFn(transportRef));
      bumpMediaMetaGeneration();
    } catch { /* leave the current match in place */ }
    setRematching(false);
  }, [rematching, repEntry, transportRef]);

  // Reset whenever a different show is opened in this same modal instance —
  // `show` changes identity, and selectedSeason must not silently keep
  // pointing at whatever the previous show's season 4 was.
  const [selectedSeason, setSelectedSeason] = useState(null);
  useEffect(() => { setSelectedSeason(defaultSeason(show)); }, [show]);

  const showMultiSeason = Boolean(show && show.seasons.length > 1);
  const seasonMeta = useSeasonMeta(
    transportRef, confident ? meta.tmdb_id : null, selectedSeason,
    showMultiSeason && Boolean(confident) && selectedSeason != null);
  const seasonConfident = showMultiSeason && seasonMeta && seasonMeta.confidence;

  // One line, joined rather than concatenated with leading separators: a
  // title TMDB has no rating for used to open the line with " · ".
  const facts = !confident ? '' : [
    meta.vote_average ? `★ ${meta.vote_average.toFixed(1)}` : null,
    meta.genres && meta.genres.length ? meta.genres.join(', ') : null,
    // The show's own year, not the selected season's — the season's air date
    // rides along with the season picker, where it names what it belongs to.
    yearOf(meta.first_air_date || meta.release_date) || null,
    meta.director ? `${t('video.director')}: ${meta.director}` : null,
  ].filter(Boolean).join(' · ');

  return html`
    <div class="video-overlay" onClick=${(e) => {
      if (e.target.classList.contains('video-overlay')) onClose();
    }}>
      <div class="video-detail ${showMultiSeason ? 'video-detail-steady' : ''}">
        <div class="video-top-bar">
          <span class="video-title">${(confident && meta.title) || title}</span>
          <button class="video-close" onClick=${onClose} title=${t('video.close')}>
            <${Icon} name="close" /></button>
        </div>
        <div class="video-detail-body">
          ${meta !== null && !confident && html`
            <p class="video-detail-nomatch">${t('video.no_match')}</p>
          `}
          <p class="video-detail-source">
            ${t('video.source_file', { name: `${repEntry.path}/${repEntry.name}` })}
            ${confident && html`<span class="video-detail-tmdbref"> · TMDB #${meta.tmdb_id}</span>`}
          </p>
          ${confident && html`
            <${OverviewText} reserve=${showMultiSeason}
              text=${(seasonConfident && seasonMeta.overview) || meta.overview} />
            ${facts && html`<p class="video-detail-facts">${facts}</p>`}
            ${meta.cast && meta.cast.length > 0 && html`
              <p class="video-detail-cast">
                ${meta.cast.slice(0, 6).map((c) => c.name).join(', ')}
              </p>
            `}
          `}
          ${isNodeAdmin && html`
            <div class="video-admin-actions">
              <button class="admin-btn video-fix-match" onClick=${() => setSearching(true)}>
                ${t('video.fix_match')}
              </button>
              <button class="admin-btn" onClick=${doRematch} disabled=${rematching}>
                ${rematching ? html`<span class="spinner"></span>` : t('video.rematch_one')}
              </button>
            </div>
          `}
          ${showMultiSeason && html`
            <${SeasonMenu} seasons=${show.seasons} selected=${selectedSeason}
              selectedYear=${seasonConfident ? yearOf(seasonMeta.air_date) : ''}
              onSelect=${setSelectedSeason} />
          `}
          ${!show && html`
            <button class="admin-btn" onClick=${() => onPlay(repEntry)}>
              <${Icon} name="play" /> ${t('group.play')}
              ${repEntry.duration ? ` (${formatDuration(repEntry.duration)})` : ''}
            </button>
          `}
          ${show && html`
            <div class="video-season-list">
              ${(showMultiSeason ? show.seasons.filter((s) => s.season === selectedSeason) : show.seasons)
                .map((s) => html`
                <div class="video-season" key=${s.season}>
                  ${!showMultiSeason && html`
                    <div class="video-season-header">
                      ${s.season === 0 ? t('video.specials') : t('video.season_n', { n: s.season })}
                    </div>
                  `}
                  ${s.episodes.map((ep) => html`
                    <button class="video-episode-row" key=${ep.id} onClick=${() => onPlay(ep)}>
                      <${LazyTile} cls="video-episode-thumb-slot">
                        <${MediaThumb} thumbHash=${ep.thumb_hash} alt=${ep.display_title || ep.name}
                          cls="video-episode-thumb" transportRef=${ep._tRef || transportRef} gekRef=${ep._gRef || gekRef}
                          reloadKey=${ep._connGen} />
                      </${LazyTile}>
                      <span class="video-episode-label">
                        S${ep.season}E${String(ep.episode).padStart(2, '0')}
                        ${' · '}${ep.display_title || ep.name}
                      </span>
                      <span class="video-episode-meta">
                        ${formatDuration(ep.duration)} ${formatResolution(ep.width, ep.height)}
                      </span>
                    </button>
                  `)}
                </div>
              `)}
            </div>
          `}
        </div>
      </div>
    </div>
    ${searching && html`
      <${TmdbSearchOverlay} initialQuery=${(confident && meta.title) || title} mediaType=${mediaType}
        fileId=${repEntry.id} transportRef=${transportRef} gekRef=${gekRef}
        onClose=${() => setSearching(false)}
        onApplied=${() => setSearching(false)} />
    `}
  `;
}

function PosterGrid({
  movies, shows, transportRef, gekRef, onPreview, tmdbEnabled, isNodeAdmin, onNeedConn,
}) {
  const [detail, setDetail] = useState(null); // { title, repEntry, show? }
  // raw (per-folder-parsed-title) show title -> its own resolved media_meta_resp.
  const [metaByGroup, setMetaByGroup] = useState({});

  const handleMetaResolved = useCallback((groupKey, meta) => {
    setMetaByGroup((prev) => (prev[groupKey] === meta ? prev : { ...prev, [groupKey]: meta }));
  }, []);

  // Two raw groups (grouped by parsed display_title, §4.1) resolving to the
  // same confident TMDB id are almost certainly one show whose seasons
  // were released under differently-named folders — confirmed live: one
  // operator's show had its two seasons parsed as two spellings by
  // two different release groups, showing as two identical-looking cards
  // once both matched the same real show (§3.4/V6). Merged here once both
  // are actually known — never required for the fallback to work: a group
  // with no confident match yet, or ever, still shows on its own, exactly
  // the generic per-folder display needs.
  const mergedShows = useMemo(() => {
    const byTmdbId = new Map();
    const standalone = [];
    for (const s of shows) {
      const meta = metaByGroup[s.title];
      const tmdbId = meta && meta.confidence && meta.tmdb_id;
      if (tmdbId) {
        if (!byTmdbId.has(tmdbId)) byTmdbId.set(tmdbId, []);
        byTmdbId.get(tmdbId).push(s);
      } else {
        standalone.push([s]);
      }
    }
    return [...byTmdbId.values(), ...standalone].map((groups) => {
      const episodes = groups.flatMap((g) => g.episodes);
      return {
        // groups[0].title, not a joined string of every constituent's
        // title: a fresh key here would make this a brand-new PosterCard
        // (and LazyTile) the instant a second raw group merges into an
        // already-visible one — throwing away its already-fired
        // IntersectionObserver and already-resolved metadata/poster for no
        // reason, and reintroducing exactly the flash the "ready" gating
        // above exists to prevent. groups[0].title is already unique
        // (raw titles are, via groupVideoEntries' showsByTitle) and, for
        // the overwhelmingly common unmerged case, is the same key the
        // card already had — so nothing about this changes when no merge
        // ever happens.
        key: groups[0].title,
        title: groups[0].title,
        episodes,
        seasons: buildSeasons(episodes),
      };
    });
  }, [shows, metaByGroup]);

  const openDetail = (title, repEntry, show) => setDetail({ title, repEntry, show });
  const detailTRef = detail && detail.repEntry._tRef ? detail.repEntry._tRef : transportRef;
  const detailGRef = detail && detail.repEntry._gRef ? detail.repEntry._gRef : gekRef;
  const detailMeta = useMediaMeta(
    detailTRef, detail ? detail.repEntry.id : null, !!detail,
    detail ? (detail.repEntry.display_title || '') : '',
    detail ? detail.repEntry._connGen : 0);

  return html`
    <div class="video-grid">
      ${movies.map((e) => html`
        <${LazyTile} key=${e.id}>
          <${PosterCard} title=${e.display_title || e.name}
            subtitle=${formatDuration(e.duration)} repEntry=${e}
            groupKey=${`movie:${e.id}`}
            transportRef=${transportRef} gekRef=${gekRef}
            onNeedConn=${onNeedConn}
            onOpen=${() => (tmdbEnabled
              // With TMDB off there is nothing the detail modal would show
              // for a movie (no overview, no season list to pick from,
              // unlike a show) — so it would just be an extra click in
              // front of a Play button. Straight to the player instead.
              ? openDetail(e.display_title || e.name, e, null)
              : onPreview(e))} />
        </${LazyTile}>
      `)}
      ${mergedShows.map((s) => {
        // Prefer an episode that actually has a thumbnail over blindly
        // episodes[0]: if that specific file's enrichment hasn't produced
        // one yet (or failed), the card showed an empty placeholder even
        // though sibling episodes — visible right there in Flat list —
        // have one. The TMDB path (or its absence) is the same regardless
        // of which episode's own file supplies the fallback frame.
        const repEntry = s.episodes.find((e) => e.thumb_hash) || s.episodes[0];
        // Known up front from the already-parsed index fields (§3.4), no
        // TMDB needed: a card covering exactly one season says so before
        // a click, rather than an anonymous episode count — the generic
        // "N episodes" stays for a merged, multi-season, or special-only
        // card, where a single number would misrepresent it.
        const singleSeason = s.seasons.length === 1 ? s.seasons[0].season : null;
        const subtitle = singleSeason != null
          ? (singleSeason === 0 ? t('video.specials') : t('video.season_n', { n: singleSeason }))
          : t('video.n_episodes', { n: s.episodes.length });
        return html`
        <${LazyTile} key=${s.key}>
          <${PosterCard} title=${s.title}
            subtitle=${subtitle}
            repEntry=${repEntry}
            groupKey=${s.title}
            onMetaResolved=${handleMetaResolved}
            onNeedConn=${onNeedConn}
            transportRef=${transportRef} gekRef=${gekRef}
            onOpen=${() => openDetail(s.title, repEntry, s)} />
        </${LazyTile}>
      `; })}
    </div>
    ${detail && html`
      <${VideoDetailModal} title=${detail.title} meta=${detailMeta}
        repEntry=${detail.repEntry} show=${detail.show}
        transportRef=${detailTRef} gekRef=${detailGRef} isNodeAdmin=${isNodeAdmin}
        onClose=${() => setDetail(null)}
        onPlay=${(entry) => { setDetail(null); onPreview(entry); }} />
    `}
  `;
}

// ── Mode B: flat, thumbnail-only, no TMDB ────────────────────────────────────

// Within a season group, every episode's own display_title is usually
// just the show name again (guessit rarely finds a per-episode subtitle
// for this kind of release) — repeating the show name twelve times in a row said
// nothing an episode number wouldn't say better. Shown only when this row
// is actually inside a season group (`seasonContext` set); a real,
// distinct per-episode title (a show that *does* carry one) still wins
// over the generic "Episode N" label.
function FlatMovieRow({ entry, transportRef, gekRef, onPreview, seasonContext, onNeedConn }) {
  const tRef = entry._tRef || transportRef;
  const gRef = entry._gRef || gekRef;

  useEffect(() => {
    if (onNeedConn && entry.groupId) {
      Promise.resolve(onNeedConn(entry.groupId)).catch(() => {});
    }
  }, [onNeedConn, entry.groupId]);

  const isEpisode = seasonContext && entry.season != null && entry.episode != null;
  const hasOwnTitle = entry.display_title && entry.display_title !== seasonContext;
  const label = isEpisode
    ? (hasOwnTitle ? `${t('video.episode_n', { n: entry.episode })} · ${entry.display_title}`
                   : t('video.episode_n', { n: entry.episode }))
    : (entry.display_title || entry.name);

  return html`
    <div class="video-flat-row" onClick=${() => onPreview(entry)}>
      <${LazyTile} cls="video-flat-thumb-slot">
        <${MediaThumb} thumbHash=${entry.thumb_hash} alt=${entry.display_title || entry.name}
          cls="video-flat-thumb" transportRef=${tRef} gekRef=${gRef}
          reloadKey=${entry._connGen} />
      </${LazyTile}>
      <div class="video-flat-info">
        <div class="video-flat-title">${label}</div>
        <div class="video-flat-sub">
          ${formatDuration(entry.duration)} ${formatResolution(entry.width, entry.height)}
          ${' · '}${formatSize(entry.size)}
        </div>
      </div>
      ${entry.groupName && html`
        <a href="#/group/${entry.groupId}" class="badge search-group-badge"
          onClick=${(e) => e.stopPropagation()}>${entry.groupName}</a>
      `}
    </div>
  `;
}

function FlatShowFolder({ show, transportRef, gekRef, onPreview, onNeedConn }) {
  const [open, setOpen] = useState(false);
  return html`
    <div class="video-flat-folder">
      <div class="video-flat-row" onClick=${() => setOpen((v) => !v)}>
        <div class="video-flat-thumb video-thumb-empty"><${Icon} name="folder" /></div>
        <div class="video-flat-info">
          <div class="video-flat-title">${show.title}</div>
          <div class="video-flat-sub">${t('video.n_episodes', { n: show.episodes.length })}</div>
        </div>
        <${Icon} name="chevron" cls=${open ? 'video-flat-chevron open' : 'video-flat-chevron'} />
      </div>
      ${open && show.seasons.map((s) => html`
        <div class="video-flat-season" key=${s.season}>
          <div class="video-season-header">
            ${s.season === 0 ? t('video.specials') : t('video.season_n', { n: s.season })}
          </div>
          ${s.episodes.map((ep) => html`
            <${FlatMovieRow} key=${ep.id} entry=${ep} seasonContext=${show.title}
              transportRef=${transportRef} gekRef=${gekRef} onPreview=${onPreview}
              onNeedConn=${onNeedConn} />
          `)}
        </div>
      `)}
    </div>
  `;
}

function FlatList({ movies, shows, transportRef, gekRef, onPreview, onNeedConn }) {
  const items = [
    ...movies.map((e) => ({ key: e.display_title || e.name, kind: 'movie', entry: e })),
    ...shows.map((s) => ({ key: s.title, kind: 'show', show: s })),
  ].sort((a, b) => a.key.localeCompare(b.key));

  return html`
    <div class="video-flat-list">
      ${items.map((it) => it.kind === 'movie'
        ? html`<${FlatMovieRow} key=${it.entry.id} entry=${it.entry}
            transportRef=${transportRef} gekRef=${gekRef} onPreview=${onPreview}
            onNeedConn=${onNeedConn} />`
        : html`<${FlatShowFolder} key=${it.show.title} show=${it.show}
            transportRef=${transportRef} gekRef=${gekRef} onPreview=${onPreview}
            onNeedConn=${onNeedConn} />`)}
    </div>
  `;
}

// ── shell ────────────────────────────────────────────────────────────────────

function VideoApp({
  groupId, transportRef, gekRef, status, entries, onPreview, videoRoot, tmdbConfig, isNodeAdmin,
  hideFilter, onNeedConn,
}) {
  const [mode, setMode] = useState(loadViewMode);
  const [filter, setFilter] = useState('');
  // Which of movies/shows to show at all — independent of the text filter
  // below, and applied first: a title match within a type nobody asked to
  // see is still not what "Movies only" means.
  const [typeFilter, setTypeFilter] = useState('all');
  const tmdbEnabled = tmdbConfig ? tmdbConfig.enabled : true;

  useEffect(() => { setMode(loadViewMode()); }, [groupId]);
  useEffect(() => { setFilter(''); setTypeFilter('all'); }, [groupId]);

  const setModeAndSave = (m) => { setMode(m); saveViewMode(m); };

  const { movies, shows } = useMemo(
    () => groupVideoEntries(entries, videoRoot), [entries, videoRoot]);

  const needle = filter.trim().toLowerCase();
  const filteredMovies = useMemo(() => (typeFilter === 'series' ? [] : !needle ? movies : movies.filter(
    (e) => (e.display_title || e.name).toLowerCase().includes(needle))), [movies, needle, typeFilter]);
  const filteredShows = useMemo(() => (typeFilter === 'movies' ? [] : !needle ? shows : shows.filter(
    (s) => s.title.toLowerCase().includes(needle))), [shows, needle, typeFilter]);

  return html`
    ${(status === 'discovering' || status === 'connecting' || status === 'fetching') && html`
      <p class="page-message"><span class="spinner"></span>${' '}${t('status.connecting_short')}</p>
    `}
    ${status === 'offline' && html`
      <p class="page-message">${t('group.offline_title')} ${t('group.offline_hint')}</p>
    `}
    ${status === 'connected' && !videoRoot && html`
      <p class="page-message">${t('video.no_root_configured')}</p>
    `}
    ${status === 'connected' && videoRoot && html`
      <div class="video-toolbar">
        <button class="tb-btn ${mode === 'poster' ? 'active' : ''}"
          onClick=${() => setModeAndSave('poster')}>
          ${t('video.mode_poster')}
        </button>
        <button class="tb-btn ${mode === 'flat' ? 'active' : ''}"
          onClick=${() => setModeAndSave('flat')}>
          ${t('video.mode_flat')}
        </button>
        <div class="tb-typefilter">
          <button class=${typeFilter === 'all' ? 'active' : ''}
            onClick=${() => setTypeFilter('all')}>
            ${t('video.filter_all')}
          </button>
          <button class=${typeFilter === 'movies' ? 'active' : ''}
            onClick=${() => setTypeFilter('movies')}>
            ${t('video.filter_movies')}
          </button>
          <button class=${typeFilter === 'series' ? 'active' : ''}
            onClick=${() => setTypeFilter('series')}>
            ${t('video.filter_series')}
          </button>
        </div>
        ${!hideFilter && html`<div class="tb-search">
          <${Icon} name="search" />
          <input type="text" placeholder="${t('group.filter')}"
            value=${filter} onInput=${(e) => setFilter(e.target.value)} />
        </div>`}
      </div>
      ${filteredMovies.length === 0 && filteredShows.length === 0 && html`
        <p class="page-message">${needle ? t('group.empty_filter') : t('video.empty')}</p>
      `}
      ${mode === 'poster'
        ? html`<${PosterGrid} movies=${filteredMovies} shows=${filteredShows}
                transportRef=${transportRef} gekRef=${gekRef} onPreview=${onPreview}
                tmdbEnabled=${tmdbEnabled} isNodeAdmin=${isNodeAdmin} onNeedConn=${onNeedConn} />`
        : html`<${FlatList} movies=${filteredMovies} shows=${filteredShows}
                transportRef=${transportRef} gekRef=${gekRef} onPreview=${onPreview}
                onNeedConn=${onNeedConn} />`}
    `}
  `;
}

// MediaThumb and LazyTile are also used by music-app.js (docs/musicbay.md
// §7.1): the same "decrypt a thumb_hash via the chunk path into a cached
// blob" and "mount only once actually scrolled near" mechanisms apply to a
// track's cover art unchanged, so Music imports them here rather than
// re-implementing (apps.md §4's checklist).
export { VideoApp, MediaThumb, LazyTile, groupVideoEntries, bumpMediaMetaGeneration, bumpThumbGeneration };