aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/group-settings.js
blob: 60b018409955a49d58083ac209521935bb7834c1 (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
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
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
import {
  html, useState, useEffect, useCallback, useMemo, useRef,
} from './vendor/htm-preact.js';
import { t, getLocale, LOCALES } from './i18n.js';
import { Icon } from './icon.js';
import { hubFetch, navigate } from './hub-client.js';
import { APPS } from './apps.js';
import * as platform from './platform.js';

// MeshBay's own locale codes (i18n.js LOCALES) to the language tag TMDB
// expects — the two don't share a format (MeshBay's "en" vs TMDB's
// required region, "en-US"). Used only to pre-fill the TMDB language field
// with the operator's own current UI language, a reasonable default they
// can still change; the node never guesses this on its own.
const TMDB_LANGUAGE_BY_LOCALE = {
  en: 'en-US', fr: 'fr-FR', es: 'es-ES', 'pt-BR': 'pt-BR', 'zh-CN': 'zh-CN',
  ja: 'ja-JP', de: 'de-DE', it: 'it-IT', nl: 'nl-NL', pl: 'pl-PL',
};

/**
 * A settings-section that folds — every section but the ones that are
 * really just a form to fill in (invite, pair-operator, approve-device):
 * hiding an input the operator is mid-typing-into behind a click they'd
 * have to undo is friction with nothing to show for it, but a section that
 * is only ever glanced at once it's configured (TMDB, scan tuning, the
 * danger zone) benefits from staying out of the way otherwise. `title` (an
 * already-built string/vnode) wins over `titleKey` when both are given —
 * the members-table heading needs a live count baked in, not just a
 * lookup.
 */
function CollapsibleSection({ titleKey, title, defaultOpen = true, children }) {
  const [open, setOpen] = useState(defaultOpen);
  return html`
    <div class="settings-section">
      <button type="button" class="settings-collapsible-header"
        onClick=${() => setOpen((v) => !v)} aria-expanded=${open}>
        <h3 class="settings-heading">${title != null ? title : t(titleKey)}</h3>
        <${Icon} name="chevron" cls=${open ? 'video-flat-chevron open' : 'video-flat-chevron'} />
      </button>
      ${open && html`<div class="settings-collapsible-body">${children}</div>`}
    </div>
  `;
}

/**
 * A modern on/off switch — replaces a plain checkbox or a "Turn on/off"
 * button wherever the setting itself is a straight binary (uploads
 * allowed, TMDB/MusicBrainz enabled). Still a real <input type="checkbox">
 * under the hood (keyboard/screen-reader behaviour for free), just
 * restyled — see .toggle-switch in style.css.
 */
function ToggleSwitch({ checked, onChange, disabled, label }) {
  return html`
    <label class="toggle-switch ${disabled ? 'toggle-switch-disabled' : ''}">
      <input type="checkbox" checked=${checked} disabled=${disabled}
        onChange=${(e) => onChange(e.target.checked)} />
      <span class="toggle-switch-track"><span class="toggle-switch-thumb"></span></span>
      ${label != null && html`<span class="toggle-switch-label">${label}</span>`}
    </label>
  `;
}

/**
 * Which folder is an app's entry point for this group — the shared shape
 * behind both the Videos and Music root pickers (docs/musicbay.md's
 * amended §2.1): a depth-indented <select> over every folder the group's
 * index already knows about, a Save button that only enables once the
 * draft actually differs, and a confirm prompt only when replacing an
 * *already-set* root (setting one for the first time has nothing to lose).
 */
function RootFolderRow({
  icon, titleKey, hintKey, folders, value, draft, onDraftChange,
  busy, msg, onSave, noneKey, saveKey,
}) {
  return html`
    <div class="settings-root-row">
      <div class="settings-root-row-title">
        <${Icon} name=${icon} />
        <h4>${t(titleKey)}</h4>
      </div>
      <p class="settings-hint">${t(hintKey)}</p>
      <div class="settings-row">
        <label class="settings-label">
          <select value=${draft} disabled=${busy} onChange=${e => onDraftChange(e.target.value)}>
            <option value="">${t(noneKey)}</option>
            ${folders.map(p => html`
              <option key=${p} value=${p}>
                ${'  '.repeat(p.split('/').length - 1)}${p.split('/').pop()}
              </option>
            `)}
          </select>
        </label>
      </div>
      <button class="btn btn-small btn-secondary" style="margin-top:8px"
        disabled=${busy || draft === (value || '')} onClick=${onSave}>
        ${busy ? t('settings_node.scan_saving') : t(saveKey)}
      </button>
      ${msg && html`<p class=${msg.ok ? 'success-msg' : 'error-msg'} style="margin-top:8px">
        ${msg.text}</p>`}
    </div>
  `;
}

/**
 * Which folder(s) are the Photos app's entry points for this group — a
 * *set*, unlike RootFolderRow's single value above (docs/photos.md §2.1: a
 * photo library is routinely scattered across several folders). An
 * add/remove list rather than a `<select>`: pick a folder to add from the
 * same `rootFolderOptions` the Videos/Music pickers use, list what is
 * already configured with a remove button each, and one Save signs the
 * whole resulting set in one op (same shape as the app-enable checkboxes
 * below — several changes staged, one signature).
 */
function PhotoRootsRow({ folders, value, busy, msg, onSave }) {
  const [draft, setDraft] = useState(value || []);
  useEffect(() => { setDraft(value || []); }, [value]);
  const [addSelection, setAddSelection] = useState('');

  const available = folders.filter((p) => !draft.includes(p));
  const addRoot = () => {
    if (!addSelection || draft.includes(addSelection)) return;
    setDraft((prev) => [...prev, addSelection].sort());
    setAddSelection('');
  };
  const removeRoot = (path) => setDraft((prev) => prev.filter((p) => p !== path));

  const unchanged = draft.length === (value || []).length
    && draft.every((p) => (value || []).includes(p));

  return html`
    <div class="settings-root-row">
      <div class="settings-root-row-title">
        <${Icon} name="image" />
        <h4>${t('settings_node.photo_roots_title')}</h4>
      </div>
      <p class="settings-hint">${t('settings_node.photo_roots_hint')}</p>
      ${draft.length === 0 && html`
        <p class="settings-hint">${t('settings_node.photo_roots_none')}</p>
      `}
      ${draft.length > 0 && html`
        <ul class="settings-root-list">
          ${draft.map((p) => html`
            <li key=${p} class="settings-root-list-item">
              <span>${'  '.repeat(p.split('/').length - 1)}${p.split('/').pop()}</span>
              <button class="link-btn" disabled=${busy} onClick=${() => removeRoot(p)}
                title=${t('settings_node.photo_roots_remove')}>
                <${Icon} name="close" /></button>
            </li>
          `)}
        </ul>
      `}
      <div class="settings-row">
        <label class="settings-label">
          <select value=${addSelection} disabled=${busy || available.length === 0}
            onChange=${(e) => setAddSelection(e.target.value)}>
            <option value="">${t('settings_node.photo_roots_add_placeholder')}</option>
            ${available.map((p) => html`
              <option key=${p} value=${p}>
                ${'  '.repeat(p.split('/').length - 1)}${p.split('/').pop()}
              </option>
            `)}
          </select>
        </label>
        <button class="btn btn-small btn-secondary" disabled=${busy || !addSelection}
          onClick=${addRoot}>${t('settings_node.photo_roots_add')}</button>
      </div>
      <button class="btn btn-small btn-secondary" style="margin-top:8px"
        disabled=${busy || unchanged} onClick=${() => onSave(draft)}>
        ${busy ? t('settings_node.scan_saving') : t('settings_node.photo_roots_save')}
      </button>
      ${msg && html`<p class=${msg.ok ? 'success-msg' : 'error-msg'} style="margin-top:8px">
        ${msg.text}</p>`}
    </div>
  `;
}

// ── Members Panel ────────────────────────────────────────────────────────

/**
 * Everything about the group that is not its files or its chat.
 *
 * Was "Members", which was a list with three unrelated forms stacked on top of
 * it and the group's own controls somewhere else entirely — leaving or deleting
 * a group lived in the header, beside its title. One tab now, in sections, with
 * the roster last: it is the part that grows without limit, and burying the
 * controls under two hundred names is how a tab stops being usable.
 */
function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef,
                             isNodeAdmin, userId, operatorPaired, connected,
                             memberUpload, onMemberUpload,
                             enabledApps, onEnabledApps,
                             scanSettings, onScanSettings,
                             tmdbConfig, onTmdbConfig, onTmdbEnabled,
                             musicbrainzConfig, onMusicbrainzConfig, onMusicbrainzEnabled,
                             entries, nodeDirs, videoRoot, onVideoRoot,
                             audioRoot, onAudioRoot,
                             photoRoots, onPhotoRoots, onRefreshIndex,
                             onPaired, onLeft }) {
  const [members, setMembers] = useState([]);
  const [adminId, setAdminId] = useState('');
  const [loading, setLoading] = useState(true);
  const [inviteUser, setInviteUser] = useState('');
  const [inviting, setInviting] = useState(false);
  const [error, setError] = useState('');

  // Node loopback state (Electron-only)
  const [nodeDetected, setNodeDetected] = useState(false);
  const [nodeRoots, setNodeRoots] = useState([]);
  const [nodeGroupName, setNodeGroupName] = useState('');
  const [nodeBusy, setNodeBusy] = useState(false);
  const [nodeMsg, setNodeMsg] = useState('');
  // Bytes-based indexing progress while a newly added directory is being
  // scanned — same source as the Create Group wizard's step, see
  // platform.watchIndexProgress.
  const [nodeIndexProgress, setNodeIndexProgress] = useState(null);

  const loadNodeInfo = useCallback(async () => {
    if (!platform.node.available) return;
    try {
      const detect = await platform.node.detect();
      if (!detect.detected) { setNodeDetected(false); return; }
      setNodeDetected(true);
      const data = await platform.node.call('GET', '/api/groups');
      const groups = data.groups || [];
      const ng = groups.find(g => g.id === groupId);
      if (ng) {
        setNodeRoots(ng.roots || []);
        setNodeGroupName(ng.name || '');
      }
    } catch { setNodeDetected(false); }
  }, [groupId]);

  useEffect(() => { loadNodeInfo(); }, [loadNodeInfo]);

  /**
   * Poll /api/groups until the root count actually matches what an
   * add/remove just did, instead of trusting a single loadNodeInfo() call
   * right after /api/reload. Found live: /api/reload is fire-and-forget on
   * the node (ops.start_reload schedules the real work and returns
   * immediately, deliberately — a brand-new group's initial scan can take
   * minutes, see its own docstring) — and the list this section renders
   * (ops.list_groups) reads the *runtime* root set
   * (groups_ctx[gid]["roots"]), which only gets replaced once
   * _reload_config_inner's retarget actually finishes, not the config-file
   * list add_root/remove_root already updated synchronously. A single
   * fetch right after can land in that gap and show the old count.
   */
  const waitForRootCount = useCallback(async (expectedCount) => {
    for (let i = 0; i < 10; i++) {
      try {
        const data = await platform.node.call('GET', '/api/groups');
        const ng = (data.groups || []).find(g => g.id === groupId);
        const roots = (ng && ng.roots) || [];
        if (roots.length === expectedCount) {
          setNodeRoots(roots);
          if (ng) setNodeGroupName(ng.name || '');
          return true;
        }
      } catch { /* keep trying — the node may be mid-reload */ }
      await new Promise(r => setTimeout(r, 400));
    }
    return false;
  }, [groupId]);
  const [inviteCode, setInviteCode] = useState(null);
  const [pairCode, setPairCode] = useState('');
  const [pairStatus, setPairStatus] = useState('');
  const [pairing, setPairing] = useState(false);
  // Your own devices on this node. Not a members feature — it is beside them
  // because this is where a live connection to the node exists.
  const [devices, setDevices] = useState([]);
  const [approveCode, setApproveCode] = useState('');
  const [deviceMsg, setDeviceMsg] = useState('');

  // Pairing lives here rather than in Settings because this is where a live
  // connection to the node exists — and it is offered only when the node itself
  // says this account is its operator (is_node_admin comes from the authenticated
  // handshake_ack, not from the hub).
  const loadDevices = useCallback(async () => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    try {
      const out = await transport.listDevices();
      setDevices(out.devices);
    } catch { /* a node that has none says so by listing none */ }
  }, [transportRef]);

  useEffect(() => { loadDevices(); }, [loadDevices]);

  const approveDevice = useCallback(async (e) => {
    e.preventDefault();
    const code = approveCode.trim();
    if (!code) return;
    setDeviceMsg('');
    try {
      await transportRef.current.approveDevice(userId, code);
      setApproveCode('');
      setDeviceMsg(t('device.approved'));
      await loadDevices();
    } catch (err) { setDeviceMsg(err.message); }
  }, [approveCode, userId, transportRef, loadDevices]);

  const revokeDevice = useCallback(async (device) => {
    if (!confirm(t('device.revoke_confirm'))) return;
    setDeviceMsg('');
    try {
      await transportRef.current.revokeDevice(
        userId, device.pk_ed25519, device.pk_x25519 || '');
      await loadDevices();
    } catch (err) { setDeviceMsg(err.message); }
  }, [userId, transportRef, loadDevices]);

  const doPair = useCallback(async (e) => {
    e.preventDefault();
    const code = pairCode.trim();
    if (!code) return;
    setPairing(true);
    setPairStatus('');
    try {
      const transport = transportRef && transportRef.current;
      if (!transport || !transport.connected) throw new Error('Not connected to the node');
      await transport.pairOperator(userId, code);
      setPairCode('');
      setPairStatus('paired');
      // The node has pinned this key as an operator key; the form has nothing
      // left to do. It used to stay put through a refresh, because what governed
      // it was the account, which pairing does not change.
      if (onPaired) onPaired();
    } catch (err) {
      setPairStatus(err.message);
    } finally {
      setPairing(false);
    }
  }, [pairCode, transportRef, userId]);

  const [uploadBusy, setUploadBusy] = useState(false);
  const [uploadMsg, setUploadMsg] = useState('');

  /**
   * Close or open uploading for everyone who is not the operator.
   *
   * Signed, like removing a member: the node refuses an unsigned instruction,
   * so this is a request to the node rather than a decision taken here. The
   * button does not move until the node has said it did it.
   */
  const setUploads = useCallback(async (allowed) => {
    const transport = transportRef && transportRef.current;
    setUploadMsg('');
    setUploadBusy(true);
    try {
      if (!transport || !transport.connected) {
        throw new Error('Not connected to the node');
      }
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      await transport.setMemberUpload(allowed, signFn);
      if (onMemberUpload) onMemberUpload(allowed);
    } catch (err) {
      setUploadMsg(err.message);
    } finally {
      setUploadBusy(false);
    }
  }, [transportRef, onMemberUpload]);

  const [appsBusy, setAppsBusy] = useState(false);
  const [appsMsg, setAppsMsg] = useState('');
  const activeApps = enabledApps && enabledApps.length ? enabledApps : APPS.map(a => a.key);

  /**
   * Toggle one app in or out of the group's enabled set. Same shape as
   * `setUploads`: signed, and the checkbox does not move until the node has
   * said it did it. Refuses to submit an empty set client-side — the node
   * refuses it too, but there is no reason to make a round trip to learn that.
   */
  const toggleApp = useCallback(async (key) => {
    const next = activeApps.includes(key)
      ? activeApps.filter(k => k !== key)
      : [...activeApps, key];
    if (next.length === 0) {
      setAppsMsg(t('members.apps_need_one'));
      return;
    }
    const transport = transportRef && transportRef.current;
    setAppsMsg('');
    setAppsBusy(true);
    try {
      if (!transport || !transport.connected) {
        throw new Error('Not connected to the node');
      }
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      await transport.setAppsEnabled(next, signFn);
      if (onEnabledApps) onEnabledApps(next);
    } catch (err) {
      setAppsMsg(err.message);
    } finally {
      setAppsBusy(false);
    }
  }, [transportRef, onEnabledApps, activeApps]);

  const [scanBusy, setScanBusy] = useState(false);
  const [scanMsg, setScanMsg] = useState('');
  const [reconcileMinutes, setReconcileMinutes] = useState(
    scanSettings ? Math.round(scanSettings.reconcile_interval_secs / 60) : 10);
  const [debounceSeconds, setDebounceSeconds] = useState(
    scanSettings ? Math.round(scanSettings.debounce_secs) : 2);
  // The node is the source of truth; once it has answered, the fields track
  // it rather than whatever this browser guessed before connecting.
  useEffect(() => {
    if (!scanSettings) return;
    setReconcileMinutes(Math.round(scanSettings.reconcile_interval_secs / 60));
    setDebounceSeconds(Math.round(scanSettings.debounce_secs));
  }, [scanSettings]);

  /**
   * How often the reconciliation backstop runs, and how long a changed file
   * is left alone before being hashed. Same shape as toggleApp: signed, and
   * the fields do not claim success until the node has confirmed it.
   */
  const saveScanSettings = useCallback(async () => {
    const transport = transportRef && transportRef.current;
    setScanMsg('');
    setScanBusy(true);
    try {
      if (!transport || !transport.connected) {
        throw new Error('Not connected to the node');
      }
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      await transport.setScanSettings(reconcileMinutes * 60, debounceSeconds, signFn);
      const applied = {
        reconcile_interval_secs: reconcileMinutes * 60,
        debounce_secs: debounceSeconds,
      };
      if (onScanSettings) onScanSettings(applied);
      setScanMsg(t('settings_node.scan_saved'));
    } catch (err) {
      setScanMsg(err.message);
    } finally {
      setScanBusy(false);
    }
  }, [transportRef, onScanSettings, reconcileMinutes, debounceSeconds]);

  const [tmdbBusy, setTmdbBusy] = useState(false);
  const [tmdbMsg, setTmdbMsg] = useState('');
  const [tmdbTokenDraft, setTmdbTokenDraft] = useState('');
  const [tmdbEnabledBusy, setTmdbEnabledBusy] = useState(false);
  const tmdbEnabled = tmdbConfig ? tmdbConfig.enabled : true;
  // Pre-filled from the operator's own current UI language the first time
  // this renders with nothing configured yet — a sensible default, not a
  // claim about what the node is actually using until they hit Save.
  const [tmdbLanguage, setTmdbLanguage] = useState(
    () => (tmdbConfig && tmdbConfig.language)
      || TMDB_LANGUAGE_BY_LOCALE[getLocale()] || 'en-US');
  useEffect(() => {
    if (tmdbConfig && tmdbConfig.language) setTmdbLanguage(tmdbConfig.language);
  }, [tmdbConfig && tmdbConfig.language]);

  /**
   * Whether TMDB is used at all — per-group (2026-08-24, used to be bundled
   * into the same signed op as the token/language below): a real
   * media-library group and a test/demo group on the same node need not
   * share this decision. Saves immediately on toggle, same as an ordinary
   * checkbox-style setting elsewhere — there is nothing else on the form to
   * batch it with any more.
   */
  const saveTmdbEnabled = useCallback(async (nextEnabled) => {
    const transport = transportRef && transportRef.current;
    setTmdbMsg('');
    setTmdbEnabledBusy(true);
    try {
      if (!transport || !transport.connected) {
        throw new Error('Not connected to the node');
      }
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      await transport.setTmdbEnabled(nextEnabled, signFn);
      if (onTmdbEnabled) onTmdbEnabled(nextEnabled);
    } catch (err) {
      setTmdbMsg(err.message);
    } finally {
      setTmdbEnabledBusy(false);
    }
  }, [transportRef, onTmdbEnabled]);

  /**
   * An optional custom API token, and the language TMDB is queried in —
   * node-wide, not per-group (docs/mediacenter.md §5.5): one shared
   * credential and cache. Same shape as saveScanSettings: signed, and the
   * button does not claim success until the node confirms it. The token
   * field is cleared after a save either way: it is never echoed back by
   * the node (tmdb_config_ack carries only whether one is set, never the
   * value), so there is nothing to keep showing.
   */
  const saveTmdbConfig = useCallback(async () => {
    const transport = transportRef && transportRef.current;
    setTmdbMsg('');
    setTmdbBusy(true);
    try {
      if (!transport || !transport.connected) {
        throw new Error('Not connected to the node');
      }
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      const token = tmdbTokenDraft.trim();
      await transport.setTmdbConfig(token || undefined, tmdbLanguage, signFn);
      setTmdbTokenDraft('');
      if (onTmdbConfig) {
        onTmdbConfig({
          tokenCustomized: token
            ? true
            : (tmdbConfig ? tmdbConfig.tokenCustomized : false),
          language: tmdbLanguage,
        });
      }
      setTmdbMsg(t('settings_node.scan_saved'));
    } catch (err) {
      setTmdbMsg(err.message);
    } finally {
      setTmdbBusy(false);
    }
  }, [transportRef, onTmdbConfig, tmdbTokenDraft, tmdbConfig, tmdbLanguage]);

  // A node that has never had a language explicitly set would otherwise
  // query TMDB with none at all — which TMDB itself resolves to English,
  // regardless of who the operator is — even though this form already
  // *suggests* their own UI language as the value. Applied once,
  // automatically, the first time the operator (the only one who can sign
  // this) is actually connected to see it: a real default tied to whoever
  // runs this particular node, never a single hardcoded language for every
  // node. `tmdbConfig.language` being set at all — from this or from an
  // explicit save — is what stops it from ever firing again, so "unless
  // manually changed" holds regardless of which of the two set it first.
  const autoLanguageSetRef = useRef(false);
  useEffect(() => {
    if (!isNodeAdmin || !connected || !tmdbConfig || tmdbConfig.language) return;
    if (autoLanguageSetRef.current) return;
    autoLanguageSetRef.current = true;
    saveTmdbConfig();
  }, [isNodeAdmin, connected, tmdbConfig, saveTmdbConfig]);

  const [mbBusy, setMbBusy] = useState(false);
  const [mbMsg, setMbMsg] = useState('');
  const [mbContactDraft, setMbContactDraft] = useState('');
  const [mbEnabledBusy, setMbEnabledBusy] = useState(false);
  const mbEnabled = musicbrainzConfig ? musicbrainzConfig.enabled : true;

  /**
   * Whether MusicBrainz is used at all — per-group from the start
   * (docs/musicbay.md §3.2/§6). Same shape as saveTmdbEnabled.
   */
  const saveMusicbrainzEnabled = useCallback(async (nextEnabled) => {
    const transport = transportRef && transportRef.current;
    setMbMsg('');
    setMbEnabledBusy(true);
    try {
      if (!transport || !transport.connected) {
        throw new Error('Not connected to the node');
      }
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      await transport.setMusicbrainzEnabled(nextEnabled, signFn);
      if (onMusicbrainzEnabled) onMusicbrainzEnabled(nextEnabled);
    } catch (err) {
      setMbMsg(err.message);
    } finally {
      setMbEnabledBusy(false);
    }
  }, [transportRef, onMusicbrainzEnabled]);

  /**
   * The node-wide MusicBrainz contact string (docs/musicbay.md §3.2) — not
   * a secret, unlike TMDB's token, but still cleared from the draft field
   * after a save: the node never echoes it back
   * (musicbrainz_config_ack carries only whether one is set), so there is
   * nothing to keep showing.
   */
  const saveMusicbrainzConfig = useCallback(async () => {
    const transport = transportRef && transportRef.current;
    setMbMsg('');
    setMbBusy(true);
    try {
      if (!transport || !transport.connected) {
        throw new Error('Not connected to the node');
      }
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      const contact = mbContactDraft.trim();
      await transport.setMusicbrainzConfig(contact || undefined, signFn);
      setMbContactDraft('');
      if (onMusicbrainzConfig) {
        onMusicbrainzConfig({
          contactConfigured: contact
            ? true
            : (musicbrainzConfig ? musicbrainzConfig.contactConfigured : false),
        });
      }
      setMbMsg(t('settings_node.scan_saved'));
    } catch (err) {
      setMbMsg(err.message);
    } finally {
      setMbBusy(false);
    }
  }, [transportRef, onMusicbrainzConfig, mbContactDraft, musicbrainzConfig]);

  // Every folder anywhere in the group's shared index, deepest included —
  // `entries[].path` is each file's containing directory (files-app.js's own
  // convention), so every ancestor prefix of it is a real folder, and
  // `nodeDirs` covers ones with nothing in them yet. A flat, depth-indented
  // <select> rather than a live folder browser: choosing an app's root is a
  // rare, one-off decision, not something worth a whole navigable tree for.
  // Shared between the Videos and Music root pickers below — same folder
  // set either way.
  const rootFolderOptions = useMemo(() => {
    const set = new Set();
    const addAncestors = (path) => {
      if (!path) return;
      const parts = path.split('/');
      for (let i = 1; i <= parts.length; i++) set.add(parts.slice(0, i).join('/'));
    };
    for (const e of (entries || [])) addAncestors(e.path);
    for (const d of (nodeDirs || [])) addAncestors(d);
    return [...set].sort();
  }, [entries, nodeDirs]);

  const [videoRootDraft, setVideoRootDraft] = useState(videoRoot || '');
  useEffect(() => { setVideoRootDraft(videoRoot || ''); }, [videoRoot]);
  const [videoRootBusy, setVideoRootBusy] = useState(false);
  const [videoRootMsg, setVideoRootMsg] = useState(null);

  /**
   * Which folder is the Videos app's entry point for this group — same
   * shape as toggleApp/saveScanSettings: signed, and the picker does not
   * claim success until the node confirms it.
   *
   * Changing an *already-set* root is destructive to every member's Videos
   * tab (a different set of files, possibly none in common) — the operator
   * confirms that explicitly. Setting it for the first time is not: there is
   * nothing yet to lose.
   */
  const saveVideoRoot = useCallback(async () => {
    const next = videoRootDraft;
    const current = videoRoot || '';
    if (next === current) return;
    if (current && !confirm(t('settings_node.video_root_change_confirm'))) return;
    const transport = transportRef && transportRef.current;
    setVideoRootMsg(null);
    setVideoRootBusy(true);
    try {
      if (!transport || !transport.connected) {
        throw new Error('Not connected to the node');
      }
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      await transport.setVideoRoot(next, signFn);
      if (onVideoRoot) onVideoRoot(next);
      setVideoRootMsg({ text: t('settings_node.scan_saved'), ok: true });
    } catch (err) {
      setVideoRootMsg({ text: err.message, ok: false });
    } finally {
      setVideoRootBusy(false);
    }
  }, [transportRef, onVideoRoot, videoRootDraft, videoRoot]);

  // Same shape as the Videos root above — the Music app's own entry point
  // (docs/musicbay.md's amended §2.1).
  const [audioRootDraft, setAudioRootDraft] = useState(audioRoot || '');
  useEffect(() => { setAudioRootDraft(audioRoot || ''); }, [audioRoot]);
  const [audioRootBusy, setAudioRootBusy] = useState(false);
  const [audioRootMsg, setAudioRootMsg] = useState(null);

  const saveAudioRoot = useCallback(async () => {
    const next = audioRootDraft;
    const current = audioRoot || '';
    if (next === current) return;
    if (current && !confirm(t('settings_node.audio_root_change_confirm'))) return;
    const transport = transportRef && transportRef.current;
    setAudioRootMsg(null);
    setAudioRootBusy(true);
    try {
      if (!transport || !transport.connected) {
        throw new Error('Not connected to the node');
      }
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      await transport.setAudioRoot(next, signFn);
      if (onAudioRoot) onAudioRoot(next);
      setAudioRootMsg({ text: t('settings_node.scan_saved'), ok: true });
    } catch (err) {
      setAudioRootMsg({ text: err.message, ok: false });
    } finally {
      setAudioRootBusy(false);
    }
  }, [transportRef, onAudioRoot, audioRootDraft, audioRoot]);

  // Photos app's own entry points — a set (docs/photos.md §2.1), unlike
  // videoRoot/audioRoot above. No "removing a root is destructive" confirm
  // dialog: removing one root only drops that root's albums from view, it
  // does not replace the whole tab's content the way changing video_root
  // does.
  const [photoRootsBusy, setPhotoRootsBusy] = useState(false);
  const [photoRootsMsg, setPhotoRootsMsg] = useState(null);

  const savePhotoRoots = useCallback(async (nextRoots) => {
    const transport = transportRef && transportRef.current;
    setPhotoRootsMsg(null);
    setPhotoRootsBusy(true);
    try {
      if (!transport || !transport.connected) {
        throw new Error('Not connected to the node');
      }
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      await transport.setPhotoRoots(nextRoots, signFn);
      if (onPhotoRoots) onPhotoRoots(nextRoots);
      setPhotoRootsMsg({ text: t('settings_node.scan_saved'), ok: true });
    } catch (err) {
      setPhotoRootsMsg({ text: err.message, ok: false });
    } finally {
      setPhotoRootsBusy(false);
    }
  }, [transportRef, onPhotoRoots]);

  const [removing, setRemoving] = useState('');

  /**
   * Take someone out of this group: both halves, in the order that fails safe.
   *
   * The node first, because that is the half that stops the group key being
   * wrapped for them; if the hub removal then fails, they are a member on paper
   * with no key. The other order would leave them able to reach a node that
   * still serves them.
   */
  const removeMember = useCallback(async (member) => {
    const transport = transportRef && transportRef.current;
    setError('');
    setRemoving(member.user_id);
    try {
      if (platform.node.available) {
        try {
          await platform.node.call('POST',
            `/api/members/${member.user_id}/revoke?group_id=${groupId}`);
        } catch { /* best effort — node may not host this group */ }
        try {
          await platform.node.call('POST',
            `/api/members/${member.user_id}/unpin`);
        } catch { /* best effort */ }
      } else if (transport && transport.connected && operatorPaired) {
        const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
        const signFn = (sk && window.MeshBayKeys)
          ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
          : null;
        await transport.revokeMember(member.user_id, signFn);
      }
      await hubFetch(`/v1/groups/${groupId}/members/${member.username}`, {
        method: 'DELETE', token,
      });
      loadMembers();
    } catch (err) {
      setError(err.message);
    } finally {
      setRemoving('');
    }
  }, [groupId, token, transportRef, operatorPaired]);

  const loadMembers = useCallback(() => {
    setLoading(true);
    hubFetch(`/v1/groups/${groupId}/members`, { token })
      .then(data => {
        setMembers(data.members || []);
        setAdminId(data.admin_id || '');
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [groupId, token]);

  useEffect(() => { loadMembers(); }, [loadMembers]);

  const isAdmin = group && group.is_admin;

  const doInvite = useCallback(async (e) => {
    e.preventDefault();
    if (!inviteUser.trim()) return;
    setInviting(true);
    setError('');
    setInviteCode(null);
    try {
      const transport = transportRef && transportRef.current;
      const username = inviteUser.trim();
      if (!transport || !transport.connected) {
        throw new Error('Not connected to the node — it must be online to invite');
      }

      // The hub is asked for the account id, and nothing else. It is no longer
      // asked for the invitee's public key: the node wraps the group key itself,
      // for a key the invitee proves possession of when they connect (H3). A hub
      // that answered with the wrong account here would produce an invite whose
      // code it never learns — the code goes to a human, out of band.
      const account = await hubFetch(`/v1/users/${username}/pubkeys`, { token });

      // Signed with the identity this node pinned for us — the only one it
      // will accept, and the only one we hold here.
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      const result = await transport.createInvite(
        account.user_id, groupId, username, signFn);

      // Membership on the hub is what lets them reach the node at all; the code
      // is what gets them the key.
      await hubFetch(`/v1/groups/${groupId}/members/${username}`, {
        method: 'POST', token, body: {},
      });

      setInviteCode({ username, code: result.code, expires: result.expires_at });
      setInviteUser('');
      loadMembers();
    } catch (err) {
      setError(err.message);
    } finally {
      setInviting(false);
    }
  }, [groupId, token, inviteUser, loadMembers, transportRef]);

  if (loading) return html`<p class="page-message">${t('explore.loading')}</p>`;

  const isOwner = Boolean(isAdmin);

  return html`
    <div class="members-panel">
      ${error && html`<div class="error-msg" style="margin-bottom:12px">${error}</div>`}

      ${/* Inviting needs the node: it is the node that wraps the group key and
            issues the code, not the hub. Public groups admit anyone — no invite.
            The form stays in the DOM so a brief reconnect does not destroy the
            input the user is typing into — controls are disabled instead. */
        isAdmin && group?.join_policy !== 'open' && html`
        <div class="settings-section">
          <h3 class="settings-heading">${t('members.invite_title')}</h3>
          ${!connected ? html`
            <p class="settings-hint">${t('group.offline_title')}</p>
          ` : !operatorPaired ? html`
            <p class="settings-hint">
              ${isNodeAdmin ? t('members.invite_needs_pairing')
                            : t('members.invite_ask_operator')}
            </p>
          ` : ''}
          <form onSubmit=${doInvite}>
            ${inviteCode && html`
              <div class="success-msg" style="margin-bottom:8px">
                <p>${t('members.invite_code_ready', { user: inviteCode.username })}</p>
                <p class="code-display">${inviteCode.code}</p>
                <p>${t('members.invite_code_hint')}</p>
              </div>
            `}
            <div class="form-row">
              <input type="text" placeholder="${t('members.username_placeholder')}"
                value=${inviteUser} onInput=${e => setInviteUser(e.target.value)}
                disabled=${!connected || !operatorPaired} required />
              <button class="admin-btn" type="submit"
                disabled=${inviting || !connected || !operatorPaired}>
                ${inviting ? '...' : t('members.invite_btn')}
              </button>
            </div>
          </form>
        </div>
      `}

      ${isNodeAdmin && !operatorPaired && connected && html`
        <div class="settings-section">
          <h3 class="settings-heading">${t('members.pair_title')}</h3>
          <p class="settings-hint">${t('members.pair_hint')}</p>
          ${pairStatus && html`
            <p class=${pairStatus === 'paired' ? 'success-msg' : 'error-msg'}>
              ${pairStatus === 'paired' ? t('members.pair_success') : pairStatus}
            </p>
          `}
          <form class="form-row" onSubmit=${doPair}>
            <input type="text" placeholder="XXXX-XXXX" class="code-input"
              value=${pairCode} onInput=${e => setPairCode(e.target.value)} required />
            <button class="admin-btn" type="submit" disabled=${pairing}>
              ${pairing ? '...' : t('members.pair_btn')}
            </button>
          </form>
        </div>
      `}

      ${/* Which group "applications" members see. New ones (Videos, Music,
            Photos) show up here automatically as they register in apps.js —
            nothing about this section changes to add one. */
        isNodeAdmin && connected && html`
        <${CollapsibleSection} titleKey="members.apps_title">
          <p class="settings-hint">${t('members.apps_hint')}</p>
          <ul class="apps-toggle-list">
            ${APPS.map(a => html`
              <li key=${a.key} class="settings-row">
                <label class="settings-label">
                  <input type="checkbox" checked=${activeApps.includes(a.key)}
                    disabled=${appsBusy}
                    onChange=${() => toggleApp(a.key)} />
                  ${' '}${t(a.labelKey)}
                </label>
              </li>
            `)}
          </ul>
          ${appsMsg && html`<p class="error-msg">${appsMsg}</p>`}
        </${CollapsibleSection}>
      `}

      ${/* How hard the node works watching its own disk — indexer.py
            DirectoryIndexer. A performance knob, not a permission: it
            changes nothing about who can see or do what. */
        isNodeAdmin && connected && html`
        <${CollapsibleSection} titleKey="settings_node.scan_title" defaultOpen=${false}>
          <p class="settings-hint">${t('settings_node.scan_hint')}</p>
          <div class="settings-row">
            <label class="settings-label">
              ${t('settings_node.scan_reconcile_label')}
              <input type="number" min="1" max="1440" step="1"
                value=${reconcileMinutes} disabled=${scanBusy}
                onInput=${e => setReconcileMinutes(Number(e.target.value))} />
            </label>
          </div>
          <div class="settings-row">
            <label class="settings-label">
              ${t('settings_node.scan_debounce_label')}
              <input type="number" min="0" max="300" step="1"
                value=${debounceSeconds} disabled=${scanBusy}
                onInput=${e => setDebounceSeconds(Number(e.target.value))} />
            </label>
          </div>
          <button class="btn btn-small btn-secondary" style="margin-top:8px"
            disabled=${scanBusy} onClick=${saveScanSettings}>
            ${scanBusy ? t('settings_node.scan_saving') : t('settings_node.scan_save')}
          </button>
          ${scanMsg && html`<p class="settings-hint">${scanMsg}</p>`}
        </${CollapsibleSection}>
      `}

      ${/* The on/off switch is per-group (2026-08-24); the custom token and
            query language stay node-wide, one shared credential/cache
            (docs/mediacenter.md §5.5). Both are new outbound third-party
            traffic the node did not have before the Videos app, so both are
            signed operator settings, not display preferences — but two
            independent ones now, saved separately. */
        isNodeAdmin && connected && html`
        <${CollapsibleSection} defaultOpen=${false} title=${html`
          <span class="settings-meta-title">
            <${Icon} name="server" />${' '}${t('settings_node.tmdb_title')}
            <span class="settings-meta-badge ${tmdbEnabled ? 'on' : ''}">
              ${tmdbEnabled ? t('settings_node.tmdb_enabled') : t('settings_node.tmdb_disabled')}
            </span>
          </span>
        `}>
          <p class="settings-hint">${t('settings_node.tmdb_hint')}</p>
          <div class="settings-row">
            <${ToggleSwitch} checked=${tmdbEnabled} disabled=${tmdbEnabledBusy}
              onChange=${(v) => saveTmdbEnabled(v)}
              label=${tmdbEnabled ? t('settings_node.tmdb_enabled') : t('settings_node.tmdb_disabled')} />
          </div>
          <div class="settings-row">
            <label class="settings-label">
              ${t('settings_node.tmdb_token_label')}
              <input type="password" placeholder=${t('settings_node.tmdb_token_placeholder')}
                value=${tmdbTokenDraft} disabled=${tmdbBusy}
                onInput=${e => setTmdbTokenDraft(e.target.value)} />
            </label>
            <p class="settings-hint">
              ${tmdbConfig && tmdbConfig.tokenCustomized
                ? t('settings_node.tmdb_token_customized')
                : t('settings_node.tmdb_token_default')}
            </p>
          </div>
          <div class="settings-row">
            <label class="settings-label">
              ${t('settings_node.tmdb_language_label')}
              <select value=${tmdbLanguage} disabled=${tmdbBusy}
                onChange=${e => setTmdbLanguage(e.target.value)}>
                ${LOCALES.map(l => html`
                  <option key=${l.code} value=${TMDB_LANGUAGE_BY_LOCALE[l.code]}>
                    ${l.name}
                  </option>
                `)}
              </select>
            </label>
            <p class="settings-hint">${t('settings_node.tmdb_language_hint')}</p>
          </div>
          <button class="btn btn-small btn-secondary" style="margin-top:8px"
            disabled=${tmdbBusy} onClick=${() => saveTmdbConfig()}>
            ${tmdbBusy ? t('settings_node.scan_saving') : t('settings_node.tmdb_save')}
          </button>
          ${tmdbMsg && html`<p class="settings-hint">${tmdbMsg}</p>`}
        </${CollapsibleSection}>
      `}

      ${/* Same two-part shape as TMDB above: the on/off switch is per-group,
            the contact string stays node-wide (docs/musicbay.md §3.2) —
            one operator identity, not a per-group concern. Unlike TMDB
            there is no token field: MusicBrainz's read endpoints need no
            credential, just a descriptive User-Agent contact. */
        isNodeAdmin && connected && html`
        <${CollapsibleSection} defaultOpen=${false} title=${html`
          <span class="settings-meta-title">
            <${Icon} name="music" />${' '}${t('settings_node.musicbrainz_title')}
            <span class="settings-meta-badge ${mbEnabled ? 'on' : ''}">
              ${mbEnabled ? t('settings_node.musicbrainz_enabled') : t('settings_node.musicbrainz_disabled')}
            </span>
          </span>
        `}>
          <p class="settings-hint">${t('settings_node.musicbrainz_hint')}</p>
          <div class="settings-row">
            <${ToggleSwitch} checked=${mbEnabled} disabled=${mbEnabledBusy}
              onChange=${(v) => saveMusicbrainzEnabled(v)}
              label=${mbEnabled ? t('settings_node.musicbrainz_enabled') : t('settings_node.musicbrainz_disabled')} />
          </div>
          <div class="settings-row">
            <label class="settings-label">
              ${t('settings_node.musicbrainz_contact_label')}
              <input type="text" placeholder=${t('settings_node.musicbrainz_contact_placeholder')}
                value=${mbContactDraft} disabled=${mbBusy}
                onInput=${e => setMbContactDraft(e.target.value)} />
            </label>
            <p class="settings-hint">
              ${musicbrainzConfig && musicbrainzConfig.contactConfigured
                ? t('settings_node.musicbrainz_contact_set')
                : t('settings_node.musicbrainz_contact_unset')}
            </p>
          </div>
          <button class="btn btn-small btn-secondary" style="margin-top:8px"
            disabled=${mbBusy} onClick=${() => saveMusicbrainzConfig()}>
            ${mbBusy ? t('settings_node.scan_saving') : t('settings_node.musicbrainz_save')}
          </button>
          ${mbMsg && html`<p class="settings-hint">${mbMsg}</p>`}
        </${CollapsibleSection}>
      `}

      ${/* Which folder is the Videos app's entry point for this group —
            per-group like uploads, not node-wide like TMDB (mediacenter.md
            §5.6). Until one is chosen, the Videos tab says so instead of
            listing anything, and the node runs no TMDB/thumbnail work for
            this group at all (daemon.py's _enrich_new_video_entries). */
        isNodeAdmin && connected
          && ((nodeDetected && nodeRoots.length > 0)
              || activeApps.includes('video') || activeApps.includes('music')
              || activeApps.includes('photo')) && html`
        <${CollapsibleSection} titleKey="settings_node.directories_title">
          <p class="settings-hint">${t('settings_node.directories_hint')}</p>

          ${activeApps.includes('video') && html`
            <${RootFolderRow} icon="video"
              titleKey="settings_node.video_root_title" hintKey="settings_node.video_root_hint"
              folders=${rootFolderOptions} value=${videoRoot}
              draft=${videoRootDraft} onDraftChange=${setVideoRootDraft}
              busy=${videoRootBusy} msg=${videoRootMsg} onSave=${saveVideoRoot}
              noneKey="settings_node.video_root_none" saveKey="settings_node.video_root_save" />
          `}
          ${activeApps.includes('music') && html`
            <${RootFolderRow} icon="music"
              titleKey="settings_node.audio_root_title" hintKey="settings_node.audio_root_hint"
              folders=${rootFolderOptions} value=${audioRoot}
              draft=${audioRootDraft} onDraftChange=${setAudioRootDraft}
              busy=${audioRootBusy} msg=${audioRootMsg} onSave=${saveAudioRoot}
              noneKey="settings_node.audio_root_none" saveKey="settings_node.audio_root_save" />
          `}
          ${activeApps.includes('photo') && html`
            <${PhotoRootsRow}
              folders=${rootFolderOptions} value=${photoRoots}
              busy=${photoRootsBusy} msg=${photoRootsMsg} onSave=${savePhotoRoots} />
          `}
      ${/* Roots management (Electron-only, when node is local) — folded into
            the same Directories section as the two root pickers above. */
        nodeDetected && nodeRoots.length > 0 && html`
        <div class="settings-root-row">
          <div class="settings-root-row-title">
            <${Icon} name="server" />
            <h4>${t('settings_node.roots')}</h4>
          </div>
          ${nodeMsg && html`<p class="settings-hint">${nodeMsg}</p>`}
          <div class="node-roots">
            ${nodeRoots.map(r => html`
              <div class="node-root ${!r.available ? 'node-root-unavailable' : ''}"
                   key=${r.name}>
                <div class="node-root-info">
                  <span class="node-root-name">
                    <${Icon} name="folder" />
                    ${r.name}
                  </span>
                  ${r.upload && html`
                    <span class="node-root-badge">${t('node.upload_root')}</span>`}
                  ${!r.available && html`
                    <span class="node-root-badge node-root-badge-warn">
                      ${t('node.unavailable')}</span>`}
                </div>
                ${nodeRoots.length > 1 && !r.upload && html`
                  <button class="btn btn-small btn-danger"
                    disabled=${nodeBusy}
                    onClick=${async () => {
                      if (!confirm(t('node.root_remove_confirm', { name: r.name }))) return;
                      const countBefore = nodeRoots.length;
                      setNodeBusy(true); setNodeMsg('');
                      try {
                        await platform.node.call('DELETE',
                          '/api/groups/' + groupId + '/roots/' + encodeURIComponent(r.name));
                        await platform.node.call('POST', '/api/reload');
                        setNodeMsg(t('node.root_removed'));
                        await waitForRootCount(countBefore - 1);
                        // Folders (unlike files) only ever arrive via a full
                        // index_sync, never index_delta (daemon.py's ongoing
                        // push has no `dirs` field) — without this, the
                        // Videos/Music root pickers kept offering a folder
                        // that no longer existed until the page was reloaded.
                        if (onRefreshIndex) await onRefreshIndex();
                      } catch (err) { setNodeMsg(platform.bridgeMessage(err)); }
                      finally { setNodeBusy(false); }
                    }}>
                    ${t('node.remove_root')}</button>`}
              </div>
            `)}
            <button class="btn btn-small btn-secondary" style="margin-top:8px"
              disabled=${nodeBusy}
              onClick=${async () => {
                const chosen = await platform.rootPicker.choose();
                if (!chosen) return;
                const countBefore = nodeRoots.length;
                setNodeBusy(true); setNodeMsg(''); setNodeIndexProgress(null);
                try {
                  await platform.node.call('POST',
                    '/api/groups/' + groupId + '/roots',
                    { path: chosen.path, name: chosen.name });
                  await platform.node.call('POST', '/api/reload');
                  // The root is already scanning in the background on the
                  // node regardless of whether anyone watches this — see
                  // the "closing the client" test in test_hot_reload_*.py.
                  // This is only about not leaving the operator staring at
                  // an unchanged screen while it happens.
                  await platform.watchIndexProgress(groupId, setNodeIndexProgress);
                  setNodeMsg(t('node.root_added'));
                  await waitForRootCount(countBefore + 1);
                  // See the matching comment on root removal above — a new
                  // folder needs a full index_sync to show up anywhere that
                  // reads `nodeDirs` (the Videos/Music root pickers), not
                  // just in this section's own node-roots list.
                  if (onRefreshIndex) await onRefreshIndex();
                } catch (err) { setNodeMsg(platform.bridgeMessage(err)); }
                finally { setNodeBusy(false); }
              }}>
              <${Icon} name="folder-plus" /> ${t('node.add_root')}
            </button>
            ${nodeIndexProgress && nodeIndexProgress.scanning && html`
              <div class="index-progress" style="margin-top:8px">
                <div class="index-progress-bar">
                  <div class="index-progress-fill" style="width:${
                    nodeIndexProgress.total_bytes
                      ? Math.min(100, Math.round(
                          100 * nodeIndexProgress.scanned_bytes / nodeIndexProgress.total_bytes))
                      : 0}%"></div>
                </div>
                <div class="index-progress-label">${t('wizard.indexing_progress', {
                  pct: nodeIndexProgress.total_bytes
                    ? Math.min(100, Math.round(
                        100 * nodeIndexProgress.scanned_bytes / nodeIndexProgress.total_bytes))
                    : 0,
                })}</div>
                ${nodeIndexProgress.current_dir && html`
                  <div class="index-progress-dir">
                    ${t('wizard.indexing_current_dir', { dir: nodeIndexProgress.current_dir })}
                  </div>
                `}
              </div>
            `}
          </div>
        </div>
      `}
        </${CollapsibleSection}>
      `}

      ${/* Operator only, and only with a live connection: the node is what
            holds and enforces this, so there is nothing to show or change
            without one. */ isNodeAdmin && connected && html`
        <${CollapsibleSection} titleKey="members.uploads_title">
          <div class="settings-row">
            <${ToggleSwitch} checked=${memberUpload} disabled=${uploadBusy}
              onChange=${() => setUploads(!memberUpload)}
              label=${memberUpload ? t('members.uploads_on') : t('members.uploads_off')} />
          </div>
          <p class="settings-hint">${t('members.uploads_hint')}</p>
          ${uploadMsg && html`<p class="error-msg">${uploadMsg}</p>`}
        </${CollapsibleSection}>
      `}

      ${/* Upload toggle via loopback when MNP not connected */
        nodeDetected && !connected && html`
        <${CollapsibleSection} titleKey="members.uploads_title">
          <div class="settings-row">
            <${ToggleSwitch} checked=${memberUpload} disabled=${nodeBusy}
              onChange=${async () => {
                setNodeBusy(true); setNodeMsg('');
                try {
                  const newVal = !memberUpload;
                  await platform.node.call('PUT',
                    '/api/groups/' + groupId + '/member-upload',
                    { allowed: newVal });
                  if (onMemberUpload) onMemberUpload(newVal);
                } catch (err) { setNodeMsg(platform.bridgeMessage(err)); }
                finally { setNodeBusy(false); }
              }}
              label=${memberUpload ? t('members.uploads_on') : t('members.uploads_off')} />
          </div>
          <p class="settings-hint">${t('members.uploads_hint')}</p>
        </${CollapsibleSection}>
      `}

      ${/* Delete/leave — node detach first (reversible), then hub delete
            (irreversible). Closed by default: a danger-zone action is one
            click away either way, but not the first thing seen on open. */
        html`
        <${CollapsibleSection} defaultOpen=${false}
          title=${isOwner ? t('group.delete_group') : t('group.leave')}>
          <div class="settings-row">
            <span class="settings-label">
              ${isOwner ? t('members.danger_delete_hint')
                        : t('members.danger_leave_hint')}
            </span>
            ${isOwner
              ? html`
                <button class="admin-btn danger" onClick=${async () => {
                  if (!confirm(t('group.delete_group_confirm', { name: group.name }))) return;
                  try {
                    // Node detach first (reversible), then hub delete (irreversible)
                    if (nodeDetected && nodeGroupName) {
                      try {
                        await platform.node.call('POST', '/api/groups/detach',
                          { name: nodeGroupName });
                      } catch (detachErr) {
                        if (!confirm(t('settings_node.detach_failed_continue'))) return;
                      }
                    }
                    await hubFetch('/v1/groups/' + groupId, { method: 'DELETE', token });
                    navigate('/');
                    window.location.reload();
                  } catch (err) { setError(err.message); }
                }}>${t('group.delete_group')}</button>
              `
              : html`
                <button class="admin-btn danger" onClick=${async () => {
                  if (!confirm(t('group.leave_confirm', { name: group.name }))) return;
                  try {
                    await hubFetch('/v1/groups/' + groupId + '/leave',
                                   { method: 'POST', token });
                    if (onLeft) onLeft(groupId);
                  } catch (err) { setError(err.message); }
                }}>${t('group.leave')}</button>
              `}
          </div>
        </${CollapsibleSection}>
      `}

      ${connected && html`
        <div class="settings-section">
          <h3 class="settings-heading">${t('device.mine_title')}</h3>
          <p class="settings-hint">${t('device.mine_hint')}</p>
          ${deviceMsg && html`<p class="settings-hint">${deviceMsg}</p>`}
          ${devices.length === 0
            ? html`<p class="settings-hint">${t('device.mine_empty')}</p>`
            : html`
              <ul class="device-list">
                ${devices.map(d => html`
                  <li class="device-row" key=${d.pk_ed25519}>
                    <span class="device-key">${d.pk_ed25519.slice(0, 16)}…</span>
                    <span class="device-meta">
                      ${d.is_this_one && html`
                        <span class="badge">${t('device.this_one')}</span>${' '}
                      `}
                      ${d.pinned_via}${d.label ? ' · ' + d.label : ''}
                    </span>
                    ${!d.is_this_one && devices.length > 1 && html`
                      <button class="admin-btn" onClick=${() => revokeDevice(d)}>
                        ${t('device.revoke')}
                      </button>
                    `}
                  </li>
                `)}
              </ul>
            `}
          <form onSubmit=${approveDevice} class="settings-subform">
            <p class="settings-hint">${t('device.approve_hint')}</p>
            <div class="form-row">
              <input type="text" placeholder="XXXX-XXXX" class="code-input"
                value=${approveCode} onInput=${e => setApproveCode(e.target.value)} />
              <button class="admin-btn" type="submit">${t('device.approve_btn')}</button>
            </div>
          </form>
        </div>
      `}

      <${CollapsibleSection} title=${`${t('group.tab_members')} (${members.length})`}>
        <table class="admin-table">
          <thead>
            <tr>
              <th>${t('admin.col_username')}</th>
              <th>${t('members.group_role')}</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            ${members.map(m => html`
              <tr key=${m.user_id}>
                <td>${m.username}</td>
                <td>
                  ${m.user_id === adminId
                    ? html`<span class="badge badge-owner">${t('members.owner')}</span>`
                    : html`<span class="badge">${t('members.member')}</span>`
                  }
                </td>
                <td class="admin-actions">
                  ${isAdmin && m.user_id !== adminId && html`
                    <button class="admin-btn danger" disabled=${removing === m.user_id}
                      onClick=${() => {
                        if (!confirm(t('members.remove_confirm', { user: m.username }))) return;
                        removeMember(m);
                      }}>
                      ${removing === m.user_id ? '...' : t('members.remove')}
                    </button>
                  `}
                </td>
              </tr>
            `)}
          </tbody>
        </table>
        ${isAdmin && members.length > 1 && html`
          <p class="settings-hint">${t('members.remove_hint')}</p>
        `}
      </${CollapsibleSection}>
    </div>
  `;
}

// ── Chat Panel ──────────────────────────────────────────────────────────

/**
 * Message text with its links made clickable.
 *
 * Only http and https, and built as elements rather than markup: a message is
 * something another member wrote, so it must never become HTML. `javascript:`
 * and `data:` are not matched at all, and the anchors carry noopener so the new
 * tab cannot reach back into this one.
 */
const URL_RE = /\bhttps?:\/\/[^\s<>"']+/gi;


export { GroupSettingsPanel };