summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/app.js
blob: 4b5ccd350d30a863c817cc80e6050d543ab2805a (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
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
import {
  html, render, useState, useEffect, useLayoutEffect, useCallback, useRef,
  createContext, useContext,
} from './vendor/htm-preact.js';
import { t, getLocale, setLocale, initLocale, LOCALES } from './i18n.js';
import { ZipStream, entriesUnder } from './zipstream.js';
import { transfers, formatSpeed } from './transfers.js';
import * as downloads from './downloads.js';
import * as platform from './platform.js';

// ── Constants ────────────────────────────────────────────────────────────────

// Where the hub is. Empty in a browser — it served this page, so a relative
// path cannot be pointed at the wrong place. In the installed app the page
// comes from disk and has no origin of its own, so the base is configured.
// See platform.js.
const HUB = platform.hubBase();
const AUTH_KEY = 'mb_auth';
// Renew an access token with this much life left rather than waiting for it to
// fail. Generous against a one-hour token: a film is watched without the hub
// hearing a word, and coming back to a tab that has been asleep for an hour
// should not cost a round trip before the first click works.
const TOKEN_RENEW_MARGIN_S = 600;
// How often to look. Cheap — it reads a timestamp out of the token and almost
// always does nothing.
const TOKEN_CHECK_MS = 60000;
const THEME_KEY = 'mb_theme';
const IDB_NAME = 'meshbay';
const IDB_VERSION = 1;
const IDB_STORE = 'group_indexes';

// ── IndexedDB cache ─────────────────────────────────────────────────────────

function openDB() {
  return new Promise((resolve, reject) => {
    const req = indexedDB.open(IDB_NAME, IDB_VERSION);
    req.onupgradeneeded = () => {
      const db = req.result;
      if (!db.objectStoreNames.contains(IDB_STORE)) {
        db.createObjectStore(IDB_STORE, { keyPath: 'groupId' });
      }
    };
    req.onsuccess = () => resolve(req.result);
    req.onerror = () => reject(req.error);
  });
}

async function cacheGroupIndex(groupId, groupName, entries) {
  try {
    const db = await openDB();
    const tx = db.transaction(IDB_STORE, 'readwrite');
    tx.objectStore(IDB_STORE).put({
      groupId, groupName, entries, cachedAt: Date.now(),
    });
    await new Promise((r, rej) => { tx.oncomplete = r; tx.onerror = rej; });
    db.close();
  } catch { /* best-effort */ }
}

async function getCachedGroupIndex(groupId) {
  try {
    const db = await openDB();
    const tx = db.transaction(IDB_STORE, 'readonly');
    const req = tx.objectStore(IDB_STORE).get(groupId);
    const result = await new Promise((r, rej) => { req.onsuccess = () => r(req.result); req.onerror = rej; });
    db.close();
    return result || null;
  } catch { return null; }
}

async function getAllCachedIndexes() {
  try {
    const db = await openDB();
    const tx = db.transaction(IDB_STORE, 'readonly');
    const req = tx.objectStore(IDB_STORE).getAll();
    const result = await new Promise((r, rej) => { req.onsuccess = () => r(req.result); req.onerror = rej; });
    db.close();
    return result || [];
  } catch { return []; }
}

// ── Auth persistence ─────────────────────────────────────────────────────────

// The key that opens a node's keypair bundle, derived once at sign-in. There is
// no global identity to keep: identity keys belong to a node and are fetched from
// it (transport.js), so nothing of that kind lives here.
let _bundleKey = null;
// A one-time pairing code the user just typed, consumed by the next connection
// attempt. Deliberately not persisted: it is single-use and short-lived.
let _pendingJoinCode = null;

function _openKeyDB() {
  return new Promise((resolve, reject) => {
    const req = indexedDB.open('meshbay_keys', 1);
    req.onupgradeneeded = () => req.result.createObjectStore('k');
    req.onsuccess = () => resolve(req.result);
    req.onerror = () => reject(req.error);
  });
}
async function _storeBundleKey(key) {
  try {
    const db = await _openKeyDB();
    const tx = db.transaction('k', 'readwrite');
    tx.objectStore('k').put(key, 'bk');
    await new Promise(r => { tx.oncomplete = r; });
    db.close();
  } catch {}
}
async function _loadBundleKey() {
  try {
    const db = await _openKeyDB();
    const tx = db.transaction('k', 'readonly');
    const g = tx.objectStore('k').get('bk');
    const val = await new Promise(r => { g.onsuccess = () => r(g.result); });
    db.close();
    return val || null;
  } catch { return null; }
}
async function _clearKeyDB() {
  try {
    const db = await _openKeyDB();
    const tx = db.transaction('k', 'readwrite');
    tx.objectStore('k').clear();
    await new Promise(r => { tx.oncomplete = r; });
    db.close();
  } catch {}
}
/**
 * Rough passphrase strength, in bits, and what it is up against.
 *
 * This number carries more weight here than in most applications. The encrypted
 * keypair bundle is protected by PBKDF2-SHA512 (600k) and sits on every node
 * whose group you join, so the people who host your groups can attack it offline
 * (finding C4). PBKDF2 is memory-light, which is exactly what GPUs are good at.
 *
 * The estimate is deliberately conservative — character classes and length, with
 * a penalty for repetition and for the handful of patterns everyone tries. It is
 * a guide, not a guarantee, and it says so in the UI.
 */
function passwordBits(pw) {
  if (!pw) return 0;
  let pool = 0;
  if (/[a-z]/.test(pw)) pool += 26;
  if (/[A-Z]/.test(pw)) pool += 26;
  if (/[0-9]/.test(pw)) pool += 10;
  if (/[^A-Za-z0-9]/.test(pw)) pool += 32;
  let bits = pw.length * Math.log2(pool || 1);

  const unique = new Set(pw).size;
  if (unique < pw.length / 2) bits *= 0.6;          // "aaaaaaaa", "abcabcabc"
  if (/^[0-9]+$/.test(pw)) bits *= 0.5;             // dates, PINs
  if (/(password|motdepasse|azerty|qwerty|123456|meshbay)/i.test(pw)) bits *= 0.3;
  return Math.round(bits);
}

const PASSWORD_MIN_BITS = 60;   // refuse below this
const PASSWORD_MIN_LEN = 12;

/** Public X25519 key from our own secret — never read back from the hub. */
async function _pkXFromSk(skPkcs8B64) {
  const raw = Uint8Array.from(atob(skPkcs8B64), c => c.charCodeAt(0));
  const sk = await crypto.subtle.importKey('pkcs8', raw, { name: 'X25519' }, true, ['deriveBits']);
  const jwk = await crypto.subtle.exportKey('jwk', sk);
  const b64 = jwk.x.replace(/-/g, '+').replace(/_/g, '/');
  const pad = b64.length % 4;
  return pad ? b64 + '='.repeat(4 - pad) : b64;
}

function loadAuth() {
  try {
    return JSON.parse(localStorage.getItem(AUTH_KEY));
  } catch {
    return null;
  }
}

function saveAuth(auth) {
  if (auth) {
    localStorage.setItem(AUTH_KEY, JSON.stringify(auth));
  } else {
    localStorage.removeItem(AUTH_KEY);
    _bundleKey = null;
    _clearKeyDB();
  }
}

// ── Session ──────────────────────────────────────────────────────────────────
//
// The access token lasts an hour and the refresh token thirty days. Nothing was
// using the second: `hubFetch` reported a 401 as an error like any other, so an
// hour of watching a film — during which the hub hears nothing, because the
// video comes over WebRTC — ended with "token expired or invalid" and no way
// out but signing out and back in. Reopening the tab the next day did the same,
// with a perfectly good refresh token sitting in localStorage beside the stale
// access one.
//
// This lives outside the component because `hubFetch` is a plain function and
// has to be able to renew a token mid-request without every caller passing the
// machinery down to it.

let _auth = loadAuth();
let _onAuthChange = null;    // set by App, so the UI follows a background renewal
let _refreshing = null;      // in flight, shared: see refreshAccessToken

function setAuth(auth) {
  _auth = auth;
  saveAuth(auth);
  if (_onAuthChange) _onAuthChange(auth);
}

/** Seconds until this JWT expires, or null if it says nothing useful. */
function tokenLifeLeft(token) {
  try {
    const payload = JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')));
    if (!payload.exp) return null;
    return payload.exp - Math.floor(Date.now() / 1000);
  } catch {
    return null;   // not a JWT we can read; treat as unknown, never as expired
  }
}

/**
 * Trade the refresh token for a new pair.
 *
 * The hub rotates: it revokes the token presented and returns a new one, and a
 * revoked token presented again revokes the whole family. So the new one must
 * be stored — the previous code kept only the access token and dropped its
 * replacement, which burned the refresh token on first use and locked the
 * account out of renewal on the second. That is why signing out and in was the
 * only way back.
 *
 * Concurrent callers share one request. Two 401s racing would otherwise send
 * the same refresh token twice, and the second would look exactly like theft.
 */
async function refreshAccessToken() {
  if (!_auth || !_auth.refreshToken) return null;
  if (_refreshing) return _refreshing;
  _refreshing = (async () => {
    try {
      const r = await platform.apiFetch(HUB + '/v1/users/token/refresh', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ refresh_token: _auth.refreshToken }),
      });
      if (!r.ok) {
        // Expired, revoked, or the family was torn down. Nothing to salvage:
        // sign out cleanly rather than leave a session that fails every call.
        setAuth(null);
        return null;
      }
      const data = await r.json();
      setAuth({
        ..._auth,
        token: data.access_token,
        refreshToken: data.refresh_token || _auth.refreshToken,
      });
      return data.access_token;
    } catch {
      return null;   // offline: keep the session, the next call can try again
    } finally {
      _refreshing = null;
    }
  })();
  return _refreshing;
}

/** Renew before it bites, rather than after. */
async function ensureFreshToken() {
  if (!_auth || !_auth.token) return null;
  const left = tokenLifeLeft(_auth.token);
  if (left !== null && left > TOKEN_RENEW_MARGIN_S) return _auth.token;
  return refreshAccessToken();
}

// ── Theme ────────────────────────────────────────────────────────────────────

function getInitialTheme() {
  const stored = localStorage.getItem(THEME_KEY);
  if (stored === 'dark' || stored === 'light' || stored === 'system') return stored;
  return 'system';
}

function resolveTheme(pref) {
  if (pref === 'system') {
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
  }
  return pref;
}

// ── Hub API ──────────────────────────────────────────────────────────────────

async function hubFetch(path, { method = 'GET', body, token, _retried } = {}) {
  const headers = {};
  if (body) headers['Content-Type'] = 'application/json';
  // Prefer the token the session currently holds. Callers read theirs from
  // React state, which is a render behind a renewal that happened in the
  // background — and sending the stale one would 401 for no reason.
  const bearer = token && _auth && _auth.token ? _auth.token : token;
  if (bearer) headers['Authorization'] = `Bearer ${bearer}`;
  const opts = { method, headers };
  if (body) opts.body = JSON.stringify(body);
  const r = await platform.apiFetch(HUB + path, opts);
  if (r.status === 401 && bearer && !_retried) {
    // The one case worth a second attempt: the access token aged out while
    // nothing was talking to the hub. Renew once and replay. If the renewal
    // fails it signs out, and the replay below is skipped.
    const fresh = await refreshAccessToken();
    if (fresh) {
      return hubFetch(path, { method, body, token: fresh, _retried: true });
    }
  }
  if (!r.ok) {
    const err = await r.json().catch(() => ({ detail: r.statusText }));
    const detail = Array.isArray(err.detail)
      ? err.detail.map(e => e.msg || JSON.stringify(e)).join(', ')
      : (err.detail || r.statusText);
    throw new Error(String(detail));
  }
  return r.json();
}

// ── Router ───────────────────────────────────────────────────────────────────

function useRoute() {
  const [hash, setHash] = useState(window.location.hash.slice(1) || '/');
  useEffect(() => {
    const onHash = () => setHash(window.location.hash.slice(1) || '/');
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return hash;
}

function navigate(path) {
  window.location.hash = path;
}

// ── Context ──────────────────────────────────────────────────────────────────

const AuthContext = createContext(null);
function useAuth() { return useContext(AuthContext); }

// ── Icons ────────────────────────────────────────────────────────────────────
//
// One stroked set, drawn in currentColor and sized in em, so an icon takes the
// weight and colour of the text beside it. The Administration entry was already
// an outline shield while the rest of the site was colour emoji — a different
// drawing on every operating system, and never the same line weight twice.
//
// The explorer keeps its emoji on purpose. There the icon says what kind of file
// this is, and the colour is doing real work; a wall of identical grey outlines
// would be a worse file list.

const ICON_PATHS = {
  menu:     ['M4 7h16M4 12h16M4 17h16'],
  bell:     ['M18 9a6 6 0 1 0-12 0c0 6-2.5 7.5-2.5 7.5h17S18 15 18 9',
             'M10.3 20a2 2 0 0 0 3.4 0'],
  shield:   ['M12 3l7.5 3v5.2c0 4.6-3.1 8.6-7.5 10.3-4.4-1.7-7.5-5.7-7.5-10.3V6z'],
  globe:    ['M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18',
             'M3.4 9.2h17.2M3.4 14.8h17.2',
             'M12 3c-2.6 2.4-4 5.6-4 9s1.4 6.6 4 9c2.6-2.4 4-5.6 4-9s-1.4-6.6-4-9'],
  archive:  ['M3 7.5h18v3H3z', 'M4.5 10.5V19a1.5 1.5 0 0 0 1.5 1.5h12a1.5 1.5 0 0 0 1.5-1.5v-8.5',
             'M10 14h4'],
  play:     ['M8 5.5v13l11-6.5z'],
  eye:      ['M2 12s3.6-6.5 10-6.5S22 12 22 12s-3.6 6.5-10 6.5S2 12 2 12',
             'M12 14.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5'],
  trash:    ['M4 7h16', 'M10 11v6M14 11v6',
             'M6 7l1 12.5A1.5 1.5 0 0 0 8.5 21h7a1.5 1.5 0 0 0 1.5-1.5L18 7',
             'M9.5 7V5a1.5 1.5 0 0 1 1.5-1.5h2A1.5 1.5 0 0 1 14.5 5v2'],
  user:     ['M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8',
             'M4.5 20a7.5 7.5 0 0 1 15 0'],
  gear:     ['M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6',
             'M19.2 14.4a1.7 1.7 0 0 0 .3 1.9 2 2 0 1 1-2.8 2.8 1.7 1.7 0 0 0-2.9 1.2 2 2 0 0 1-4 0 1.7 1.7 0 0 0-2.9-1.2 2 2 0 1 1-2.8-2.8 1.7 1.7 0 0 0-1.2-2.9 2 2 0 0 1 0-4 1.7 1.7 0 0 0 1.2-2.9 2 2 0 1 1 2.8-2.8 1.7 1.7 0 0 0 2.9-1.2 2 2 0 0 1 4 0 1.7 1.7 0 0 0 2.9 1.2 2 2 0 1 1 2.8 2.8 1.7 1.7 0 0 0 1.2 2.9 2 2 0 0 1 0 4 1.7 1.7 0 0 0-1.5 1.1z'],
  sun:      ['M12 8.2a3.8 3.8 0 1 0 0 7.6 3.8 3.8 0 0 0 0-7.6',
             'M12 2.5v2M12 19.5v2M2.5 12h2M19.5 12h2M5.2 5.2l1.4 1.4M17.4 17.4l1.4 1.4M18.8 5.2l-1.4 1.4M6.6 17.4l-1.4 1.4'],
  moon:     ['M20.8 13.4A8.6 8.6 0 1 1 10.6 3.2a6.9 6.9 0 0 0 10.2 10.2z'],
  power:    ['M12 3.2v8.4', 'M6.9 6.6a7.6 7.6 0 1 0 10.2 0'],
  lock:     ['M5.5 11h13a1 1 0 0 1 1 1v7.5a1 1 0 0 1-1 1h-13a1 1 0 0 1-1-1V12a1 1 0 0 1 1-1z',
             'M8 11V7.4a4 4 0 0 1 8 0V11'],
  envelope: ['M4 5.5h16a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-11a1 1 0 0 1 1-1z',
             'M3.4 6.6L12 13.4l8.6-6.8'],
  door:     ['M13.5 3.5H6a1 1 0 0 0-1 1v15a1 1 0 0 0 1 1h7.5',
             'M10.5 12H21', 'M17.8 8.8L21 12l-3.2 3.2'],
  download: ['M12 3.5v12', 'M7.5 11l4.5 4.5 4.5-4.5', 'M4.5 20h15'],
  upload:   ['M12 20.5v-12', 'M7.5 13l4.5-4.5 4.5 4.5', 'M4.5 4h15'],
  transfer: ['M6.5 3.5v11', 'M3.5 11l3 3.5 3-3.5',
             'M17.5 20.5v-11', 'M14.5 13l3-3.5 3 3.5'],
  search:   ['M11 4.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13', 'M15.8 15.8L20.5 20.5'],
  dots:     ['M12 5.6h.01', 'M12 12h.01', 'M12 18.4h.01'],
  checkbox: ['M5.5 4h13a1.5 1.5 0 0 1 1.5 1.5v13a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 4 18.5v-13A1.5 1.5 0 0 1 5.5 4z'],
  home:     ['M4 11.2L12 4.5l8 6.7', 'M6.2 9.8V19a1 1 0 0 0 1 1h9.6a1 1 0 0 0 1-1V9.8'],
  'folder-plus': ['M3.5 6.6a1 1 0 0 1 1-1h4.2l2 2.4h7.8a1 1 0 0 1 1 1v9.4a1 1 0 0 1-1 1h-14a1 1 0 0 1-1-1z',
                  'M12 11.4v5', 'M9.5 13.9h5'],
  plus:     ['M12 5v14', 'M5 12h14'],
  clip:     ['M20.5 11.8l-8.4 8.4a5.4 5.4 0 0 1-7.6-7.6l8.8-8.8a3.6 3.6 0 0 1 5.1 5.1l-8.8 8.8a1.8 1.8 0 0 1-2.5-2.5l8.1-8.1'],
  pencil:   ['M4 20h4l10.5-10.5a2.1 2.1 0 0 0-3-3L5 17v3',
             'M14.5 6.5l3 3'],
  check:    ['M4.5 12.5l5 5 10-11'],
  chevron:  ['M6 9.5l6 6 6-6'],
  close:    ['M6 6l12 12M18 6L6 18'],
  chat:     ['M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z'],
  folder:   ['M3.5 6.6a1 1 0 0 1 1-1h4.2l2 2.4h7.8a1 1 0 0 1 1 1v9.4a1 1 0 0 1-1 1h-14a1 1 0 0 1-1-1z'],
  'bell-off': ['M18 9a6 6 0 0 0-12 0c0 6-2.5 7.5-2.5 7.5h17S18 15 18 9',
               'M10.3 20a2 2 0 0 0 3.4 0',
               'M4 4l16 16'],
  server:   ['M4 6.5a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-2z',
             'M4 15.5a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-2z',
             'M8 7.5h.01', 'M8 16.5h.01'],
  cast:     ['M2 16.1A5 5 0 0 1 6.9 21', 'M2 12.05A9 9 0 0 1 12.95 21',
             'M2 8V6a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-6',
             'M2 21h.01'],
};

// The M of the wordmark is a picture; the rest is text. Resolved from this
// module's own URL so the hub's fingerprinted path and the application's
// app:// scheme both come out right without either being named here.
const BRAND_M = new URL('./meshbay-m.png', import.meta.url).href;

function Icon({ name, cls = '' }) {
  const paths = ICON_PATHS[name];
  if (!paths) return null;
  return html`
    <svg class="icon ${cls}" viewBox="0 0 24 24" aria-hidden="true" focusable="false"
         fill="none" stroke="currentColor" stroke-width="1.6"
         stroke-linecap="round" stroke-linejoin="round">
      ${paths.map((d, i) => html`<path key=${i} d=${d} />`)}
    </svg>
  `;
}

// ── User Menu ────────────────────────────────────────────────────────────────

function UserMenu({ user, theme, onThemeChange, onLogout }) {
  const [open, setOpen] = useState(false);
  const [langOpen, setLangOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    if (!open) return;
    const close = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, [open]);

  const resolved = resolveTheme(theme);

  return html`
    <div class="user-menu-wrap" ref=${ref}>
      <button class="user-menu-trigger" onClick=${() => setOpen(o => !o)}>
        <span class="user-menu-avatar">${user.username[0].toUpperCase()}</span>
        <span class="user-menu-name">${user.username}</span>
        <${Icon} name="chevron" cls="user-menu-caret ${open ? 'flip' : ''}" />
      </button>
      ${open && html`
        <div class="user-menu-dropdown">
          <div class="user-menu-header">
            <span class="user-menu-avatar lg">${user.username[0].toUpperCase()}</span>
            <div>
              <div class="user-menu-uname">${user.username}</div>
              <div class="user-menu-role">${user.role || 'user'}</div>
            </div>
          </div>
          <div class="user-menu-divider"></div>
          <button class="user-menu-item" onClick=${(e) => { e.stopPropagation(); setLangOpen(o => !o); }}>
            <${Icon} name="globe" cls="umi-icon" /> ${t('usermenu.language')}
            <${Icon} name="chevron" cls="umi-arrow ${langOpen ? 'flip' : ''}" />
          </button>
          ${langOpen && LOCALES.map(l => html`
            <button key=${l.code} class="user-menu-item user-menu-sub"
              onClick=${() => { setLocale(l.code); window.location.reload(); }}>
              <span class="umi-icon">${l.flag}</span> ${l.name}
              ${getLocale() === l.code
                && html`<${Icon} name="check" cls="umi-check" />`}
            </button>
          `)}
          <button class="user-menu-item" onClick=${() => { setOpen(false); navigate('/profile'); }}>
            <${Icon} name="user" cls="umi-icon" /> ${t('usermenu.profile')}
          </button>
          <button class="user-menu-item" onClick=${() => { setOpen(false); navigate('/settings'); }}>
            <${Icon} name="gear" cls="umi-icon" /> ${t('usermenu.settings')}
          </button>
          <button class="user-menu-item" onClick=${() => {
            onThemeChange(resolved === 'dark' ? 'light' : 'dark');
            setOpen(false);
          }}>
            <${Icon} name=${resolved === 'dark' ? 'sun' : 'moon'} cls="umi-icon" />
            ${' '}${resolved === 'dark' ? t('usermenu.theme_light') : t('usermenu.theme_dark')}
          </button>
          <div class="user-menu-divider"></div>
          <button class="user-menu-item user-menu-logout" onClick=${onLogout}>
            <${Icon} name="power" cls="umi-icon" /> ${t('usermenu.logout')}
          </button>
        </div>
      `}
    </div>
  `;
}

// ── Transfers widget ─────────────────────────────────────────────────────────

function TransferWidget() {
  const [items, setItems] = useState(() => transfers.list());
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => transfers.subscribe(setItems), []);

  useEffect(() => {
    if (!open) return;
    const close = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, [open]);

  const running = items.filter(i => i.status === 'running');
  if (!items.length) return null;

  return html`
    <div class="transfer-wrap" ref=${ref}>
      <button class="nav-notif transfer-btn ${running.length ? 'active' : ''}"
        title=${t('transfers.title')}
        onClick=${(e) => { e.stopPropagation(); setOpen(o => !o); }}>
        <${Icon} name="transfer" />
        ${running.length > 0 && html`
          <span class="notif-badge">${running.length}</span>
        `}
      </button>
      ${open && html`
        <div class="transfer-panel">
          <div class="transfer-head">
            ${t('transfers.title')}
            <button class="btn-secondary"
              onClick=${() => transfers.clearFinished()}>
              ${t('transfers.clear')}
            </button>
          </div>
          ${items.map(it => html`
            <div class="transfer-item" key=${it.id}>
              <div class="transfer-line">
                <span class="transfer-kind">
                  <${Icon} name=${it.kind === 'upload' ? 'upload' : 'download'} />
                </span>
                ${it.canOpen
                  ? html`<a class="transfer-name" href="#" title=${it.name}
                      onClick=${(e) => { e.preventDefault(); transfers.open(it.id); }}>${it.name}</a>`
                  : html`<span class="transfer-name" title=${it.name}>${it.name}</span>`}
                ${it.status === 'running' && html`
                  <button class="transfer-cancel" title=${t('transfers.cancel')}
                    onClick=${() => transfers.cancel(it.id)}>
                    <${Icon} name="close" />
                  </button>
                `}
              </div>
              ${it.status === 'running'
                ? html`
                  <div class="dl-progress">
                    <div class="dl-fill" style="width:${it.percent}%"></div>
                  </div>
                  <div class="transfer-meta">
                    <span>${formatSize(it.done)}${it.total
                      ? ' / ' + formatSize(it.total) : ''}</span>
                    <span>${formatSpeed(it.speed)}</span>
                  </div>
                `
                : html`
                  <div class="transfer-meta">
                    <span class=${it.status === 'failed' ? 'transfer-failed' : ''}>
                      ${it.status === 'done' ? t('transfers.done')
                        : it.status === 'cancelled' ? t('transfers.cancelled')
                        : it.error || t('transfers.failed')}
                    </span>
                    ${it.canOpen && html`
                      <button class="link-btn" onClick=${() => transfers.open(it.id)}>
                        ${t('transfers.open')}
                      </button>
                    `}
                  </div>
                `}
            </div>
          `)}
        </div>
      `}
    </div>
  `;
}

// ── Nav ──────────────────────────────────────────────────────────────────────

function Nav({ user, theme, onThemeChange, onLogout, onMenuToggle, unreadCount,
              hubUnset }) {
  return html`
    <nav class="nav">
      <div class="nav-left">
        ${user && html`
          <button class="nav-hamburger" onClick=${onMenuToggle}
            aria-label="${t('nav.toggle_menu')}"><${Icon} name="menu" /></button>
        `}
        <a class="nav-brand" href="#/">
          <img class="nav-brand-m" src=${BRAND_M} alt="M" />eshBay
        </a>
      </div>
      <div class="nav-right">
        ${user && html`<${TransferWidget} />`}
        ${user && html`
          <a class="nav-notif" href="#/" title=${t('notif.title')}>
            <${Icon} name="bell" />${unreadCount > 0
              && html`<span class="notif-badge">${unreadCount}</span>`}
          </a>
        `}
        ${user ? html`
          <${UserMenu} user=${user} theme=${theme}
            onThemeChange=${onThemeChange} onLogout=${onLogout} />
        ` : hubUnset ? null : html`
          <a class="nav-btn" href="#/login">${t('nav.login')}</a>
        `}
      </div>
    </nav>
  `;
}

// ── Sidebar ──────────────────────────────────────────────────────────────────

function Sidebar({ groups, presence, route, menuOpen, role, hasNodeKey }) {
  const isStaff = role === 'moderator' || role === 'admin';
  return html`
    <aside class="sidebar ${menuOpen ? 'open' : ''}">
      ${isStaff && html`
        <div class="sidebar-section">
          <div class="sidebar-heading">${t('sidebar.admin')}</div>
          <a class="sidebar-item ${route === '/admin' ? 'active' : ''}"
             href="#/admin"><${Icon} name="shield" /> ${t('admin.title')}</a>
        </div>
      `}
      <div class="sidebar-section">
        <div class="sidebar-heading">${t('sidebar.discover')}</div>
        <a class="sidebar-item ${route === '/explore' ? 'active' : ''}"
           href="#/explore"><${Icon} name="globe" /> ${t('sidebar.public_groups')}</a>
        <a class="sidebar-item ${route === '/search' ? 'active' : ''}"
           href="#/search"><${Icon} name="search" /> ${t('sidebar.search')}</a>
      </div>
      ${platform.capabilities.nodeAdmin && hasNodeKey && html`
        <div class="sidebar-section">
          <div class="sidebar-heading">${t('sidebar.node')}</div>
          <a class="sidebar-item ${route === '/node' ? 'active' : ''}"
             href="#/node"><${Icon} name="server" /> ${t('node.title')}</a>
          <a class="sidebar-item ${route === '/create-group' ? 'active' : ''}"
             href="#/create-group"><${Icon} name="plus" /> ${t('sidebar.create_group')}</a>
        </div>
      `}
      <div class="sidebar-section">
        <div class="sidebar-heading">${t('sidebar.my_groups')}</div>
        ${groups.length === 0
          ? html`<div class="sidebar-empty">${t('sidebar.no_groups')}</div>`
          : [...groups].sort((a, b) =>
              (b.last_activity_at || b.created_at || '').localeCompare(
               a.last_activity_at || a.created_at || '')).map(g => {
            // Three states, each backed by something. `node_online` comes from
            // the hub's signaling registry and rides on the group list itself,
            // so there is no poll and no timer; a connection this browser tried
            // and failed overrides it, because that is the fact the reader
            // actually cares about. Anything else is "not known yet".
            const state = presence[g.id] ?? (g.node_online === true ? 'online'
              : g.node_online === false ? 'offline' : 'unknown');
            return html`
              <a key=${g.id}
                 class="sidebar-item ${route === '/group/' + g.id ? 'active' : ''}"
                 href="#/group/${g.id}">
                <span class="presence presence-${state}"
                      title="${t('presence.' + state)}"
                      aria-label="${t('presence.' + state)}"></span>
                <span class="sidebar-item-name">${g.name}</span>
              </a>
            `;
          })
        }
      </div>
    </aside>
  `;
}

// ── Login Page ───────────────────────────────────────────────────────────────

/**
 * Which hub, asked once on a desktop build.
 *
 * There is no default. A client that picks its own hub is a client that can be
 * pointed at one, and the address is the whole of what the application trusts
 * the hub for — its API, and nothing else: the interface comes from the package.
 *
 * Changing it restarts the window, because the address reaches the interface as
 * a process argument. Reloading in place would leave it talking to the old hub
 * with nothing on screen to say so.
 */
function FirstRunPage({ onSet }) {
  const [url, setUrl] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setBusy(true);
    try {
      await window.meshbay.setHubBase(url.trim());
      onSet();
    } catch (err) {
      setError(platform.bridgeMessage(err));
      setBusy(false);
    }
  };

  return html`
    <div class="page-center">
      <div class="card login-card">
        <h2>${t('firstrun.title')}</h2>
        <p class="settings-hint" style="margin-bottom:16px">${t('firstrun.hint')}</p>
        <form onSubmit=${submit}>
          <input type="text" placeholder="https://meshbay.org" required
            autofocus value=${url}
            onInput=${e => setUrl(e.target.value)} />
          <button type="submit" disabled=${busy}>
            ${busy ? t('firstrun.checking') : t('firstrun.btn')}
          </button>
        </form>
        ${error && html`<div class="error-msg">${error}</div>`}
        <p class="settings-hint" style="margin-top:16px">${t('firstrun.note')}</p>
      </div>
    </div>
  `;
}

function LoginPage() {
  const auth = useAuth();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!username || !password) return;
    setError('');
    setLoading(true);
    try {
      await auth.login(username, password);
      navigate('/');
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return html`
    <div class="page-center">
      <div class="card login-card">
        <h2>${t('login.title')}</h2>
        <form onSubmit=${onSubmit}>
          <input type="text" placeholder="${t('login.username')}" value=${username}
                 onInput=${e => setUsername(e.target.value)}
                 autocomplete="username" required autofocus />
          <input type="password" placeholder="${t('login.password')}" value=${password}
                 onInput=${e => setPassword(e.target.value)}
                 autocomplete="current-password" required />
          ${error && html`<div class="error-msg">${error}</div>`}
          <button type="submit" disabled=${loading}>
            ${loading ? t('login.loading') : t('login.submit')}
          </button>
        </form>
        <div class="login-footer">
          ${t('login.no_account')} <a href="#/register">${t('login.register_link')}</a>
        </div>
      </div>
    </div>
  `;
}

// ── Register Page ────────────────────────────────────────────────────────────

function RegisterPage() {
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [loading, setLoading] = useState(false);

  const onSubmit = async (e) => {
    e.preventDefault();
    if (password !== confirm) { setError(t('register.err_mismatch')); return; }
    if (password.length < PASSWORD_MIN_LEN) {
      setError(t('register.err_min_len', { n: PASSWORD_MIN_LEN })); return;
    }
    // The floor can only live here: with the password split (T1) the hub never
    // sees the password, so it cannot enforce anything about it.
    if (passwordBits(password) < PASSWORD_MIN_BITS) {
      setError(t('register.err_too_weak')); return;
    }
    setError('');
    setLoading(true);
    try {
      if (window.MeshBayKeys) {
        await window.MeshBayKeys.registerUser(username, email, password);
      } else {
        await hubFetch('/v1/users/register', {
          method: 'POST',
          body: { username, email, password, pk_user_ed25519: '', pk_user_x25519: '' },
        });
      }
      setSuccess(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  if (success) {
    return html`
      <div class="page-center">
        <div class="card login-card">
          <h2>${t('register.success_title')}</h2>
          <p style="text-align:center; margin-bottom:16px; color:var(--text-secondary)">
            ${t('register.success_msg')}
          </p>
          <a href="#/login" style="display:block; text-align:center">${t('register.go_login')}</a>
        </div>
      </div>
    `;
  }

  return html`
    <div class="page-center">
      <div class="card login-card">
        <h2>${t('register.title')}</h2>
        <form onSubmit=${onSubmit}>
          <input type="text" placeholder="${t('register.username')}" value=${username}
                 onInput=${e => setUsername(e.target.value)}
                 autocomplete="username" required />
          <input type="email" placeholder="${t('register.email')}" value=${email}
                 onInput=${e => setEmail(e.target.value)}
                 autocomplete="email" required />
          <input type="password" placeholder="${t('register.password')}" value=${password}
                 onInput=${e => setPassword(e.target.value)}
                 autocomplete="new-password" required minlength="8" />
          ${password && html`
            <div style="margin:-4px 0 10px">
              <div style="height:4px;background:var(--border);border-radius:2px;overflow:hidden">
                <div style=${`height:100%;width:${Math.min(100, passwordBits(password) / 100 * 100)}%;
                     background:${passwordBits(password) < PASSWORD_MIN_BITS ? 'var(--error)'
                       : passwordBits(password) < 80 ? 'var(--yellow, #f59e0b)' : 'var(--success)'}`}></div>
              </div>
              <p style="font-size:0.8em;color:var(--text-dim);margin-top:4px">
                ${t('register.strength', { bits: passwordBits(password) })}
              </p>
            </div>
          `}
          <input type="password" placeholder="${t('register.confirm')}" value=${confirm}
                 onInput=${e => setConfirm(e.target.value)}
                 autocomplete="new-password" required />
          ${error && html`<div class="error-msg">${error}</div>`}
          <button type="submit" disabled=${loading}>
            ${loading ? t('register.loading') : t('register.submit')}
          </button>
        </form>
        <div class="login-footer">
          ${t('register.has_account')} <a href="#/login">${t('register.login_link')}</a>
        </div>
      </div>
    </div>
  `;
}

// ── Home Page ────────────────────────────────────────────────────────────────

function NotificationFeed({ notifications, onMarkRead, onPurge }) {
  if (!notifications.length) return null;
  return html`
    <div class="notif-feed">
      <h3>
        ${t('notif.title')}
        <button class="btn-secondary notif-purge" onClick=${onPurge}>
          ${t('notif.purge')}
        </button>
      </h3>
      ${notifications.map(n => html`
        <div key=${n.id} class="notif-item ${n.read ? '' : 'notif-unread'}"
          onClick=${() => {
            // Reading it is the point of clicking it: it goes, here and in the
            // count, rather than sitting there greyed out.
            onMarkRead(n.id);
            if (n.link) navigate(n.link);
          }}>
          <span class="notif-kind">${n.kind}</span>
          <span class="notif-text">${n.title}</span>
          <span class="notif-time">${new Date(n.created_at).toLocaleDateString()}</span>
        </div>
      `)}
    </div>
  `;
}

function HomePage({ groups, notifications, onMarkRead, onPurge }) {
  const [setupDismissed, setSetupDismissed] = useState(false);

  if (groups.length === 0) {
    if (platform.isNative && !setupDismissed) {
      return html`<${SetupWelcome}
        onDismiss=${() => setSetupDismissed(true)} />`;
    }
    return html`
      <div>
        <h2>${t('home.welcome')}</h2>
        <${NotificationFeed} notifications=${notifications}
          onMarkRead=${onMarkRead} onPurge=${onPurge} />
        <p class="page-message">
          ${t('home.no_groups')}
          ${' '}${t('home.browse_prefix')}<a href="#/explore">${t('home.browse_link')}</a>${t('home.browse_suffix')}
        </p>
      </div>
    `;
  }

  return html`
    <div>
      <h2>${t('home.my_groups')}</h2>
      <${NotificationFeed} notifications=${notifications}
        onMarkRead=${onMarkRead} onPurge=${onPurge} />
      <div class="group-grid">
        ${groups.map(g => html`
          <a key=${g.id} class="group-card" href="#/group/${g.id}">
            <h3>${g.name}</h3>
            ${g.description && html`<p class="group-card-desc">${g.description}</p>`}
            <span class="badge">${g.visibility}</span>
            ${' '}
            <span class="badge">${g.join_policy}</span>
            ${g.is_admin && html`${' '}<span class="badge">admin</span>`}
          </a>
        `)}
      </div>
    </div>
  `;
}

// ── Explore Page ─────────────────────────────────────────────────────────────

function ExplorePage({ token, myGroupIds }) {
  const [groups, setGroups] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [joining, setJoining] = useState(null);

  const doSearch = useCallback((q) => {
    setLoading(true);
    const url = q ? `/v1/groups?q=${encodeURIComponent(q)}` : '/v1/groups';
    hubFetch(url, { token })
      .then(data => setGroups(data.groups || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [token]);

  useEffect(() => { doSearch(''); }, [token]);

  const onSearch = useCallback((e) => {
    const q = e.target.value;
    setSearch(q);
    doSearch(q);
  }, [doSearch]);

  const joinGroup = useCallback(async (gid) => {
    setJoining(gid);
    try {
      await hubFetch(`/v1/groups/${gid}/join`, { method: 'POST', token });
      navigate(`/group/${gid}`);
      setTimeout(() => window.location.reload(), 100);
    } catch (err) {
      if (err.message.includes('Already a member')) {
        navigate(`/group/${gid}`);
      } else {
        alert(err.message);
      }
    } finally {
      setJoining(null);
    }
  }, [token]);

  const isMember = (gid) => myGroupIds && myGroupIds.includes(gid);

  return html`
    <div>
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px">
        <h2 style="margin:0">${t('explore.title')}</h2>
        ${platform.node.available && html`
          <a class="admin-btn" href="#/create-group">${t('explore.create_group')}</a>
        `}
      </div>
      <div class="file-toolbar" style="margin-bottom:16px">
        <input type="text" class="admin-search" placeholder="${t('explore.search')}"
          value=${search} onInput=${onSearch} />
      </div>
      ${loading
        ? html`<p class="page-message">${t('explore.loading')}</p>`
        : groups.length === 0
          ? html`<p class="page-message">${t('explore.empty')}</p>`
          : html`
            <div class="group-grid">
              ${groups.map(g => html`
                <div key=${g.id} class="group-card">
                  <a href="#/group/${g.id}" style="text-decoration:none;color:inherit">
                    <h3>${g.name}</h3>
                    ${g.description && html`<p class="group-card-desc">${g.description}</p>`}
                  </a>
                  <span class="badge">${g.join_policy}</span>
                  ${g.source && g.source !== 'local' && html`
                    ${' '}<span class="badge">${g.source}</span>
                  `}
                  ${' '}
                  ${isMember(g.id)
                    ? html`<span class="badge">${t('explore.member')}</span>`
                    : g.join_policy === 'open' && html`
                      <button class="admin-btn" style="margin-top:8px"
                        disabled=${joining === g.id}
                        onClick=${() => joinGroup(g.id)}>
                        ${joining === g.id ? '...' : t('explore.join')}
                      </button>
                    `
                  }
                </div>
              `)}
            </div>
          `
      }
    </div>
  `;
}

// ── First-run welcome (Electron-only, shown once on empty home) ─────────────

function SetupWelcome({ onDismiss }) {
  return html`<div class="page-content">
    <h2>${t('setup.welcome_title')}</h2>
    <p class="page-message" style="margin-bottom:24px">
      ${t('setup.welcome_message')}</p>
    <div style="display:flex;gap:8px;flex-wrap:wrap">
      <a class="btn btn-primary" href="#/create-group">
        ${t('setup.create_group')}</a>
      <button class="btn btn-secondary" onClick=${onDismiss}>
        ${t('setup.dismiss')}</button>
    </div>
  </div>`;
}

// ── Create Group Page ────────────────────────────────────────────────────────

function CreateGroupPage(props) {
  if (platform.node.available) return html`<${CreateGroupWizard} ...${props} />`;
  return html`<${CreateGroupFormSimple} ...${props} />`;
}

function CreateGroupFormSimple({ token, onCreated }) {
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [joinPolicy, setJoinPolicy] = useState('invite');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!name.trim()) return;
    setLoading(true);
    setError('');
    try {
      const body = { name: name.trim(), join_policy: joinPolicy,
                     visibility: joinPolicy === 'open' ? 'public' : 'private' };
      if (description.trim()) body.description = description.trim().slice(0, 512);
      const data = await hubFetch('/v1/groups', {
        method: 'POST', token, body,
      });

      if (onCreated) onCreated();
      navigate('/');
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return html`
    <div>
      <h2>${t('create_group.title')}</h2>
      <p class="page-message">${t('create_group.hint')}</p>
      ${error && html`<div class="error-msg" style="margin-bottom:16px">${error}</div>`}

      <form onSubmit=${onSubmit}>
        <div class="settings-section">
          <div class="form-field">
            <label class="form-label">${t('create_group.name')}</label>
            <input type="text" placeholder="${t('create_group.name_placeholder')}"
              value=${name} onInput=${e => setName(e.target.value)} required autofocus />
          </div>

          <div class="form-field" style="margin-bottom:0">
            <label class="form-label">${t('create_group.description')}</label>
            <textarea class="form-textarea" rows="3" maxlength="512"
              placeholder="${t('create_group.description_hint')}"
              value=${description}
              onInput=${e => setDescription(e.target.value)} />
            <div class="form-char-count">${description.length}/512</div>
          </div>
        </div>

        <div class="settings-section">
          <h3 class="settings-heading">${t('create_group.join_policy')}</h3>
          <div class="choice-list">
            <label class="choice ${joinPolicy === 'invite' ? 'selected' : ''}">
              <input type="radio" name="join_policy" checked=${joinPolicy === 'invite'}
                onChange=${() => setJoinPolicy('invite')} />
              <${Icon} name="lock" cls="choice-icon" />
              <span class="choice-text">
                <span class="choice-title">${t('create_group.invite')}</span>
                <span class="choice-desc">${t('create_group.invite_desc')}</span>
              </span>
            </label>
            <label class="choice ${joinPolicy === 'open' ? 'selected' : ''}">
              <input type="radio" name="join_policy" checked=${joinPolicy === 'open'}
                onChange=${() => setJoinPolicy('open')} />
              <${Icon} name="globe" cls="choice-icon" />
              <span class="choice-text">
                <span class="choice-title">${t('create_group.open')}</span>
                <span class="choice-desc">${t('create_group.open_desc')}</span>
              </span>
            </label>
          </div>
        </div>

        <button class="btn-primary" type="submit" disabled=${loading}>
          ${loading ? t('create_group.creating') : t('create_group.submit')}
        </button>
      </form>
    </div>
  `;
}

// ── Create Group Wizard (Electron-only) ─────────────────────────────────────

function CreateGroupWizard({ token, onCreated }) {
  const [step, setStep] = useState(0);  // 0=node check, 1=details, 2=setup, 3=done
  const [nodeStatus, setNodeStatus] = useState(null);  // null=loading, object=result
  const [nodeStarting, setNodeStarting] = useState(false);
  const [error, setError] = useState('');

  // Step 1 fields
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [joinPolicy, setJoinPolicy] = useState('invite');
  const [roots, setRoots] = useState([]);
  const [uploadIdx, setUploadIdx] = useState(0);

  // Step 2 progress
  const [setupSteps, setSetupSteps] = useState([]);
  const [setupError, setSetupError] = useState('');
  const [groupId, setGroupId] = useState('');

  const linkNodeKey = useCallback(async (pk) => {
    if (!pk) return;
    try {
      await hubFetch('/v1/users/me/node_key', {
        method: 'PUT', token, body: { pk_node_ed25519: pk },
      });
    } catch { /* already linked or same key */ }
  }, [token]);

  // Step 0: detect node
  const detectNode = useCallback(async () => {
    setNodeStatus(null);
    setError('');
    try {
      const result = await platform.node.detect();
      if (result.detected) {
        await linkNodeKey(result.pk_node_ed25519);
        setNodeStatus(result);
        setStep(1);
        return;
      }
      // Not responding — check if the unit is installed (for the Start button)
      const inst = await platform.node.installed();
      setNodeStatus({ detected: false, configured: result.configured, installed: inst.installed });
    } catch (err) {
      setError(err.message);
      setNodeStatus({ detected: false });
    }
  }, [token, linkNodeKey]);

  const startNode = useCallback(async () => {
    setNodeStarting(true);
    setError('');
    try {
      const result = await platform.node.start();
      await linkNodeKey(result.pk_node_ed25519);
      setNodeStatus({ detected: true, ...result });
      setNodeStarting(false);
      setStep(1);
    } catch (err) {
      setError(platform.bridgeMessage(err));
      setNodeStarting(false);
    }
  }, [linkNodeKey]);

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

  const addRoot = useCallback(async () => {
    const chosen = await platform.rootPicker.choose();
    if (!chosen) return;
    if (roots.some(r => r.path === chosen.path)) return;
    setRoots(prev => [...prev, chosen]);
  }, [roots]);

  const removeRoot = useCallback((idx) => {
    setRoots(prev => {
      const next = prev.filter((_, i) => i !== idx);
      if (uploadIdx >= next.length && next.length > 0) setUploadIdx(0);
      return next;
    });
  }, [uploadIdx]);

  const runSetup = useCallback(async () => {
    setStep(2);
    setSetupError('');
    const steps = [
      { label: t('wizard.step_create_hub'), status: 'pending' },
      { label: t('wizard.step_attach'), status: 'pending' },
    ];
    if (roots.length > 1)
      steps.push({ label: t('wizard.step_add_roots'), status: 'pending' });
    steps.push({ label: t('wizard.step_gek'), status: 'pending' });
    steps.push({ label: t('wizard.step_pair'), status: 'pending' });
    setSetupSteps([...steps]);

    let si = 0;
    const update = (status) => {
      steps[si].status = status;
      setSetupSteps([...steps]);
    };
    const advance = () => { si++; };

    try {
      // 1. Create group on hub
      update('running');
      const body = { name: name.trim(), join_policy: joinPolicy,
                     visibility: joinPolicy === 'open' ? 'public' : 'private' };
      if (description.trim()) body.description = description.trim().slice(0, 512);
      const data = await hubFetch('/v1/groups', { method: 'POST', token, body });
      const gid = data.group_id;
      setGroupId(gid);
      update('done');
      advance();

      // 2. Attach to node with first root
      update('running');
      const mainRoot = roots[uploadIdx] || roots[0];
      const attachBody = { name: name.trim(), shared_dir: mainRoot.path };
      if (roots.length === 1 || uploadIdx === 0) {
        attachBody.upload_dir = mainRoot.path;
      }
      await platform.node.call('POST', '/api/groups/attach', attachBody);
      await platform.node.call('POST', '/api/reload');
      update('done');
      advance();

      // 3. Add extra roots (if >1)
      if (roots.length > 1) {
        update('running');
        for (let i = 0; i < roots.length; i++) {
          if (i === (uploadIdx < roots.length ? uploadIdx : 0)) continue;
          const r = roots[i];
          await platform.node.call('POST', `/api/groups/${gid}/roots`, {
            path: r.path, name: r.name,
            upload: i === uploadIdx,
          });
        }
        update('done');
        advance();
      }

      // 4. GEK init
      update('running');
      await platform.node.call('POST', `/api/groups/${gid}/gek`);
      update('done');
      advance();

      // 5. Generate pairing code
      update('running');
      const pairResult = await platform.node.call('POST', '/api/operator/pair');
      if (pairResult && pairResult.code) {
        await platform.node.setPairingCode(pairResult.code);
      }
      update('done');

      // Reload node config so it picks up the new group
      try { await platform.node.call('POST', '/api/reload'); } catch { /* best effort */ }

      setStep(3);
      if (onCreated) onCreated();
    } catch (err) {
      update('error');
      setSetupError(platform.bridgeMessage(err));
    }
  }, [name, description, joinPolicy, roots, uploadIdx, token, onCreated]);

  // Step 0: Node detection
  if (step === 0) {
    if (nodeStatus === null) {
      return html`<div class="page-content">
        <h2>${t('wizard.title')}</h2>
        <p class="page-message">${t('wizard.detecting')}</p>
      </div>`;
    }
    if (!nodeStatus.detected) {
      const canStart = nodeStatus.installed || nodeStatus.configured;
      return html`<div class="page-content">
        <h2>${t('wizard.title')}</h2>
        <p class="page-message">${canStart
          ? t('setup.node_not_running')
          : t('setup.node_not_installed')}</p>
        ${!canStart && html`<p class="page-message" style="margin-top:8px">
          ${t('setup.node_install_hint')}</p>`}
        ${error && html`<div class="error-msg" style="margin-top:8px">${error}</div>`}
        <div style="display:flex;gap:8px;margin-top:16px;flex-wrap:wrap">
          ${canStart && html`
            <button class="btn btn-primary" disabled=${nodeStarting}
              onClick=${startNode}>
              ${nodeStarting ? t('setup.node_starting') : t('setup.node_start')}</button>`}
          <button class="btn btn-secondary" onClick=${detectNode}>
            ${t('wizard.retry')}</button>
        </div>
      </div>`;
    }
  }

  // Step 1: Group details + directories
  if (step === 1) {
    const canProceed = name.trim() && roots.length > 0;
    return html`<div class="page-content">
      <h2>${t('wizard.title')}</h2>
      ${error && html`<div class="error-msg" style="margin-bottom:16px">${error}</div>`}

      <div class="settings-section">
        <div class="form-field">
          <label class="form-label">${t('create_group.name')}</label>
          <input type="text" placeholder="${t('create_group.name_placeholder')}"
            value=${name} onInput=${e => setName(e.target.value)} required autofocus />
        </div>

        <div class="form-field">
          <label class="form-label">${t('create_group.description')}</label>
          <textarea class="form-textarea" rows="3" maxlength="512"
            placeholder="${t('create_group.description_hint')}"
            value=${description}
            onInput=${e => setDescription(e.target.value)} />
          <div class="form-char-count">${description.length}/512</div>
        </div>
      </div>

      <div class="settings-section">
        <h3 class="settings-heading">${t('create_group.join_policy')}</h3>
        <div class="choice-list">
          <label class="choice ${joinPolicy === 'invite' ? 'selected' : ''}">
            <input type="radio" name="join_policy" checked=${joinPolicy === 'invite'}
              onChange=${() => setJoinPolicy('invite')} />
            <${Icon} name="lock" cls="choice-icon" />
            <span class="choice-text">
              <span class="choice-title">${t('create_group.invite')}</span>
              <span class="choice-desc">${t('create_group.invite_desc')}</span>
            </span>
          </label>
          <label class="choice ${joinPolicy === 'open' ? 'selected' : ''}">
            <input type="radio" name="join_policy" checked=${joinPolicy === 'open'}
              onChange=${() => setJoinPolicy('open')} />
            <${Icon} name="globe" cls="choice-icon" />
            <span class="choice-text">
              <span class="choice-title">${t('create_group.open')}</span>
              <span class="choice-desc">${t('create_group.open_desc')}</span>
            </span>
          </label>
        </div>
      </div>

      <div class="settings-section">
        <h3 class="settings-heading">${t('wizard.directories')}</h3>
        <p style="font-size:0.85em;color:var(--text-dim);margin-bottom:8px">
          ${t('wizard.directories_hint')}</p>
        ${roots.map((r, i) => html`
          <div class="wizard-root" key=${r.path}>
            <div class="wizard-root-info">
              <${Icon} name="folder" />
              <span class="wizard-root-name">${r.name}</span>
              <span class="wizard-root-path">${r.path}</span>
              ${i === uploadIdx && html`
                <span class="node-root-badge">${t('wizard.upload_target')}</span>`}
            </div>
            <div class="wizard-root-actions">
              ${roots.length > 1 && i !== uploadIdx && html`
                <button class="btn btn-small btn-secondary"
                  onClick=${() => setUploadIdx(i)}>
                  ${t('wizard.set_upload')}</button>`}
              <button class="btn btn-small btn-danger"
                onClick=${() => removeRoot(i)}>
                ${t('wizard.remove')}</button>
            </div>
          </div>
        `)}
        <button class="btn btn-secondary" style="margin-top:8px"
          onClick=${addRoot}>
          <${Icon} name="folder-plus" /> ${t('wizard.add_directory')}
        </button>
      </div>

      <div style="display:flex;gap:8px;margin-top:16px">
        <button class="btn btn-primary" disabled=${!canProceed}
          onClick=${runSetup}>
          ${t('wizard.create_and_setup')}</button>
      </div>
    </div>`;
  }

  // Step 2: Automatic setup progress
  if (step === 2) {
    return html`<div class="page-content">
      <h2>${t('wizard.title')}</h2>
      <p class="page-message">${t('wizard.setting_up')}</p>
      <div class="wizard-progress">
        ${setupSteps.map((s, i) => html`
          <div class="wizard-step wizard-step-${s.status}" key=${i}>
            <span class="wizard-step-icon">
              ${s.status === 'done' ? '✓' :
                s.status === 'running' ? '●' :
                s.status === 'error' ? '✗' : '○'}
            </span>
            <span>${s.label}</span>
          </div>
        `)}
      </div>
      ${setupError && html`
        <div class="error-msg" style="margin-top:16px">${setupError}</div>
        <div style="display:flex;gap:8px;margin-top:8px">
          <button class="btn btn-primary" onClick=${runSetup}>
            ${t('wizard.retry')}</button>
          <button class="btn btn-secondary" onClick=${() => {
            if (onCreated) onCreated();
            navigate('/');
          }}>
            ${t('wizard.finish_later')}</button>
        </div>
      `}
    </div>`;
  }

  // Step 3: Done
  return html`<div class="page-content">
    <h2>${t('wizard.done_title')}</h2>
    <p class="page-message">${t('wizard.done_message')}</p>
    <button class="btn btn-primary" style="margin-top:16px"
      onClick=${() => navigate(`/groups/${groupId}`)}>
      ${t('wizard.go_to_group')}</button>
  </div>`;
}

// ── Helpers ──────────────────────────────────────────────────────────────────

const FILE_ICONS = {
  video: '\u{1F3AC}', audio: '\u{1F3B5}', image: '\u{1F5BC}',
  document: '\u{1F4C4}', archive: '\u{1F4E6}', other: '\u{1F4CE}',
};

function formatSize(bytes) {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
  if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
  return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
}

function formatDate(ts) {
  return new Date(ts * 1000).toLocaleDateString(undefined, {
    year: 'numeric', month: 'short', day: 'numeric',
  });
}

// ── Group Page ──────────────────────────────────────────────────────────────

const PREVIEWABLE_TEXT =
  /\.(txt|md|json|csv|log|xml|yaml|yml|ini|conf|py|js|html|css|sh|c|h|java|rs|go|rb|toml)$/i;

function canPreview(e) {
  return ['image', 'video', 'document'].includes(e.type)
    || PREVIEWABLE_TEXT.test(e.name);
}

const CHUNK_SIZE = 1024 * 1024;
// Seconds of already-watched video kept in the SourceBuffer, and the queue depth
// past which we start making room before being forced to.
const BUFFER_BEHIND_S = 60;
// How far past the playhead we are willing to pull. The browser caps a video
// SourceBuffer at a few hundred megabytes and refuses the append that goes
// past, so "as fast as the network allows" is not a strategy for a film: the
// node remuxes with `-c copy`, so a 500 MB file puts 500 MB on the wire, and a
// ten-megabit second fills the ceiling in the first minute. Buffering by time
// rather than by bytes keeps a two-hour film and a two-minute clip alike.
const BUFFER_AHEAD_S = 90;
// While we deliberately hold credit back, the node must still hear from us: its
// own stall timeout is two minutes, and a paused film is not a gone viewer.
const CREDIT_KEEPALIVE_MS = 20000;
// Segments allowed in flight while there is room to put them. This is a window,
// topped up as segments land, and not a debt released in one go: accumulating a
// credit per append and handing the lot over when the buffer finally had room
// sent 6 MB in a burst, overshot the target by a minute of film, and then said
// nothing for the next forty-six seconds. Measured in Chrome against real
// fragmented MP4. A stream that arrives in gulps has no margin for a network
// that hesitates, and looks like a hang while it is quiet.
const STREAM_WINDOW = 8;
// Dragging the scrubber fires `seeking` continuously, and every seek we act on
// kills an ffmpeg and spawns another. Only where the finger stops is worth a
// restart.
const SEEK_DEBOUNCE_MS = 350;
// A position is remembered per file, in this browser. Below the first threshold
// there is nothing to resume; above the second the film is finished and
// offering to resume thirty seconds before the credits is a nuisance.
const RESUME_MIN_S = 30;
const RESUME_MAX_FRACTION = 0.97;
const QUEUE_HIGH_WATER = 12;
const PIPELINE_WINDOW = 8;

/**
 * Open somewhere to write, honouring the user's download setting.
 *
 * Returns a target ({writable, name}), null for "no stream available — collect
 * it and hand the browser a blob", or false for "the person dismissed the
 * dialog", which is not an error and must not start a transfer.
 */
async function _openDownloadTarget(filename, size = 0, pickerOpts = {},
                                   swSize = size) {
  // On a desktop build this is the whole answer, and it comes first.
  //
  // The two browser paths below are both unavailable there — `showDirectoryPicker`
  // does not exist, and Chromium refuses a service worker on a custom scheme —
  // so without this the chain fell all the way through to its floor, which
  // collects the file in the page and hands the browser a blob. A gigabyte of
  // film meant a gigabyte of RAM, and a Save As dialog at the *end*.
  if (platform.capabilities.nativeSave) {
    try {
      const native = await platform.nativeSave(
        filename, { auto: downloads.getMode() === 'auto' });
      // Null means the person dismissed the dialog, which is not an error and
      // must not start a transfer.
      return native || false;
    } catch (err) {
      console.warn('[MeshBay] native save failed:', platform.bridgeMessage(err));
      return false;
    }
  }

  try {
    const target = await downloads.openTarget(filename);
    if (target) return target;
  } catch (err) {
    console.warn('[MeshBay] download folder unusable:', err.message);
  }

  // No granted folder. A service worker can still hand the browser a stream to
  // write, which is how this works at all in Firefox: the alternative there is
  // to collect gigabytes in a tab. It goes to the browser's own download
  // folder, without a dialog, which is what "save automatically" meant.
  if (downloads.getMode() === 'auto') {
    const streamed = await downloads.openStreamedDownload(filename, swSize);
    if (streamed) return streamed;
    // Nothing to stream to: small enough for memory, and no dialog.
    if (size < downloads.BLOB_LIMIT) return null;
  }

  if (!window.showSaveFilePicker) return null;
  try {
    const handle = await window.showSaveFilePicker({
      suggestedName: filename, ...pickerOpts,
    });
    return { writable: await handle.createWritable(), name: handle.name || filename };
  } catch (err) {
    if (err.name === 'AbortError') return false;
    throw err;
  }
}

/** The download of last resort, for browsers with no way to stream to disk. */
function _saveBlob(blob, filename) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

async function pipelinedDownload(transport, gekKey, fileId, totalChunks, onChunk,
                                 writable, signal) {
  const results = writable ? null : new Array(totalChunks);
  let nextSend = 0, nextRecv = 0;
  const inflight = new Array(totalChunks);

  const fire = () => {
    while (nextSend < totalChunks && nextSend - nextRecv < PIPELINE_WINDOW) {
      inflight[nextSend] = transport.fetchChunk(fileId, nextSend);
      nextSend++;
    }
  };

  fire();
  while (nextRecv < totalChunks) {
    if (signal && signal.aborted) {
      const err = new Error('Cancelled');
      err.name = 'AbortError';
      throw err;
    }
    const chunkMsg = await inflight[nextRecv];
    let plaintext;
    if (gekKey && chunkMsg.ct) {
      plaintext = await window.MeshBayCrypto.decryptChunkBin(
        gekKey, fileId, nextRecv, chunkMsg.nonce, chunkMsg.ct);
    } else if (gekKey && chunkMsg.ct_b64) {
      plaintext = await window.MeshBayCrypto.decryptChunk(
        gekKey, fileId, nextRecv, chunkMsg.nonce_b64, chunkMsg.ct_b64);
    } else {
      plaintext = _b64ToU8(chunkMsg.ct_b64 || chunkMsg.data_b64);
    }
    if (writable) {
      await writable.write(plaintext);
    } else {
      results[nextRecv] = plaintext;
    }
    nextRecv++;
    fire();
    if (onChunk) onChunk(plaintext.byteLength, nextRecv, totalChunks);
  }
  return results;
}

function GroupPage({ groupId, group, token, username, userId, userPrefs,
                    onRefreshAuth, onJoined, onGroupUpdated, onPresence, onLeft }) {
  const [status, setStatus] = useState('idle');
  const [entries, setEntries] = useState([]);

  const [error, setError] = useState('');
  const [selecting, setSelecting] = useState(false);
  const [selected, setSelected] = useState(() => new Set());
  const [editingDesc, setEditingDesc] = useState(false);
  const [descDraft, setDescDraft] = useState('');
  const [savingDesc, setSavingDesc] = useState(false);
  const [sortKey, setSortKey] = useState('name');
  const [sortAsc, setSortAsc] = useState(true);
  const [filter, setFilter] = useState('');
  const [currentPath, setCurrentPath] = useState('');
  const [videoEntry, setVideoEntry] = useState(null);
  const [previewEntry, setPreviewEntry] = useState(null);
  const defaultTab = (userPrefs && (userPrefs[`default_tab:${groupId}`] || userPrefs['default_tab'])) || 'chat';
  const [tab, setTab] = useState(defaultTab);
  useEffect(() => { setTab(defaultTab); }, [groupId]);
  const [groupMuted, setGroupMuted] = useState(() => !!(group && group.muted));

  const _lastTouch = useRef(0);
  const touchActivity = useCallback(() => {
    const now = Date.now();
    if (now - _lastTouch.current < 60_000) return;
    _lastTouch.current = now;
    const ts = new Date().toISOString();
    if (onGroupUpdated) onGroupUpdated(groupId, { last_activity_at: ts });
    hubFetch(`/v1/groups/${groupId}/activity`, { method: 'POST', token }).catch(() => {});
  }, [groupId, token, onGroupUpdated]);

  const toggleGroupMute = useCallback(async () => {
    const next = !groupMuted;
    setGroupMuted(next);
    try {
      await hubFetch(`/v1/groups/${groupId}/mute`, {
        method: 'POST', token, body: { muted: next },
      });
      if (onGroupUpdated) onGroupUpdated(groupId, { muted: next });
    } catch (err) {
      setGroupMuted(!next);
    }
  }, [groupMuted, groupId, token, onGroupUpdated]);

  // Directories are not index entries, so a new empty one needs a nudge
  // to appear in the breadcrumb listing.
  const [nodeDirs, setNodeDirs] = useState([]);
  // The group's roots and whether each is readable. A root whose drive is
  // unplugged keeps its files listed — they are frozen, not deleted — so this is
  // the only thing that lets the UI say which of the two it is.
  const [nodeRoots, setNodeRoots] = useState([]);

  const [isNodeAdmin, setIsNodeAdmin] = useState(false);
  // Whether ordinary members may upload here. The node decides and enforces it;
  // this only says whether to offer the controls. Defaults to true so a node
  // that predates the setting behaves as it always did.
  const [memberUpload, setMemberUpload] = useState(true);
  // Paired ≠ operator account. `is_node_admin` says the hub account owning this
  // node is the one connecting; this says the node pinned *this browser's* key
  // as an operator key. Only the second one lets you sign an invite, and only
  // the second one should make the pairing form go away.
  const [operatorPaired, setOperatorPaired] = useState(false);
  const [needsCode, setNeedsCode] = useState(false);
  // This browser holds a key the node does not know, for an account it does.
  // Not the operator's problem: a device already paired here can admit it.
  const [needsDevice, setNeedsDevice] = useState(false);
  const [deviceCode, setDeviceCode] = useState('');
  const [codeInput, setCodeInput] = useState('');
  const [retryKey, setRetryKey] = useState(0);
  const transportRef = useRef(null);
  const gekRef = useRef(null);
  // One refresh per mount: if a fresh token still says we are not a member, we
  // really are not, and retrying forever would hide that.
  const refreshedRef = useRef(false);

  const submitJoinCode = useCallback((e) => {
    e.preventDefault();
    const code = codeInput.trim();
    if (!code) return;
    _pendingJoinCode = code;
    setCodeInput('');
    setNeedsCode(false);
    setError('');
    setRetryKey(k => k + 1);
  }, [codeInput]);

  // One place that takes an index from the node and puts it everywhere it has to
  // go. Deleting a file used to refresh the table and leave the cache alone, so
  // the search page went on offering a file that no longer existed until the
  // group was reconnected.
  const applyIndex = useCallback((indexMsg) => {
    const fresh = indexMsg.entries || [];
    setEntries(fresh);
    if (indexMsg.dirs) setNodeDirs(indexMsg.dirs);
      if (indexMsg.roots) setNodeRoots(indexMsg.roots);
    cacheGroupIndex(groupId, group ? group.name : groupId, fresh);
  }, [groupId, group]);

  useEffect(() => {
    let cancelled = false;

    // The cache is written here and read only by the search page. It used to
    // seed this list too, which put a stale index on screen and then raced the
    // live one: IndexedDB is async, so a fast node could be overwritten by the
    // cache landing afterwards. Files shows what the node says, or says it
    // cannot reach the node.

    const connect = async () => {
      setStatus('discovering');
      setError('');
      gekRef.current = null;
      if (!_bundleKey) _bundleKey = await _loadBundleKey();
      try {
        const nodesData = await hubFetch(`/v1/groups/${groupId}/nodes`, { token });
        if (cancelled) return;
        if (!nodesData.nodes || nodesData.nodes.length === 0) {
          setStatus('offline');
          if (onPresence) onPresence(groupId, 'offline');
          return;
        }

        // No keys are carried in: the transport fetches this node's identity
        // from the node, or creates one there on a first join.
        const sessionKeys = null;

        setStatus('connecting');
        const nodeId = nodesData.nodes[0].node_id;
        // Renewed here rather than taken from the prop. This effect no longer
        // re-runs when the token rotates (see the dependency list below), so
        // the captured one can be older than the session's — and it is used to
        // sign the offer to the hub, where an expired one is a 401 and no
        // connection at all. Renewals are shared, so if one is already in
        // flight this waits for it instead of starting a second.
        const live = (await ensureFreshToken()) || token;
        // The same base the API calls use: signaling is a hub endpoint like
        // any other, and two sources for one address is how they drift.
        const transport = new window.MeshBayTransport(HUB, live);
        transportRef.current = transport;

        const ack = await transport.connect(
          nodeId, live, groupId, null, sessionKeys, _bundleKey, username,
          userId, _pendingJoinCode);
        _pendingJoinCode = null;
        if (cancelled) return;
        setIsNodeAdmin(!!ack.is_node_admin);
        setMemberUpload(ack.member_upload !== false);
        // Changed while we are connected, by an operator who may be someone
        // else entirely. Without this the button stays until a reconnection,
        // and a button that is still there is a button people press.
        transport.onUploadPolicy = (allowed) => setMemberUpload(allowed);
        setOperatorPaired(transport.memberRole === 'operator');

        // A first join to this node generated an identity for it; leave it with
        // the node so any other browser can become the same person here with the
        // passphrase. It is this node's key and no other's.
        if (transport.connected && transport.newNodeBundle) {
          try {
            await transport.storeKeypairBundle(transport.newNodeBundle);
            transport.newNodeBundle = null;
          } catch (e) {
            console.warn('[MeshBay] could not leave our key with the node:', e.message);
          }
        }

        // Import GEK from transport (fetched from node during handshake)
        if (transport.gekRaw && window.MeshBayCrypto) {
          gekRef.current = await window.MeshBayCrypto.importGEK(
            window.MeshBayCrypto.b64encode(transport.gekRaw));
        }

        setStatus('fetching');

        transport.onIndexSync = (msg) => {
          if (cancelled) return;
          applyIndex(msg);
        };

        // We are in: an invitation to this group has served its purpose.
        if (onJoined) onJoined(groupId);

        const indexMsg = await transport.fetchIndex();
        if (cancelled) return;
        applyIndex(indexMsg);
        setStatus('connected');
        touchActivity();
        // First-hand evidence, and the strongest available: this browser spoke
        // to the node. It outranks whatever the hub said in the group list.
        if (onPresence) onPresence(groupId, 'online');
      } catch (err) {
        if (cancelled) return;

        // Our token predates being added to this group. Refresh once and retry
        // rather than telling someone who was just invited that they are not a
        // member — which is what the node honestly sees, and is useless to them.
        if (err.reason === 'not_a_member' && !refreshedRef.current && onRefreshAuth) {
          refreshedRef.current = true;
          try {
            if (await onRefreshAuth()) {
              setRetryKey(k => k + 1);
              return;
            }
          } catch { /* fall through to the message below */ }
        }

        // The node has never seen this browser for this account: it needs a
        // one-time code from the operator before it will hand over the group
        // key. Not an error to shout about — a step in joining.
        if (err.reason === 'code_required') setNeedsCode(true);
        // A key this node has never pinned, for an account it knows. The way in
        // is a device already trusted here, not an operator — which is the
        // whole point of device linking: a second browser or a native client
        // must not cost anyone a support request.
        if (err.reason === 'unknown_device') setNeedsDevice(true);
        setError(err.message);
        setStatus('error');
        if (transportRef.current) {
          try { transportRef.current.close(); } catch { /* already gone */ }
          transportRef.current = null;
        }
        // A refusal means the node answered, so it is up; only a failure to
        // reach it at all is evidence of absence.
        if (onPresence) {
          onPresence(groupId, err.reason ? 'online' : 'offline');
        }
      }
    };

    if (token && window.MeshBayTransport) {
      connect();
    } else if (!window.MeshBayTransport) {
      setStatus('error');
      setError(t('group.err_transport'));
    }

    return () => {
      cancelled = true;
      if (transportRef.current) {
        // Handed over rather than closed: a download running when you leave the
        // group keeps its connection, and the last transfer using it closes it.
        transfers.releaseWhenIdle(transportRef.current);
        transportRef.current = null;
      }
    };
    // applyIndex is deliberately not a dependency: its identity changes with the
    // `group` object, which the hub poll re-creates, and re-running this effect
    // means tearing down the WebRTC connection. groupId is here, so a real group
    // change still re-captures it.
    //
    // Neither is the token itself, only whether there is one. It used to be a
    // dependency and that was harmless while a token never changed during a
    // session — it only expired. Now that the session renews itself, the string
    // rotates, and this effect tore the WebRTC connection down and rebuilt it
    // every time. Worst on arrival: a stored token past its life is renewed the
    // instant the page mounts, which is exactly when the group page is
    // negotiating ICE, so the connection was abandoned mid-handshake and the
    // node sat in `connecting` for ever. The live token is read inside
    // `connect()` instead. Signing out unmounts this page; signing in mounts
    // it; nothing in between should disturb a working connection.
  }, [groupId, Boolean(token), retryKey]);

  const downloadFile = useCallback(async (entry) => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    const gek = gekRef.current;

    // Both of these have to happen inside the click: a browser grants a file
    // picker, and re-grants a folder, only from a user gesture.
    const target = await _openDownloadTarget(entry.name, entry.size);
    if (target === false) return;          // the picker was dismissed

    const openRef = { url: null };
    transfers.start({
      kind: 'download', name: (target && target.name) || entry.name,
      total: entry.size, transport,
      open: target
        ? (target.open || null)
        : () => { if (openRef.url) window.open(openRef.url, '_blank'); },
      run: async ({ signal, onProgress }) => {
        const totalChunks = Math.ceil(entry.size / CHUNK_SIZE);
        let done = 0;
        const onChunk = (bytes) => { done += bytes; onProgress(done, entry.size); };

        if (target) {
          try {
            await pipelinedDownload(transport, gek, entry.id, totalChunks,
                                    onChunk, target.writable, signal);
            await target.writable.close();
          } catch (err) {
            await target.writable.abort().catch(() => {});
            throw err;
          }
        } else {
          const chunks = await pipelinedDownload(
            transport, gek, entry.id, totalChunks, onChunk, null, signal);
          const blob = new Blob(chunks);
          _saveBlob(blob, entry.name);
          openRef.url = URL.createObjectURL(blob);
        }
      },
    });
  }, []);

  const uploadFile = useCallback((e) => {
    const files = [...(e.target.files || [])];
    e.target.value = '';
    const transport = transportRef.current;
    if (!files.length || !transport || !transport.connected) return;
    setError('');

    for (const file of files) {
      transfers.start({
        kind: 'upload', name: file.name, total: file.size, transport,
        run: async ({ signal, onProgress }) => {
          await transport.uploadFile(file, {
            // Bytes the node acknowledged, not bytes read locally.
            onProgress: (sent) => onProgress(sent, file.size),
            signal,
          });
          // The node re-indexes on a filesystem event, so there is nothing to
          // wait on but the clock. Refreshing here means the file appears in
          // the list without anyone reloading.
          await new Promise(r => setTimeout(r, 2500));
          if (transport.connected) applyIndex(await transport.fetchIndex());
        },
      });
    }
  }, [applyIndex]);

  const makeDirectory = useCallback(async () => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    const name = prompt(t('group.mkdir_prompt'));
    if (!name || !name.trim()) return;
    try {
      await transport.createDirectory(currentPath, name.trim());
      const indexMsg = await transport.fetchIndex();
      if (indexMsg.entries) setEntries(indexMsg.entries);
      if (indexMsg.dirs) setNodeDirs(indexMsg.dirs);
      if (indexMsg.roots) setNodeRoots(indexMsg.roots);
    } catch (err) {
      setError(err.message);
    }
  }, [currentPath]);

  const saveDescription = useCallback(async (e) => {
    e.preventDefault();
    setSavingDesc(true);
    try {
      const r = await hubFetch(`/v1/groups/${groupId}`, {
        method: 'PATCH', token, body: { description: descDraft },
      });
      if (onGroupUpdated) onGroupUpdated(groupId, { description: r.description });
      setEditingDesc(false);
    } catch (err) {
      setError(err.message);
    } finally {
      setSavingDesc(false);
    }
  }, [groupId, token, descDraft, onGroupUpdated]);

  /**
   * Download a directory as a zip, written straight to disk.
   *
   * An archive of a group directory is routinely tens of gigabytes, so it is
   * never held anywhere: each file is fetched chunk by chunk, decrypted, and
   * handed to the zip writer, which hands it to the file the browser opened.
   * Peak memory is one chunk plus one small record per file.
   *
   * Without the File System Access API there is nowhere to stream to, and the
   * only alternative is to build the whole thing in memory — so that path is
   * offered but says what it costs first.
   */
  const downloadDirectory = useCallback(async (dir) => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;

    const files = entriesUnder(entries, dir);
    if (!files.length) {
      setError(t('group.zip_empty'));
      return;
    }
    const totalBytes = files.reduce((n, f) => n + (f.entry.size || 0), 0);
    const suggested = (dir.split('/').pop() || 'files') + '.zip';

    // totalBytes decides how this is delivered, but it is not the archive's
    // size — headers and the central directory come on top — so it is not
    // announced as a Content-Length that the download would then miss.
    const target = await _openDownloadTarget(suggested, totalBytes, {
      types: [{ description: 'ZIP archive',
                accept: { 'application/zip': ['.zip'] } }],
    }, 0);
    if (target === false) return;
    if (!target && !confirm(t('group.zip_no_stream', {
      size: formatSize(totalBytes), name: suggested,
    }))) {
      return;
    }
    const gek = gekRef.current;
    const zipOpenRef = { url: null };

    transfers.start({
      kind: 'download', name: (target && target.name) || suggested,
      total: totalBytes, transport,
      open: target
        ? (target.open || null)
        : () => { if (zipOpenRef.url) window.open(zipOpenRef.url, '_blank'); },
      run: async ({ signal, onProgress }) => {
        const writable = target ? target.writable : null;
        const parts = writable ? null : [];
        let written = 0;
        try {
          const zip = new ZipStream(async (bytes) => {
            if (writable) await writable.write(bytes);
            else parts.push(bytes.slice());
          });

          for (const { entry, name } of files) {
            await zip.begin(name, entry.size,
                            new Date((entry.added_at || 0) * 1000));
            // A zero-byte file has no chunk to ask for; the header and an empty
            // descriptor are the whole entry.
            const totalChunks = Math.ceil(entry.size / CHUNK_SIZE);
            if (totalChunks > 0) await pipelinedDownload(
              transport, gek, entry.id, totalChunks,
              (bytes) => { written += bytes; onProgress(written, totalBytes); },
              // pipelinedDownload writes in order, which the archive needs.
              { write: (plaintext) => zip.write(plaintext) }, signal);
            await zip.end();
          }
          await zip.finish();
          if (writable) await writable.close();
          else {
            const blob = new Blob(parts, { type: 'application/zip' });
            _saveBlob(blob, suggested);
            zipOpenRef.url = URL.createObjectURL(blob);
          }
        } catch (err) {
          if (writable) await writable.abort().catch(() => {});
          throw err;
        }
      },
    });
  }, [entries]);

  const deleteDirectory = useCallback(async (dir) => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    try {
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      await transport.deleteDirectory(dir, signFn);
      applyIndex(await transport.fetchIndex());
    } catch (err) {
      setError(err.message);
    }
  }, [applyIndex]);

  const deleteFile = useCallback(async (entry) => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    try {
      // Signs an explicit transcript built by transport.js, not opaque bytes from
      // the node — see MeshBayCrypto.adminTranscript and finding H5.
      // 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;
      await transport.deleteFile(entry.id, signFn);
      applyIndex(await transport.fetchIndex());
    } catch (err) {
      setError(err.message);
    }
  }, [applyIndex]);

  const refreshIndex = useCallback(async () => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    try {
      applyIndex(await transport.fetchIndex());
    } catch {}
  }, [applyIndex]);

  const toggleSort = useCallback((key) => {
    setSortAsc(prev => sortKey === key ? !prev : true);
    setSortKey(key);
  }, [sortKey]);

  const dirs = new Set();
  const filteredEntries = entries.filter(e => {
    const ePath = e.path || '';
    if (ePath === currentPath) {
      return !filter || e.name.toLowerCase().includes(filter.toLowerCase());
    }
    if (!currentPath && ePath) {
      dirs.add(ePath.split('/')[0]);
    } else if (currentPath && ePath.startsWith(currentPath + '/')) {
      const rest = ePath.slice(currentPath.length + 1);
      dirs.add(rest.split('/')[0]);
    }
    return false;
  });

  const sorted = [...filteredEntries].sort((a, b) => {
    let cmp = 0;
    if (sortKey === 'name') cmp = a.name.localeCompare(b.name);
    else if (sortKey === 'size') cmp = a.size - b.size;
    else if (sortKey === 'type') cmp = a.type.localeCompare(b.type);
    else if (sortKey === 'date') cmp = a.added_at - b.added_at;
    return sortAsc ? cmp : -cmp;
  });

  // The node's own listing, so an empty folder is visible, plus anything implied
  // by a file path in case the two ever disagree.
  for (const d of nodeDirs) {
    if (!currentPath && !d.includes('/')) dirs.add(d);
    else if (currentPath && d.startsWith(currentPath + '/')) {
      const rest = d.slice(currentPath.length + 1);
      if (!rest.includes('/')) dirs.add(rest);
    }
  }
  const subdirs = [...dirs].sort();

  // At the top of a group the folders on screen ARE the roots, so their state
  // belongs there. Deeper in, everything shown lives inside one readable root
  // and there is nothing to flag.
  const rootState = new Map(nodeRoots.map(r => [r.name, r]));
  const unavailableHere = currentPath
    ? []
    : subdirs.filter(d => rootState.get(d) && rootState.get(d).available === false);
  // A member cannot create a folder at the top of a group: that level is the
  // set of roots, which is the operator's configuration and not a directory on
  // anyone's disk. The node refuses it, so offering it would only produce an
  // error nobody can act on.
  const canCreateDir = Boolean(currentPath) && isNodeAdmin;

  const baseLabel = {
    idle: t('status.idle'),
    discovering: t('status.discovering'),
    connecting: t('status.connecting'),
    fetching: t('status.fetching'),
    connected: t('status.files', { n: entries.length }),
    offline: t('status.offline'),
    error: t('status.error'),
  }[status] || status;
  const statusLabel = baseLabel;

  const breadcrumbs = currentPath ? currentPath.split('/') : [];

  // Selection is keyed globally — file ids, and 'dir:' plus a full path — so
  // walking into another folder keeps what was already ticked.
  const dirKey = (name) => 'dir:' + (currentPath ? currentPath + '/' + name : name);
  const selectedFiles = entries.filter(e => selected.has(e.id));
  const selectedDirs = [...selected]
    .filter(k => typeof k === 'string' && k.startsWith('dir:'))
    .map(k => k.slice(4));
  const toggle = (key) => setSelected(prev => {
    const next = new Set(prev);
    if (next.has(key)) next.delete(key); else next.add(key);
    return next;
  });

  const onlyFile = selectedFiles.length === 1 && selectedDirs.length === 0
    ? selectedFiles[0] : null;
  const deletableFiles = selectedFiles.filter(
    e => isNodeAdmin || (userId && e.uploader_id === userId));

  // Asked in two places — the Files toolbar and the chat composer — so it is
  // answered once. The operator is never locked out of their own node.
  const mayUpload = memberUpload || isNodeAdmin;
  const run = (fn) => {
    setSelecting(false);
    setSelected(new Set());
    Promise.resolve().then(fn).catch(err => {
      if (err && err.name !== 'AbortError') setError(err.message);
    });
  };

  // Icon only, with the name in the tooltip: these sit in a toolbar that is
  // already narrow, and every one of them is a verb the icon carries on its
  // own. `title` gives the hover text and `aria-label` the accessible name —
  // an icon button with neither is unusable with a screen reader.
  //
  // Every action is rendered as soon as Select is on, and the ones that do not
  // apply are disabled rather than absent. Buttons appearing and vanishing as
  // the selection changed made the bar jump about and gave no clue that an
  // action existed at all before something was ticked.
  const action = (icon, label, onClick, opts = {}) => html`
    <button class="tb-icon-btn ${opts.danger ? 'danger' : ''}"
      title=${label} aria-label=${label}
      disabled=${!!opts.disabled} onClick=${onClick}>
      <${Icon} name=${icon} />
    </button>
  `;

  const canPlay = !!(onlyFile && onlyFile.type === 'video');
  const canView = !!(onlyFile && onlyFile.type !== 'video' && canPreview(onlyFile));
  const deletableCount = deletableFiles.length
    + (operatorPaired ? selectedDirs.length : 0);
  // The operator can always delete; anyone else only ever sees the button if
  // something here is theirs to remove. Hiding it from an uploader would take
  // away a right the protocol grants them (draft-v5 §5.1), not just a control.
  const mayEverDelete = isNodeAdmin
    || (userId && entries.some(e => e.uploader_id === userId));

  const actionItems = html`
    ${action('play', t('group.play'),
      () => run(() => setVideoEntry(onlyFile)), { disabled: !canPlay })}
    ${action('eye', t('group.view'),
      () => run(() => setPreviewEntry(onlyFile)), { disabled: !canView })}
    ${action('download',
      selectedFiles.length
        ? t('group.download_n', { n: selectedFiles.length })
        : t('group.download'),
      () => run(async () => {
        // Awaited one at a time, and each returns as soon as its transfer is
        // registered — so the transfers still run together. Firing them without
        // awaiting meant every file asked the browser for a save dialog at
        // once, and a browser allows one: the rest were rejected and only the
        // first file ever downloaded.
        for (const e of selectedFiles) await downloadFile(e);
      }), { disabled: selectedFiles.length === 0 })}
    ${action('archive',
      selectedDirs.length
        ? t('group.download_zip_n', { n: selectedDirs.length })
        : t('group.download_zip_n', { n: 0 }),
      () => run(async () => {
        for (const d of selectedDirs) await downloadDirectory(d);
      }), { disabled: selectedDirs.length === 0 })}
    ${mayEverDelete && action('trash',
      deletableCount ? t('group.delete_n', { n: deletableCount }) : t('group.delete'),
      () => {
        const names = [...deletableFiles.map(e => e.name),
                       ...(operatorPaired ? selectedDirs : [])];
        if (!confirm(t('group.delete_n_confirm', { n: names.length,
                                                   names: names.join(', ') }))) return;
        run(() => {
          for (const e of deletableFiles) deleteFile(e);
          if (operatorPaired) for (const d of selectedDirs) deleteDirectory(d);
        });
      },
      { danger: true, disabled: status !== 'connected' || deletableCount === 0 })}
  `;

  return html`
    <div>
      <div class="group-header">
        <div>
          <h2 style="margin-bottom:${group && group.description ? '4px' : '0'}">
            ${group ? group.name : t('group.default_name')}
          </h2>
          ${editingDesc
            ? html`
              <form class="group-desc-edit" onSubmit=${saveDescription}>
                <textarea rows="2" maxlength="512" autofocus
                  placeholder="${t('group.desc_placeholder')}"
                  value=${descDraft}
                  onInput=${e => setDescDraft(e.target.value)}></textarea>
                <div>
                  <button class="admin-btn" type="submit" disabled=${savingDesc}>
                    ${savingDesc ? '...' : t('group.desc_save')}
                  </button>
                  <button class="btn-secondary" type="button"
                    onClick=${() => setEditingDesc(false)}>${t('group.desc_cancel')}</button>
                </div>
              </form>
            `
            : html`
              ${group && group.description && html`
                <p class="group-desc">${group.description}</p>
              `}
              ${group && group.is_admin && html`
                <button class="link-btn" title=${t('group.desc_edit')}
                  onClick=${() => { setDescDraft(group.description || '');
                                    setEditingDesc(true); }}>
                  <${Icon} name="pencil" />${' '}
                  ${group.description ? t('group.desc_edit') : t('group.desc_add')}
                </button>
              `}
            `}
        </div>
        ${group && html`
          <button class="group-mute-btn" onClick=${toggleGroupMute}
            title=${groupMuted ? t('group.unmute') : t('group.mute')}>
            <${Icon} name=${groupMuted ? 'bell-off' : 'bell'} />
          </button>
        `}
      </div>
      ${error && html`<div class="error-msg" style="margin-bottom:12px">${error}${' '}
        <button class="admin-btn" style="margin-left:8px;font-size:0.9em"
          onClick=${() => setRetryKey(k => k + 1)}>${t('group.retry')}</button>
      </div>`}
      ${needsDevice && html`
        <div class="invite-form" style="margin-bottom:12px">
          <h4>${t('device.add_title')}</h4>
          <p class="settings-hint">${t('device.add_hint')}</p>
          ${!deviceCode && html`
            <button class="admin-btn" onClick=${async () => {
              try {
                const transport = transportRef.current;
                const out = await transport.requestDeviceAdd(userId);
                setDeviceCode(out.code);
              } catch (err) { setError(err.message); }
            }}>${t('device.add_btn')}</button>
          `}
          ${deviceCode && html`
            <p class="settings-hint">${t('device.add_show')}</p>
            <p style="font-family:monospace;font-size:1.6em;letter-spacing:2px">
              ${deviceCode}
            </p>
          `}
        </div>
      `}
      ${needsCode && html`
        <form class="invite-form" style="margin-bottom:12px" onSubmit=${submitJoinCode}>
          <h4>${t('group.join_code_title')}</h4>
          <p class="settings-hint">${t('group.join_code_hint')}</p>
          <div style="display:flex;gap:8px">
            <input type="text" placeholder="XXXX-XXXX" style="font-family:monospace"
              value=${codeInput} onInput=${e => setCodeInput(e.target.value)} required />
            <button class="admin-btn" type="submit">${t('group.join_code_btn')}</button>
          </div>
        </form>
      `}
      ${/* Not gated on the connection any more. Leaving a group, deleting it
            and seeing who is in it are hub-side, and moving them into this tab
            would otherwise have made them unreachable exactly when a node is
            down — which is when someone is most likely to want them. Files and
            chat still need the node and say so. */ group && html`
        <div class="group-tabs">
          <button class="group-tab ${tab === 'chat' ? 'active' : ''}"
            onClick=${() => setTab('chat')} title=${t('group.tab_chat')}>
            <${Icon} name="chat" cls="tab-icon" /></button>
          <button class="group-tab ${tab === 'files' ? 'active' : ''}"
            onClick=${() => setTab('files')} title=${t('group.tab_files')}>
            <${Icon} name="folder" cls="tab-icon" /></button>
          <button class="group-tab ${tab === 'settings' ? 'active' : ''}"
            onClick=${() => setTab('settings')} title=${t('group.tab_settings')}>
            <${Icon} name="gear" cls="tab-icon" /></button>
        </div>

        ${tab === 'files' && (status === 'discovering' || status === 'connecting' || status === 'fetching') && html`
          <p class="page-message"><span class="spinner"></span>${' '}${t('status.connecting_short')}</p>
        `}
        ${tab === 'files' && status === 'offline' && html`
          <p class="page-message">${t('group.offline_title')} ${t('group.offline_hint')}</p>
        `}

        ${tab === 'files' && status === 'connected' && html`
          <div class="file-toolbar">
            <div class="toolbar-group">
              ${mayUpload && html`
              <label class="tb-btn primary">
                <${Icon} name="upload" /> ${t('group.upload')}
                <input type="file" multiple style="display:none"
                  onChange=${uploadFile} />
              </label>
              `}
              ${canCreateDir && html`
              <button class="tb-btn" onClick=${makeDirectory}>
                <${Icon} name="folder-plus" /> ${t('group.mkdir')}
              </button>
              `}
            </div>

            <div class="breadcrumbs">
              <a class="crumb" onClick=${() => setCurrentPath('')}>
                <${Icon} name="home" />
              </a>
              ${breadcrumbs.map((seg, i) => {
                const path = breadcrumbs.slice(0, i + 1).join('/');
                return html`
                  <span class="crumb-sep">/</span>
                  <a class="crumb" onClick=${() => setCurrentPath(path)}>${seg}</a>
                `;
              })}
            </div>

            <div class="toolbar-group right">
              <div class="tb-search">
                <${Icon} name="search" />
                <input type="text" placeholder="${t('group.filter')}"
                  value=${filter} onInput=${e => setFilter(e.target.value)} />
              </div>
              <button class="tb-btn ${selecting ? 'active' : ''}"
                onClick=${() => {
                  setSelecting(v => !v);
                  setSelected(new Set());
                }}>
                <${Icon} name=${selecting ? 'check' : 'checkbox'} />
                ${selecting ? t('group.select_done') : t('group.select')}
              </button>
              ${selecting && html`<div class="tb-actions">${actionItems}</div>`}
            </div>
          </div>
          <table class="file-table">
            <thead>
              <tr>
                ${selecting && html`<th class="sel-cell"></th>`}
                <th></th>
                <th class="sortable" onClick=${() => toggleSort('name')}>
                  ${t('group.col_name')} ${sortKey === 'name' ? (sortAsc ? '▲' : '▼') : ''}
                </th>
                <th class="sortable" onClick=${() => toggleSort('size')}>
                  ${t('group.col_size')} ${sortKey === 'size' ? (sortAsc ? '▲' : '▼') : ''}
                </th>
                <th class="sortable th-type" onClick=${() => toggleSort('type')}>
                  ${t('group.col_type')} ${sortKey === 'type' ? (sortAsc ? '▲' : '▼') : ''}
                </th>
                <th class="sortable th-date" onClick=${() => toggleSort('date')}>
                  ${t('group.col_date')} ${sortKey === 'date' ? (sortAsc ? '▲' : '▼') : ''}
                </th>
              </tr>
            </thead>
            <tbody>
              ${subdirs.map(d => {
                const full = currentPath ? currentPath + '/' + d : d;
                const inside = entriesUnder(entries, full);
                const bytes = inside.reduce((n, f) => n + (f.entry.size || 0), 0);
                return html`
                <tr class="file-row dir-row" key=${full} onClick=${() =>
                  selecting ? toggle(dirKey(d)) : setCurrentPath(full)}>
                  ${selecting && html`
                    <td class="sel-cell">
                      <input type="checkbox" checked=${selected.has(dirKey(d))}
                        onClick=${(ev) => ev.stopPropagation()}
                        onChange=${() => toggle(dirKey(d))} />
                    </td>
                  `}
                  <td>${unavailableHere.includes(d) ? '\u{26A0}' : '\u{1F4C1}'}</td>
                  <td>${d}${unavailableHere.includes(d) ? html`
                    <span class="root-offline"> ${t('group.root_unavailable')}</span>
                  ` : ''}</td>
                  <td class="file-size">${inside.length ? formatSize(bytes) : ''}</td>
                  <td class="td-type"></td>
                  <td class="td-date"></td>
                </tr>
              `; })}
              ${sorted.map(e => html`
                  <tr class="file-row" key=${e.id}
                    onClick=${() => selecting && toggle(e.id)}>
                    ${selecting && html`
                      <td class="sel-cell">
                        <input type="checkbox" checked=${selected.has(e.id)}
                          onClick=${(ev) => ev.stopPropagation()}
                          onChange=${() => toggle(e.id)} />
                      </td>
                    `}
                    <td>${FILE_ICONS[e.type] || FILE_ICONS.other}</td>
                    <td class="file-name">
                      ${!selecting && canPreview(e)
                        ? html`<a class="file-link" onClick=${() => {
                            if (e.type === 'video') setVideoEntry(e);
                            else setPreviewEntry(e);
                          }}>${e.name}</a>`
                        : e.name
                      }
                    </td>
                    <td class="file-size">${formatSize(e.size)}</td>
                    <td class="file-type td-type">${e.type}</td>
                    <td class="file-date td-date">${formatDate(e.added_at)}</td>
                  </tr>
                `)}
              ${sorted.length === 0 && subdirs.length === 0 && html`
                <tr><td colspan=${selecting ? 6 : 5} class="file-empty">
                  ${filter ? t('group.empty_filter') : t('group.empty_dir')}
                </td></tr>
              `}
            </tbody>
          </table>
        `}

        ${tab === 'chat' && status === 'connected' && html`
          <${ChatPanel} transportRef=${transportRef} username=${username}
            entries=${entries} gekRef=${gekRef} onRefreshIndex=${refreshIndex}
            mayUpload=${mayUpload} onActivity=${touchActivity}
            onPreview=${(entry) => {
              if (entry.type === 'video') setVideoEntry(entry);
              else setPreviewEntry(entry);
            }} />
        `}
        ${tab === 'chat' && (status === 'discovering' || status === 'connecting' || status === 'fetching') && html`
          <p class="page-message"><span class="spinner"></span>${' '}${t('status.connecting_short')}</p>
        `}
        ${tab === 'chat' && status === 'offline' && html`
          <p class="page-message">${t('group.offline_title')} ${t('group.offline_hint')}</p>
        `}

        ${tab === 'settings' && html`
          <${GroupSettingsPanel} groupId=${groupId} group=${group} token=${token}
            transportRef=${transportRef} gekRef=${gekRef}
            isNodeAdmin=${isNodeAdmin} userId=${userId}
            operatorPaired=${operatorPaired} connected=${status === 'connected'}
            memberUpload=${memberUpload}
            onMemberUpload=${(allowed) => setMemberUpload(allowed)}
            onLeft=${onLeft}
            onPaired=${() => setOperatorPaired(true)} />
        `}
      `}
      ${status === 'offline' && !group && html`
        <p class="page-message">
          ${t('group.offline_title')}
          ${' '}${t('group.offline_hint')}
        </p>
      `}
      ${(status === 'discovering' || status === 'connecting' || status === 'fetching') && !group && html`
        <p class="page-message"><span class="spinner"></span>${' '}${t('status.connecting_short')}</p>
      `}
      ${previewEntry && html`
        <${FilePreview}
          entry=${previewEntry}
          transportRef=${transportRef}
          gekRef=${gekRef}
          onClose=${() => setPreviewEntry(null)}
          onDownload=${() => downloadFile(previewEntry)} />
      `}
      ${videoEntry && html`
        <${VideoPlayer}
          entry=${videoEntry}
          transportRef=${transportRef}
          gekRef=${gekRef}
          onClose=${() => setVideoEntry(null)}
          onDownload=${() => downloadFile(videoEntry)} />
      `}
    </div>
  `;
}

// ── File Preview (text, images) ─────────────────────────────────────────

const TEXT_EXTS = /\.(txt|md|json|csv|log|xml|yaml|yml|ini|conf|py|js|html|css|sh|c|h|java|rs|go|rb|toml)$/i;
const IMAGE_EXTS = /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i;

function FilePreview({ entry, transportRef, gekRef, onClose, onDownload }) {
  const [phase, setPhase] = useState('loading');
  const [progress, setProgress] = useState(0);
  const [content, setContent] = useState(null);
  const [error, setError] = useState('');
  const [downloading, setDownloading] = useState(false);
  const blobUrlRef = useRef(null);

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      const transport = transportRef.current;
      if (!transport || !transport.connected) {
        setError(t('video.err_transport'));
        setPhase('error');
        return;
      }
      try {
        const totalChunks = Math.ceil(entry.size / CHUNK_SIZE);
        let downloaded = 0;
        const chunks = await pipelinedDownload(
          transport, gekRef.current, entry.id, totalChunks,
          (bytes) => { downloaded += bytes; setProgress(downloaded / entry.size); },
        );
        if (cancelled) return;

        if (/\.pdf$/i.test(entry.name)) {
          // Decrypted here and shown from a blob: URL — the bytes never leave
          // the page, and the browser's own viewer renders them.
          const blob = new Blob(chunks, { type: 'application/pdf' });
          blobUrlRef.current = URL.createObjectURL(blob);
          setContent({ type: 'pdf' });
        } else if (entry.name.match(IMAGE_EXTS)) {
          const ext = entry.name.split('.').pop().toLowerCase();
          const mime = ext === 'svg' ? 'image/svg+xml'
            : ext === 'png' ? 'image/png'
            : ext === 'gif' ? 'image/gif'
            : ext === 'webp' ? 'image/webp'
            : 'image/jpeg';
          const blob = new Blob(chunks, { type: mime });
          blobUrlRef.current = URL.createObjectURL(blob);
          setContent({ type: 'image' });
        } else {
          const decoder = new TextDecoder('utf-8', { fatal: false });
          const text = chunks.map(c => decoder.decode(c, { stream: true })).join('');
          setContent({ type: 'text', text: text.slice(0, 500000) });
        }
        setPhase('ready');
      } catch (err) {
        if (!cancelled) { setError(err.message); setPhase('error'); }
      }
    };
    load();
    return () => { cancelled = true; };
  }, [entry]);

  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  useEffect(() => {
    return () => {
      if (blobUrlRef.current) {
        URL.revokeObjectURL(blobUrlRef.current);
        blobUrlRef.current = null;
      }
    };
  }, []);

  return html`
    <div class="video-overlay" onClick=${(e) => {
      if (e.target.classList.contains('video-overlay')) onClose();
    }}>
      <div class="video-top-bar">
        <span class="video-title">${entry.name} (${formatSize(entry.size)})</span>
        ${onDownload && html`
          <button class="video-close ${downloading ? 'dl-active' : ''}"
            onClick=${() => {
              if (!downloading) {
                setDownloading(true);
                onDownload();
                setTimeout(() => setDownloading(false), 1500);
              }
            }}
            title="${t('group.download')}" disabled=${downloading}>
            ${downloading
              ? html`<span class="spinner"></span>`
              : html`<${Icon} name="download" />`}</button>
        `}
        <button class="video-close" onClick=${onClose} title="${t('video.close')}">
          <${Icon} name="close" /></button>
      </div>
      ${phase === 'loading' && html`
        <div class="video-loading">
          <div class="video-loading-label">${t('video.loading', { name: entry.name })}</div>
          <div class="video-progress-bar">
            <div class="video-progress-fill" style="width:${Math.round(progress * 100)}%"></div>
          </div>
        </div>
      `}
      ${phase === 'ready' && content?.type === 'pdf' && html`
        <object data=${blobUrlRef.current} type="application/pdf"
                class="preview-pdf" aria-label=${entry.name}>
          <p class="page-message">${t('preview.pdf_fallback')}</p>
        </object>
      `}
      ${phase === 'ready' && content?.type === 'image' && html`
        <div class="preview-image-wrap">
          <img class="preview-image" src=${blobUrlRef.current} alt=${entry.name} />
        </div>
      `}
      ${phase === 'ready' && content?.type === 'text' && html`
        <div class="preview-text-wrap">
          <pre class="preview-text">${content.text}</pre>
        </div>
      `}
      ${phase === 'error' && html`
        <div class="video-error">${error}</div>
      `}
    </div>
  `;
}

function _b64ToU8(b64) {
  const bin = atob(b64);
  const arr = new Uint8Array(bin.length);
  for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
  return arr;
}

// ── 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,
                             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('');

  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]);
  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 [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. */
        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>
          `}
          ${connected && !operatorPaired && html`
            <p class="settings-hint">
              ${isNodeAdmin ? t('members.invite_needs_pairing')
                            : t('members.invite_ask_operator')}
            </p>
          `}
          ${connected && operatorPaired && html`
            <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)} required />
                <button class="admin-btn" type="submit" disabled=${inviting}>
                  ${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>
      `}

      ${/* 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`
        <div class="settings-section">
          <h3 class="settings-heading">${t('members.uploads_title')}</h3>
          <div class="settings-row">
            <span class="settings-label">
              ${memberUpload ? t('members.uploads_on') : t('members.uploads_off')}
            </span>
            <button class="admin-btn" disabled=${uploadBusy}
              onClick=${() => setUploads(!memberUpload)}>
              ${uploadBusy ? '...'
                           : (memberUpload ? t('members.uploads_disable')
                                           : t('members.uploads_enable'))}
            </button>
          </div>
          <p class="settings-hint">${t('members.uploads_hint')}</p>
          ${uploadMsg && html`<p class="error-msg">${uploadMsg}</p>`}
        </div>
      `}

      ${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>
      `}

      ${/* Roots management (Electron-only, when node is local) */
        nodeDetected && nodeRoots.length > 0 && html`
        <div class="settings-section">
          <h3 class="settings-heading">${t('settings_node.roots')}</h3>
          ${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;
                      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 loadNodeInfo();
                      } 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;
                setNodeBusy(true); setNodeMsg('');
                try {
                  await platform.node.call('POST',
                    '/api/groups/' + groupId + '/roots',
                    { path: chosen.path, name: chosen.name });
                  await platform.node.call('POST', '/api/reload');
                  setNodeMsg(t('node.root_added'));
                  await loadNodeInfo();
                } catch (err) { setNodeMsg(platform.bridgeMessage(err)); }
                finally { setNodeBusy(false); }
              }}>
              <${Icon} name="folder-plus" /> ${t('node.add_root')}
            </button>
          </div>
        </div>
      `}

      ${/* Upload toggle via loopback when MNP not connected */
        nodeDetected && !connected && html`
        <div class="settings-section">
          <h3 class="settings-heading">${t('members.uploads_title')}</h3>
          <div class="settings-row">
            <span class="settings-label">
              ${memberUpload ? t('members.uploads_on') : t('members.uploads_off')}
            </span>
            <button class="admin-btn" disabled=${nodeBusy}
              onClick=${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); }
              }}>
              ${memberUpload ? t('members.uploads_disable')
                             : t('members.uploads_enable')}
            </button>
          </div>
          <p class="settings-hint">${t('members.uploads_hint')}</p>
        </div>
      `}

      ${/* Delete/leave — node detach first (reversible), then hub delete
            (irreversible). */ html`
        <div class="settings-section">
          <h3 class="settings-heading">
            ${isOwner ? t('group.delete_group') : t('group.leave')}
          </h3>
          <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>
        </div>
      `}

      <div class="settings-section">
        <h3 class="settings-heading">
          ${t('group.tab_members')} (${members.length})
        </h3>
        <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>
        `}
      </div>
    </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;

function linkify(text) {
  const out = [];
  let last = 0;
  for (const m of String(text).matchAll(URL_RE)) {
    if (m.index > last) out.push(text.slice(last, m.index));
    // Trailing punctuation is almost never part of the address.
    let url = m[0];
    let tail = '';
    while (/[.,;:!?)\]]$/.test(url)) { tail = url.slice(-1) + tail; url = url.slice(0, -1); }
    out.push(html`<a href=${url} target="_blank" rel="noopener noreferrer"
      class="chat-link">${url}</a>`);
    if (tail) out.push(tail);
    last = m.index + m[0].length;
  }
  if (last < text.length) out.push(text.slice(last));
  return out;
}

function formatTime(ts) {
  const d = new Date(ts * 1000);
  const now = new Date();
  // getLocale() rather than the browser default: the user may have picked a
  // language here that differs from the one their OS reports.
  const time = d.toLocaleTimeString(getLocale(), { hour: '2-digit', minute: '2-digit' });
  if (d.toDateString() === now.toDateString()) return time;
  return d.toLocaleDateString(getLocale(), { month: 'short', day: 'numeric' }) + ' ' + time;
}

function _parsePayload(raw) {
  if (typeof raw === 'string' && raw.startsWith('{')) {
    try { return JSON.parse(raw); } catch { /* not JSON */ }
  }
  return null;
}

// How much history a group opens with, and how much each "older" click adds.
const CHAT_PAGE = 100;
const CHAT_OLDER_PAGE = 50;

// Breathing room under the panel, and the floor below which shrinking it stops
// helping — past that the page may scroll after all, which beats a chat two
// lines tall.
const CHAT_BOTTOM_GAP = 16;
const CHAT_MIN_HEIGHT = 240;

function _sameDay(a, b) {
  const da = new Date(a * 1000), db = new Date(b * 1000);
  return da.getFullYear() === db.getFullYear()
    && da.getMonth() === db.getMonth()
    && da.getDate() === db.getDate();
}

/** "Today" / "Yesterday" / a written date, in the reader's language. */
function _dayLabel(ts) {
  const d = new Date(ts * 1000);
  const now = new Date();
  if (_sameDay(ts, now.getTime() / 1000)) return t('chat.today');
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  if (_sameDay(ts, yesterday.getTime() / 1000)) return t('chat.yesterday');
  return d.toLocaleDateString(getLocale(), {
    weekday: 'long', day: 'numeric', month: 'long',
    year: d.getFullYear() === now.getFullYear() ? undefined : 'numeric',
  });
}

function ChatImage({ filename, entries, transportRef, gekRef }) {
  const [blobUrl, setBlobUrl] = useState(null);
  const [loading, setLoading] = useState(true);
  const loadedRef = useRef(false);

  useEffect(() => {
    if (loadedRef.current) return;
    let cancelled = false;
    const load = async () => {
      const transport = transportRef.current;
      if (!transport || !transport.connected) { setLoading(true); return; }
      const entry = entries.find(e => e.name === filename);
      if (!entry) { setLoading(true); return; }
      try {
        const totalChunks = Math.ceil(entry.size / CHUNK_SIZE);
        const chunks = await pipelinedDownload(transport, gekRef.current, entry.id, totalChunks);
        if (cancelled) return;
        const ext = filename.split('.').pop().toLowerCase();
        const mime = ext === 'png' ? 'image/png' : ext === 'gif' ? 'image/gif'
          : ext === 'webp' ? 'image/webp' : ext === 'svg' ? 'image/svg+xml' : 'image/jpeg';
        const blob = new Blob(chunks, { type: mime });
        loadedRef.current = true;
        setBlobUrl(URL.createObjectURL(blob));
      } catch { /* ignore */ }
      if (!cancelled) setLoading(false);
    };
    load();
    return () => { cancelled = true; };
  }, [filename, entries.length]);

  useEffect(() => {
    return () => { if (blobUrl) URL.revokeObjectURL(blobUrl); };
  }, [blobUrl]);

  if (loading) return html`<div class="chat-att-thumb"><span class="spinner"></span></div>`;
  if (!blobUrl) return html`<div class="chat-att-img">${'\u{1F5BC}'} ${filename}</div>`;
  return html`<img class="chat-att-thumb" src=${blobUrl} alt=${filename} />`;
}

function ChatPanel({ transportRef, username, entries, gekRef, onRefreshIndex,
                    onPreview, mayUpload = true, onActivity }) {
  const [messages, setMessages] = useState([]);
  const [hasMore, setHasMore] = useState(false);
  const [loadingOlder, setLoadingOlder] = useState(false);
  const [atBottom, setAtBottom] = useState(true);
  const [unreadFrom, setUnreadFrom] = useState(null);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const [attaching, setAttaching] = useState(false);
  const listRef = useRef(null);
  const panelRef = useRef(null);
  const inputRef = useRef(null);
  const loadedRef = useRef(false);
  // Set just before older messages are prepended; read once, after the DOM has
  // them but before the browser paints.
  const anchorRef = useRef(null);
  const atBottomRef = useRef(true);

  useEffect(() => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;

    if (!loadedRef.current) {
      loadedRef.current = true;
      // The newest page. This used to be fetchChatHistory(0, 200), which paged
      // forwards from the very first message ever sent, so a busy group opened
      // on its oldest screen and the recent conversation was unreachable.
      transport.fetchChatHistory({ limit: CHAT_PAGE })
        .then(({ messages: msgs, hasMore: more }) => {
          setMessages(msgs);
          setHasMore(more);
        })
        .catch(() => {});
    }

    transport.onChat = (msg) => {
      // A live message has no row id until it is re-read from the node, so it
      // gets a local one. Keys have to be stable and unique or prepending a
      // page makes Preact reuse the wrong bubbles. Computed once and reused
      // below: the unread marker points at a message by id, so generating a
      // second one there would point it at nothing.
      const id = msg.id
        || `live-${Date.now()}-${Math.random().toString(36).slice(2)}`;
      setMessages(prev => [...prev, {
        id,
        sender_id: msg.sender_id,
        sender_name: msg.sender_name || '',
        payload: msg.payload,
        timestamp: msg.timestamp || Date.now() / 1000,
        thread_id: msg.thread_id,
      }]);
      // Somebody wrote while you were reading further up: mark where you were
      // rather than yanking the view down.
      if (!atBottomRef.current) setUnreadFrom(prev => prev ?? id);
    };

    return () => { transport.onChat = null; };
  }, [transportRef.current?.connected]);

  const loadOlder = useCallback(async () => {
    const transport = transportRef.current;
    if (!transport || !transport.connected || loadingOlder || !messages.length) return;
    setLoadingOlder(true);
    const list = listRef.current;
    // Keeping the reading position means restoring the distance from the
    // *bottom*, not scrollTop: everything above the viewport just grew.
    anchorRef.current = list ? list.scrollHeight - list.scrollTop : null;
    try {
      const { messages: older, hasMore: more } =
        await transport.fetchChatHistory({ before: messages[0].id, limit: CHAT_OLDER_PAGE });
      setMessages(prev => [...older, ...prev]);
      setHasMore(more);
    } catch {
      anchorRef.current = null;
    } finally {
      setLoadingOlder(false);
    }
  }, [messages, loadingOlder]);

  useLayoutEffect(() => {
    const list = listRef.current;
    if (!list) return;
    if (anchorRef.current !== null) {
      list.scrollTop = list.scrollHeight - anchorRef.current;
      anchorRef.current = null;
      return;
    }
    // Only follow the conversation if the reader was already at the bottom.
    // Scrolling unconditionally fought every attempt to read back through it.
    //
    // scrollTop rather than bottomRef.scrollIntoView: the sentinel has no
    // height, so aligning it to the bottom of the viewport leaves the list's
    // own padding below it and the bar stops just short of the end.
    if (atBottomRef.current) list.scrollTop = list.scrollHeight;
  }, [messages]);

  // The panel was `calc(100vh - 220px)`: a guess at how much sits above it. On a
  // phone the group header — title, description, edit link, delete button, tabs
  // — is closer to 430px, so the panel ran past the fold and the composer ended
  // up off screen with the whole page scrolling to reach it.
  //
  // Measured instead, from the panel's own position in the document, so the
  // header can be any height. `visualViewport` rather than innerHeight where it
  // exists: on Android the on-screen keyboard shrinks the visual viewport
  // without changing innerHeight, and the composer would go back under it.
  useLayoutEffect(() => {
    const el = panelRef.current;
    if (!el) return;
    const fit = () => {
      const vh = window.visualViewport?.height || window.innerHeight;
      // Document-relative, so a page that happens to be scrolled does not skew
      // the result — the answer must be the same either way.
      const top = el.getBoundingClientRect().top + window.scrollY;
      el.style.height = `${Math.max(CHAT_MIN_HEIGHT, vh - top - CHAT_BOTTOM_GAP)}px`;
      // What sits *below* the panel is not knowable from up here — today it is
      // `.main`'s 24px bottom padding against this 16px gap, which left the
      // document 8px taller than the window and a scrollbar on the chat tab at
      // every window size. Rather than encode 24 somewhere and have the next
      // change to the page break it again, the leftover is measured and taken
      // off. Self-correcting: anything added under the panel is absorbed the
      // same way.
      const over = document.documentElement.scrollHeight - vh;
      if (over > 0) {
        el.style.height =
          `${Math.max(CHAT_MIN_HEIGHT, el.getBoundingClientRect().height - over)}px`;
      }
    };
    fit();
    window.addEventListener('resize', fit);
    window.addEventListener('orientationchange', fit);
    window.visualViewport?.addEventListener('resize', fit);
    return () => {
      window.removeEventListener('resize', fit);
      window.removeEventListener('orientationchange', fit);
      window.visualViewport?.removeEventListener('resize', fit);
    };
  }, []);

  const onScroll = useCallback((e) => {
    const el = e.target;
    const bottom = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
    atBottomRef.current = bottom;
    setAtBottom(bottom);
    if (bottom) setUnreadFrom(null);
  }, []);

  const jumpToBottom = useCallback(() => {
    atBottomRef.current = true;
    setAtBottom(true);
    setUnreadFrom(null);
    const list = listRef.current;
    if (list) list.scrollTo({ top: list.scrollHeight, behavior: 'smooth' });
  }, []);

  const sendMessage = useCallback(async () => {
    const text = input.trim();
    if (!text) return;
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;

    setSending(true);
    setInput('');
    try {
      await transport.sendChat(text, 0, null, username);
      setMessages(prev => [...prev, {
        id: `own-${Date.now()}-${Math.random().toString(36).slice(2)}`,
        sender_id: username,
        sender_name: username,
        payload: text,
        timestamp: Date.now() / 1000,
        thread_id: null,
      }]);
      jumpToBottom();
      if (onActivity) onActivity();
    } catch {
      setInput(text);
    } finally {
      setSending(false);
      setTimeout(() => { if (inputRef.current) inputRef.current.focus(); });
    }
  }, [input, username, jumpToBottom]);

  const attachFile = useCallback(async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    e.target.value = '';
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    setAttaching(true);
    try {
      // Two people sending IMG_1234.jpg both succeed; the node picks a free name
      // and the message has to point at the one it chose.
      const ack = await transport.uploadFile(file);
      const storedAs = (ack && ack.stored_as) || file.name;
      await new Promise(r => setTimeout(r, 2500));
      if (onRefreshIndex) await onRefreshIndex();
      const ext = file.name.split('.').pop().toLowerCase();
      const ftype = ['jpg','jpeg','png','gif','webp','svg'].includes(ext) ? 'image'
        : ['mp4','webm','mkv','mov','avi'].includes(ext) ? 'video' : 'file';
      const structured = JSON.stringify({
        text: '', attachment: { filename: storedAs, size: file.size, type: ftype },
      });
      await transport.sendChat(structured, 0, null, username);
      setMessages(prev => [...prev, {
        id: `own-${Date.now()}-${Math.random().toString(36).slice(2)}`,
        sender_id: username, sender_name: username,
        payload: structured, timestamp: Date.now() / 1000, thread_id: null,
      }]);
      jumpToBottom();
    } catch (err) {
      alert(err.message);
    } finally {
      setAttaching(false);
    }
  }, [username, onRefreshIndex, jumpToBottom]);

  const onKeyDown = useCallback((e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  }, [sendMessage]);

  return html`
    <div class="chat-panel" ref=${panelRef}>
      <div class="chat-messages" ref=${listRef} onScroll=${onScroll}>
        ${hasMore && html`
          <div class="chat-older-row">
            <button class="chat-older-btn" onClick=${loadOlder} disabled=${loadingOlder}>
              ${loadingOlder
                ? html`<span class="spinner"></span>`
                : html`<${Icon} name="chevron" cls="chat-older-icon" />`}
              ${' '}${t('chat.load_older', { n: CHAT_OLDER_PAGE })}
            </button>
          </div>
        `}
        ${!hasMore && messages.length > 0 && html`
          <div class="chat-start">${t('chat.start_of_history')}</div>
        `}
        ${messages.length === 0 && html`
          <div class="chat-empty">${t('chat.empty')}</div>
        `}
        ${messages.map((m, i) => {
          const isOwn = m.sender_name === username || m.sender_id === username;
          const displayName = m.sender_name || '?';
          const prev = messages[i - 1];
          const showSender = !isOwn && (i === 0 ||
            (prev.sender_name || prev.sender_id) !== (m.sender_name || m.sender_id));
          // A conversation read over several days is unreadable without them.
          const daySep = i === 0 || !_sameDay(prev.timestamp, m.timestamp)
            ? _dayLabel(m.timestamp) : null;
          const parsed = _parsePayload(m.payload);
          const att = parsed && parsed.attachment;
          return html`
            ${daySep && html`
              <div class="chat-day" key=${'d' + m.id}><span>${daySep}</span></div>
            `}
            ${unreadFrom && unreadFrom === m.id && html`
              <div class="chat-unread" key=${'u' + m.id}><span>${t('chat.unread')}</span></div>
            `}
            <div key=${m.id} class="chat-msg ${isOwn ? 'chat-msg-own' : ''}
                 ${showSender || daySep ? '' : 'chat-msg-tight'}">
              ${showSender && html`
                <div class="chat-sender">${displayName}</div>
              `}
              <div class="chat-bubble ${isOwn ? 'chat-bubble-own' : ''}">
                ${att ? html`
                  <div class="chat-attachment" style="cursor:pointer" onClick=${() => {
                    if (!onPreview) return;
                    const entry = entries.find(e => e.name === att.filename);
                    if (entry) onPreview(entry);
                  }}>
                    ${att.type === 'image'
                      ? html`<${ChatImage} filename=${att.filename} entries=${entries}
                              transportRef=${transportRef} gekRef=${gekRef} />`
                      : att.type === 'video'
                        ? html`<div class="chat-att-file">${'\u{1F3AC}'} ${att.filename}</div>`
                        : html`<div class="chat-att-file">${'\u{1F4CE}'} ${att.filename}</div>`
                    }
                    <div class="chat-att-size">${formatSize(att.size)}</div>
                  </div>
                ` : html`
                  <span class="chat-text">
                    ${linkify(parsed && typeof parsed.text === 'string'
                      ? parsed.text : m.payload)}
                  </span>
                `}
                <span class="chat-time">${formatTime(m.timestamp)}</span>
              </div>
            </div>
          `;
        })}
      </div>
      ${!atBottom && messages.length > 0 && html`
        <button class="chat-jump ${unreadFrom ? 'unread' : ''}" onClick=${jumpToBottom}>
          <${Icon} name="chevron" cls="chat-jump-icon" />
          ${' '}${unreadFrom ? t('chat.jump_new') : t('chat.jump_latest')}
        </button>
      `}
      <div class="chat-input-row">
        ${mayUpload && html`
        <label class="chat-attach" title="${t('chat.attach')}">
          ${attaching ? html`<span class="spinner"></span>`
                      : html`<${Icon} name="clip" />`}
          <input type="file" style="display:none" onChange=${attachFile} disabled=${attaching} />
        </label>
        `}
        <textarea class="chat-input" rows="1" ref=${inputRef}
          placeholder="${t('chat.placeholder')}"
          value=${input}
          onInput=${e => setInput(e.target.value)}
          onKeyDown=${onKeyDown}
          disabled=${sending} />
        <button class="chat-send" onClick=${sendMessage}
          disabled=${sending || !input.trim()}>
          ${t('chat.send')}
        </button>
      </div>
    </div>
  `;
}

// ── Video Player (MSE streaming) ────────────────────────────────────────

function _mseSupported(codec) {
  if (!window.MediaSource) return false;
  const mime = `video/mp4; codecs="${codec}"`;
  return MediaSource.isTypeSupported(mime);
}

/** Seconds as h:mm:ss, or m:ss under an hour. */
function formatClock(seconds) {
  const s = Math.max(0, Math.floor(seconds || 0));
  const h = Math.floor(s / 3600);
  const m = Math.floor((s % 3600) / 60);
  const sec = String(s % 60).padStart(2, '0');
  return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${sec}` : `${m}:${sec}`;
}

/**
 * Where *this account on this device* last left off in a given file.
 *
 * localStorage rather than the node: it needs no protocol, no storage anyone
 * else has to keep, and nothing new learns what you watch. The cost is that
 * the position does not follow you from the laptop to the phone.
 *
 * The account has to be in the key. Without it the position is per *device* —
 * so a second person signing in on the same machine was offered "resume where
 * you left off" in a film they had never opened, which is both wrong and a
 * small disclosure of what someone else watches. Found by signing in with a
 * fresh account and being offered a resume point.
 */
function resumeKey(fileId) {
  const auth = loadAuth();
  return auth && auth.userId ? `mb:pos:${auth.userId}:${fileId}` : null;
}

function readResumePosition(fileId) {
  try {
    const key = resumeKey(fileId);
    if (!key) return 0;
    const raw = localStorage.getItem(key);
    const at = raw ? parseFloat(raw) : 0;
    return Number.isFinite(at) && at > RESUME_MIN_S ? at : 0;
  } catch {
    return 0;   // private browsing, or storage disabled
  }
}

function writeResumePosition(fileId, at, duration) {
  try {
    const key = resumeKey(fileId);
    if (!key) return;
    if (!Number.isFinite(at) || at < RESUME_MIN_S
        || (duration && at > duration * RESUME_MAX_FRACTION)) {
      localStorage.removeItem(key);
      return;
    }
    localStorage.setItem(key, String(Math.floor(at)));
  } catch { /* nothing to be done, and nothing worth failing over */ }
}

/**
 * Drop the positions written before they were scoped to an account.
 *
 * Re-keying them is not possible — there is no record of whose they were, and
 * guessing would hand them to whoever signs in next, which is the bug. They go.
 */
function purgeUnscopedResumePositions() {
  try {
    const stale = [];
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      // `mb:pos:<file>` is the old shape; `mb:pos:<user>:<file>` is current.
      if (key && key.startsWith('mb:pos:') && key.split(':').length === 3) {
        stale.push(key);
      }
    }
    stale.forEach((key) => localStorage.removeItem(key));
  } catch { /* storage disabled: nothing was written either */ }
}

purgeUnscopedResumePositions();

function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) {
  const [dlBusy, setDlBusy] = useState(false);
  const [phase, setPhase] = useState('loading');
  const [error, setError] = useState('');
  const videoRef = useRef(null);
  const msRef = useRef(null);
  const sbRef = useRef(null);
  const blobUrlRef = useRef(null);
  const queueRef = useRef([]);
  const appendingRef = useRef(false);
  const endedRef = useRef(false);
  const durationRef = useRef(0);
  // Segments the node is allowed to have in flight but has not sent yet, and
  // when we last said anything to it at all.
  const outstandingRef = useRef(0);
  const lastPokeRef = useRef(0);
  // Diagnostics reported to the node: how many appends the browser refused for
  // want of room, and whether the element itself says it is starved.
  const quotaRef = useRef(0);
  const stalledRef = useRef(false);
  // Seeking. `awaitingInit` is true from the moment we ask the node to restart
  // somewhere else until its new `stream_init` arrives: the channel is ordered,
  // so everything in between belongs to the stream we just abandoned and would
  // otherwise be appended on top of the new one. `seekTarget` is where to put
  // the playhead once the buffer actually covers it.
  const awaitingInitRef = useRef(false);
  const seekTargetRef = useRef(null);
  const seekTimerRef = useRef(null);
  // The seek is built inside the effect, where the transport and `cancelled`
  // live; the render needs to reach it for "start from the beginning".
  const requestSeekRef = useRef(null);
  const [resumedFrom, setResumedFrom] = useState(0);
  const [castActive, setCastActive] = useState(false);
  const [castUrl, setCastUrl] = useState(null);
  const [castPickerOpen, setCastPickerOpen] = useState(false);
  const [castDevices, setCastDevices] = useState([]);
  const [castScanning, setCastScanning] = useState(false);
  const [castDeviceName, setCastDeviceName] = useState(null);
  const castActiveRef = useRef(false);
  const castCodecRef = useRef(null);
  const initSegmentRef = useRef(null);
  const castRestartPendingRef = useRef(false);
  const castDeviceRef = useRef(null);
  const castRestartGenRef = useRef(0);
  const landingPlayheadRef = useRef(false);

  /**
   * The buffered range the playhead is actually in, or null.
   *
   * Seeking makes the buffer discontinuous, and "the last range" stops meaning
   * "the one being watched" the moment there is more than one: measuring the
   * read-ahead against a range on the far side of a gap reports a full buffer
   * while the player starves.
   */
  const currentRange = useCallback(() => {
    const sb = sbRef.current;
    const v = videoRef.current;
    if (!sb || !v) return null;
    try {
      const t = v.currentTime;
      for (let i = 0; i < sb.buffered.length; i++) {
        // Half a second of slack: the playhead sits exactly on a boundary
        // often enough, and a strict test there reports nothing buffered.
        if (t >= sb.buffered.start(i) - 0.5 && t <= sb.buffered.end(i) + 0.5) {
          return [sb.buffered.start(i), sb.buffered.end(i)];
        }
      }
    } catch { /* the SourceBuffer went away under us */ }
    return null;
  }, []);

  /**
   * Drop what has already been watched.
   *
   * A SourceBuffer is not a file: browsers cap it at a few hundred megabytes
   * and refuse the append that goes past. Keeping a minute behind the playhead
   * is enough for a small seek backwards and bounded for a three-hour film.
   */
  const evictBehind = useCallback(() => {
    const sb = sbRef.current;
    const v = videoRef.current;
    if (!sb || !v || sb.updating || !sb.buffered.length) return false;
    const keepFrom = Math.max(0, v.currentTime - BUFFER_BEHIND_S);
    // The range being watched, not the first one: after a seek backwards the
    // first range is somewhere else entirely, and removing from its start to
    // just behind the playhead would take out everything in between —
    // including what is playing.
    const range = currentRange();
    const start = range ? range[0] : sb.buffered.start(0);
    if (keepFrom - start < 10) return false;
    try {
      sb.remove(start, keepFrom);
      return true;
    } catch {
      return false;
    }
  }, [currentRange]);

  /** Seconds of film held past the playhead. */
  const bufferedAhead = useCallback(() => {
    const v = videoRef.current;
    const range = currentRange();
    if (!v || !range) return 0;
    return Math.max(0, range[1] - v.currentTime);
  }, [currentRange]);

  const flushQueue = useCallback(() => {
    const sb = sbRef.current;
    if (!sb || appendingRef.current || sb.updating) return;
    if (queueRef.current.length === 0) {
      if (endedRef.current && msRef.current?.readyState === 'open') {
        try { msRef.current.endOfStream(); } catch {}
      }
      return;
    }
    appendingRef.current = true;
    const chunk = queueRef.current[0];
    try {
      sb.appendBuffer(chunk);
      queueRef.current.shift();
    } catch (e) {
      appendingRef.current = false;
      if (e.name === 'QuotaExceededError') {
        quotaRef.current += 1;
        // The segment stays at the head of the queue and is tried again once
        // there is room. Dropping it — which is what this used to do — leaves a
        // hole in the middle of the film and no error anywhere.
        if (!evictBehind()) {
          console.warn('[MSE] buffer full and nothing to evict yet');
        }
        return;
      }
      queueRef.current.shift();
      console.error('[MSE] appendBuffer error:', e);
    }
  }, [evictBehind]);

  /**
   * Decide whether the node may send more, and keep the pipeline moving.
   *
   * This is the only place credit is granted, and the only thing that can
   * restart a pipeline the buffer ceiling has stopped. That second job is why
   * it exists: an append refused for quota fires no `updateend`, so it grants
   * no credit, so the node sends nothing, so no segment arrives to call
   * `flushQueue` again. Every wakeup the append path had was downstream of the
   * append that just failed — the player deadlocked against itself and sat on
   * "buffering" for good, which is what a 500 MB film did at around 100 MB.
   *
   * So the clock drives this, not the data.
   */
  const pump = useCallback(() => {
    if (awaitingInitRef.current) return;
    const transport = transportRef.current;
    evictBehind();
    flushQueue();
    if (endedRef.current && queueRef.current.length === 0) return;
    if (!transport || !transport.connected) return;

    if (bufferedAhead() > BUFFER_AHEAD_S
        || queueRef.current.length > QUEUE_HIGH_WATER) {
      // Far enough ahead. Grant nothing, but do not go silent: two minutes of
      // silence is how the node decides nobody is watching, and pausing a film
      // for two minutes is an ordinary thing to do.
      const now = Date.now();
      if (now - lastPokeRef.current > CREDIT_KEEPALIVE_MS) {
        lastPokeRef.current = now;
        transport.grantStreamCredit(0);
      }
      return;
    }

    // Top the window back up to what is allowed in flight, rather than paying
    // off everything owed at once. Called on every arriving segment as well as
    // on the clock, so credit trickles out as room appears instead of being
    // released in one gulp when the buffer finally drains.
    const room = STREAM_WINDOW - outstandingRef.current;
    if (room > 0) {
      outstandingRef.current += room;
      lastPokeRef.current = Date.now();
      transport.grantStreamCredit(room);
    }
  }, [evictBehind, flushQueue, bufferedAhead]);

  useEffect(() => {
    let cancelled = false;
    // Reset here, not in the teardown of the run before: switching video while
    // an append was in flight left `appendingRef` true, and flushQueue bails
    // out on it. The new SourceBuffer then never appended anything, so no
    // `updateend` ever cleared the flag, no credit went back to the node, and
    // the player sat on "buffering" for good. `endedRef` surviving is the same
    // shape of bug — the next stream would call endOfStream() the first time
    // its queue ran dry and truncate the film.
    appendingRef.current = false;
    endedRef.current = false;
    queueRef.current = [];
    outstandingRef.current = 0;
    lastPokeRef.current = Date.now();
    quotaRef.current = 0;
    stalledRef.current = false;
    // The same shape again, and the seek refs are worse than the others.
    // Switching film while a seek was in flight leaves `awaitingInit` true,
    // and only reinitAt() ever lowers it — which the next film does not go
    // through, because it builds a new SourceBuffer. Every segment of the new
    // film is then dropped as though it belonged to the one we left, for good.
    // A stale `seekTarget` is milder: the new film jumps to a position from
    // the old one the moment that much is buffered.
    awaitingInitRef.current = false;
    seekTargetRef.current = null;
    clearTimeout(seekTimerRef.current);
    const transport = transportRef.current;
    if (!transport || !transport.connected) {
      setError(t('video.err_transport'));
      setPhase('error');
      return;
    }

    const onStarved = () => { stalledRef.current = true; pump(); };
    const onFed = () => { stalledRef.current = false; };

    /** The buffered ranges, short enough for a log line. */
    const describeRanges = () => {
      const sb = sbRef.current;
      if (!sb) return '(no buffer)';
      try {
        let s = '';
        for (let i = 0; i < sb.buffered.length; i++) {
          s += `${sb.buffered.start(i).toFixed(0)}-${sb.buffered.end(i).toFixed(0)} `;
        }
        return s.trim() || '(empty)';
      } catch {
        return '?';
      }
    };

    /**
     * Ask the node to restart the film somewhere else.
     *
     * Debounced, because dragging the scrubber fires `seeking` continuously and
     * each request kills an ffmpeg and spawns another. Only the position the
     * finger stops on is worth acting on.
     */
    const requestSeek = (target) => {
      clearTimeout(seekTimerRef.current);
      seekTimerRef.current = setTimeout(() => {
        const t = transportRef.current;
        if (cancelled || !t || !t.connected) return;
        // Everything arriving from here until the new `stream_init` belongs to
        // the stream being abandoned. The channel is ordered, so this flag is
        // enough to tell them apart without a sequence number in the protocol.
        // Rare enough to report every time, and the node logs it at INFO. A
        // seek nobody asked for is the kind of thing only this line can show:
        // from the node's side it is indistinguishable from a viewer dragging
        // the scrubber.
        t.sendStreamDiag({
          event: 'seek', target: +target.toFixed(1),
          t: videoRef.current ? +videoRef.current.currentTime.toFixed(1) : null,
          ready: videoRef.current ? videoRef.current.readyState : null,
          offset: sbRef.current ? sbRef.current.timestampOffset : null,
          ranges: describeRanges(),
        });
        awaitingInitRef.current = true;
        seekTargetRef.current = target;
        outstandingRef.current = STREAM_WINDOW;
        setPhase('loading');
        console.log('[seek] request', +target.toFixed(1), 'outstanding:', STREAM_WINDOW);
        t.requestStream(entry.id, STREAM_WINDOW, target);
      }, SEEK_DEBOUNCE_MS);
    };
    requestSeekRef.current = requestSeek;

    /**
     * Move the playhead onto a seek once the data for it has arrived.
     *
     * Setting `currentTime` into a region that is not buffered yet leaves the
     * element waiting with nothing to show, and on a seek backwards it would
     * be overwritten by the playhead the browser restores. So the position is
     * remembered and applied on the first append that actually covers it.
     */
    const landPlayhead = () => {
      const target = seekTargetRef.current;
      const v = videoRef.current, sb = sbRef.current;
      if (target === null || !v || !sb) return;
      try {
        for (let i = 0; i < sb.buffered.length; i++) {
          const a = sb.buffered.start(i), b = sb.buffered.end(i);
          if (target >= a - 1 && target < b) {
            seekTargetRef.current = null;
            // ffmpeg lands on the keyframe at or before what we asked for, so
            // the range can begin slightly later than the target; never seek
            // behind what is actually there.
            if (Math.abs(v.currentTime - target) > 0.5) {
              landingPlayheadRef.current = true;
              v.currentTime = Math.max(target, a);
            }
            v.play().catch(() => {});
            return;
          }
        }
      } catch { /* the SourceBuffer went away */ }
    };

    /** Wait for whatever the SourceBuffer is doing to finish. */
    const settled = (sb) => new Promise((resolve) => {
      if (!sb.updating) return resolve();
      sb.addEventListener('updateend', resolve, { once: true });
    });

    /**
     * Put the SourceBuffer back to an empty state that starts at `start`.
     *
     * Everything buffered is dropped rather than kept alongside the new
     * material. A discontinuous buffer is legal and every piece of code that
     * reads `buffered` then has to reason about which range it means — the
     * eviction, the read-ahead, the seek test — for the sake of a few
     * megabytes of film the viewer has just navigated away from.
     *
     * `abort()` first: ffmpeg was killed mid-fragment, so the parser is
     * holding half of one, and appending the next stream's header on top of
     * that is a decode error.
     */
    const reinitAt = async (start) => {
      const sb = sbRef.current;
      if (!sb) return;
      try { sb.abort(); } catch { /* not in a state that needs it */ }
      await settled(sb);
      try {
        sb.remove(0, Infinity);
        await settled(sb);
      } catch { /* nothing buffered */ }
      // ffmpeg restarts its timestamps at zero however far in we asked it to
      // seek, so this is what puts the fragments back on the film's timeline.
      try { sb.timestampOffset = start; } catch { /* older browsers */ }
      const tr = transportRef.current;
      if (tr) {
        tr.sendStreamDiag({
          event: 'reinit', target: start, offset: sb.timestampOffset,
          t: videoRef.current ? +videoRef.current.currentTime.toFixed(1) : null,
          ranges: describeRanges(),
        });
      }
      queueRef.current = [];
      appendingRef.current = false;
      endedRef.current = false;
      quotaRef.current = 0;
      awaitingInitRef.current = false;
      seekTargetRef.current = start;
      console.log('[seek] reinitAt done, start:', start, 'outstanding:', outstandingRef.current, 'queue:', queueRef.current.length);
      setPhase('streaming');
      pump();
    };

    const onSeeking = () => {
      if (landingPlayheadRef.current) {
        landingPlayheadRef.current = false;
        return;
      }
      const v = videoRef.current;
      if (!v || cancelled) return;
      const target = v.currentTime;
      // Inside what is buffered, the browser handles it and the node need not
      // hear about it at all — unless a cast is active, because the relay
      // cannot seek within its HTTP stream and must be restarted.
      if (!castActiveRef.current) {
        const sb = sbRef.current;
        if (sb) {
          try {
            for (let i = 0; i < sb.buffered.length; i++) {
              if (target >= sb.buffered.start(i) && target <= sb.buffered.end(i) - 0.5) {
                return;
              }
            }
          } catch { /* fall through and ask the node */ }
        }
      }
      requestSeek(target);
    };

    const startStream = async () => {
      transport.onStreamError = (msg) => {
        if (cancelled) return;
        // Say what the node said. Sitting on "buffering" with the reason
        // already delivered is the worst of both.
        setError(msg.detail || t('video.err_transport'));
        setPhase('error');
      };

      transport.onStreamInit = (msg) => {
        if (cancelled) return;
        if (msg.file_id && msg.file_id !== entry.id) return;
        const mime = `video/mp4; codecs="${msg.codec}"`;
        castCodecRef.current = msg.codec;

        if (!window.MediaSource || !MediaSource.isTypeSupported(mime)) {
          setError(t('video.err_mse', { codec: msg.codec }));
          setPhase('error');
          return;
        }

        durationRef.current = msg.duration || 0;

        // A second init on a live SourceBuffer is a seek landing, not a new
        // film. Reuse what is there: rebuilding the MediaSource would reset the
        // element's src, blank the picture and throw away the duration the
        // scrubber is drawn from.
        if (sbRef.current && msRef.current
            && msRef.current.readyState === 'open') {
          console.log('[seek] stream_init landed, start:', msg.start, 'awaitingInit:', awaitingInitRef.current);
          initSegmentRef.current = null;
          if (castActiveRef.current && platform.cast.available) {
            platform.cast.stop().catch(() => {});
            castRestartPendingRef.current = true;
          }
          reinitAt(msg.start || 0).catch(() => {
            setError(t('video.err_transport'));
            setPhase('error');
          });
          return;
        }

        // If we reach here during a seek (readyState was 'ended' after the
        // previous stream finished), the seek-landing path above could not run.
        // A fresh MediaSource is needed, but the seek state must still be reset
        // or awaitingInit stays true and every segment is dropped forever.
        awaitingInitRef.current = false;
        endedRef.current = false;
        appendingRef.current = false;
        queueRef.current = [];
        sbRef.current = null;
        initSegmentRef.current = null;
        if (castActiveRef.current && platform.cast.available) {
          platform.cast.stop().catch(() => {});
          castRestartPendingRef.current = true;
        }

        const ms = new MediaSource();
        msRef.current = ms;
        if (blobUrlRef.current) URL.revokeObjectURL(blobUrlRef.current);
        const url = URL.createObjectURL(ms);
        blobUrlRef.current = url;

        ms.addEventListener('sourceopen', () => {
          if (cancelled) return;
          if (durationRef.current > 0) {
            ms.duration = durationRef.current;
          }
          const sb = ms.addSourceBuffer(mime);
          sbRef.current = sb;
          // 'segments', not 'sequence': the fragments must land where they
          // belong on the film's timeline rather than one after another, or a
          // stream that started at 40 minutes would be buffered at zero and
          // the scrubber would lie about everything.
          sb.mode = 'segments';
          try { sb.timestampOffset = msg.start || 0; } catch { /* older browsers */ }
          if (msg.start) seekTargetRef.current = msg.start;
          transport.sendStreamDiag({
            event: 'first-init', target: msg.start || 0,
            offset: sb.timestampOffset, duration: durationRef.current,
            t: videoRef.current ? +videoRef.current.currentTime.toFixed(1) : null,
          });
          sb.addEventListener('updateend', () => {
            // No credit is granted here, deliberately. Appending is not the
            // same question as having room, and tying the two meant `remove()`
            // — which fires this event too — paid the node for the player's own
            // evictions. What may be in flight is decided from the buffer, in
            // pump(), and nowhere else.
            appendingRef.current = false;
            landPlayhead();
            pump();
          });
          setPhase('streaming');
          flushQueue();
        });

        if (videoRef.current) {
          videoRef.current.src = url;
          videoRef.current.addEventListener('seeking', onSeeking);
          videoRef.current.addEventListener('timeupdate', pump);
          // The element's own verdict. "buffering" on screen is this, and it
          // is the one thing the node cannot infer from a stream it is feeding.
          videoRef.current.addEventListener('waiting', onStarved);
          videoRef.current.addEventListener('stalled', onStarved);
          videoRef.current.addEventListener('playing', onFed);
          videoRef.current.addEventListener('canplay', onFed);
        }
      };

      transport.onStreamData = async (msg) => {
        if (cancelled) return;
        // A segment arrived, so it is no longer in flight — whatever we go on
        // to do with it. This has to come before every early return below, and
        // it did not: skipping the count for segments we discard leaks a slot
        // out of the window each time, and the window never grows back.
        //
        // `reinitAt` is asynchronous — it waits for two `updateend` events —
        // and a seek's first segments arrive during that gap and are dropped
        // by the flag below. Lose all eight and the player believes a full
        // window is in flight, grants nothing ever again, and the node waits
        // for credit that cannot come. A race, which is why the same seek
        // worked twice and hung on the third.
        outstandingRef.current = Math.max(0, outstandingRef.current - 1);
        if (awaitingInitRef.current) {
          console.log('[seek] dropping segment (awaitingInit), outstanding:', outstandingRef.current);
        }
        // Between asking for a seek and its `stream_init`, everything on the
        // channel is the film we just left. Same file, so `file_id` cannot
        // tell them apart — ordering can.
        if (awaitingInitRef.current) return;
        // Late segments from the stream we just left. The DataChannel is
        // ordered, so they arrive before the new stream's first segment and
        // would otherwise be decrypted against the wrong file — which fails,
        // loudly, in the console, for something that is simply not ours.
        if (msg.file_id && msg.file_id !== entry.id) return;
        try {
          const plaintext = await window.MeshBayCrypto.decryptChunkBin(
            gekRef.current, entry.id, msg.segment_index, msg.nonce, msg.ct);
          if (initSegmentRef.current === null) {
            initSegmentRef.current = plaintext;
            if (castRestartPendingRef.current && castActiveRef.current
                && platform.cast.available) {
              castRestartPendingRef.current = false;
              const gen = ++castRestartGenRef.current;
              const device = castDeviceRef.current;
              platform.cast.start({
                codec: castCodecRef.current,
                initSegment: plaintext,
              }).then(async (result) => {
                if (castRestartGenRef.current !== gen) return;
                if (!result) return;
                setCastUrl(result.url);
                const status = await platform.cast.status();
                if (status && status.chromecast && status.chromecast.connected) {
                  await platform.cast.chromecastReload({ mediaUrl: result.url });
                } else if (device) {
                  await platform.cast.chromecastConnect({
                    deviceId: device.id, mediaUrl: result.url,
                  });
                  setCastDeviceName(device.name);
                } else {
                  navigator.clipboard.writeText(result.url).catch(() => {});
                }
              }).catch((err) => {
                if (castRestartGenRef.current !== gen) return;
                console.error('[cast] restart failed:', err);
                platform.cast.stop().catch(() => {});
                setCastActive(false); castActiveRef.current = false;
                setCastUrl(null); setCastDeviceName(null);
              });
            }
          }
          if (castActiveRef.current && !castRestartPendingRef.current
              && platform.cast.available) {
            platform.cast.push(plaintext).catch(() => {});
          }
          queueRef.current.push(plaintext);
          // pump(), not flushQueue(): arriving data is the moment to top the
          // window back up, and that is what keeps the stream continuous.
          pump();
        } catch (e) {
          console.error('[MSE] decrypt error:', e);
        }
      };

      transport.onStreamEnd = (msg) => {
        if (cancelled) return;
        // The end of the previous film is not the end of this one.
        if (msg && msg.file_id && msg.file_id !== entry.id) return;
        // Nor is the end of the stream we abandoned by seeking: taking it
        // would call endOfStream() and truncate the film at the seek point.
        if (awaitingInitRef.current) return;
        endedRef.current = true;
        if (castActiveRef.current && platform.cast.available) {
          platform.cast.finish().catch(() => {});
        }
        flushQueue();
      };

      // The opening window, and the count that tracks it. Asking for more here
      // than pump() maintains would leave the node holding credit this side
      // does not know about, which is the whole window's worth of overshoot on
      // the very first breath of the stream.
      outstandingRef.current = STREAM_WINDOW;
      const resumeAt = readResumePosition(entry.id);
      if (resumeAt) setResumedFrom(resumeAt);
      transport.requestStream(entry.id, STREAM_WINDOW, resumeAt);
    };

    // Closing the tab, or backgrounding it on a phone, never runs a React
    // cleanup — so the node hears nothing and keeps transcoding. `pagehide`
    // fires in both cases and is the one event mobile browsers honour on the
    // way out; `visibilitychange` covers switching apps. The node stops the
    // stream by itself when the connection drops, but that costs a round of
    // detection, and this message is a single datagram already in flight.
    const leave = (why) => {
      const t = transportRef.current;
      console.log('[MeshBay] stopStream:', why);
      if (t && t.connected) t.stopStream();
    };
    const onPageHide = () => leave('pagehide');
    // NOT wired to stopStream. Android fires visibilitychange when a video goes
    // fullscreen, so cutting the stream here killed the film the moment it was
    // watched properly. Logged only, until that is confirmed or ruled out.
    const onVisibility = () => {
      console.log('[MeshBay] visibilitychange:', document.visibilityState);
    };
    window.addEventListener('pagehide', onPageHide);
    document.addEventListener('visibilitychange', onVisibility);

    // `timeupdate` is silent while the film is paused, and the append path
    // cannot wake itself once the ceiling has refused a segment. This is the
    // clock that guarantees something is still driving the pipeline.
    const pumpTimer = setInterval(pump, 1000);

    // What the player sees, into the node's log. A hang on a phone shows the
    // node feeding a stream quite happily; the half that says otherwise is in
    // here, and there is no console to read it from.
    const diagTimer = setInterval(() => {
      const v = videoRef.current, sb = sbRef.current;
      const t = transportRef.current;
      if (!t || !v) return;
      // Cheap, and the only thing that makes "resume where I stopped" work
      // when the tab is closed rather than the player.
      if (!v.paused) {
        writeResumePosition(entry.id, v.currentTime, durationRef.current);
      }
      let ranges = '';
      try {
        for (let i = 0; sb && i < sb.buffered.length; i++) {
          ranges += `${sb.buffered.start(i).toFixed(0)}-${sb.buffered.end(i).toFixed(0)} `;
        }
      } catch { ranges = '?'; }
      t.sendStreamDiag({
        t: +v.currentTime.toFixed(1),
        ahead: +bufferedAhead().toFixed(1),
        ranges: ranges.trim(),
        ready: v.readyState,       // 0 = nothing, 4 = enough to play through
        paused: v.paused,
        stalled: stalledRef.current,
        q: queueRef.current.length,
        inflight: outstandingRef.current,
        appending: appendingRef.current,
        updating: sb ? sb.updating : null,
        quota: quotaRef.current,
        ms: msRef.current ? msRef.current.readyState : null,
        err: v.error ? `${v.error.code}:${v.error.message}` : null,
      });
    }, 5000);

    startStream().catch(err => {
      if (!cancelled) { setError(err.message); setPhase('error'); }
    });

    return () => {
      cancelled = true;
      clearInterval(pumpTimer);
      clearInterval(diagTimer);
      clearTimeout(seekTimerRef.current);
      // Closing the player is the commonest way to stop watching, so this is
      // the write that matters most.
      if (videoRef.current) {
        writeResumePosition(entry.id, videoRef.current.currentTime,
                            durationRef.current);
      }
      if (castActiveRef.current && platform.cast.available) {
        platform.cast.chromecastDisconnect().catch(() => {});
        platform.cast.stop().catch(() => {});
        castActiveRef.current = false;
      }
      window.removeEventListener('pagehide', onPageHide);
      document.removeEventListener('visibilitychange', onVisibility);
      if (videoRef.current) {
        videoRef.current.removeEventListener('seeking', onSeeking);
        videoRef.current.removeEventListener('timeupdate', pump);
        videoRef.current.removeEventListener('waiting', onStarved);
        videoRef.current.removeEventListener('stalled', onStarved);
        videoRef.current.removeEventListener('playing', onFed);
        videoRef.current.removeEventListener('canplay', onFed);
      }
      if (transport) {
        // Tell the node first: dropping the handlers only makes us deaf, and a
        // stream nobody is listening to still occupies a transcode slot.
        transport.stopStream();
        transport.onStreamInit = null;
        transport.onStreamData = null;
        transport.onStreamEnd = null;
        transport.onStreamError = null;
      }
      // The queue can hold several megabytes of decrypted video.
      queueRef.current = [];
      const ms = msRef.current;
      if (ms && ms.readyState === 'open') {
        try { ms.endOfStream(); } catch { /* already ended */ }
      }
      if (blobUrlRef.current) {
        URL.revokeObjectURL(blobUrlRef.current);
        blobUrlRef.current = null;
      }
      sbRef.current = null;
      msRef.current = null;
    };
  }, [entry, flushQueue, pump]);

  useEffect(() => {
    if (phase === 'streaming' && videoRef.current) {
      videoRef.current.play().catch(() => {});
    }
  }, [phase]);

  useEffect(() => {
    return () => {
      if (blobUrlRef.current) {
        URL.revokeObjectURL(blobUrlRef.current);
        blobUrlRef.current = null;
      }
    };
  }, []);

  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  return html`
    <div class="video-overlay" onClick=${(e) => {
      if (e.target.classList.contains('video-overlay')) onClose();
    }}>
      <div class="video-top-bar">
        <span class="video-title">${entry.name} (${formatSize(entry.size)})</span>
        ${platform.capabilities.lanCast && html`
          <div class="cast-wrapper" style="position:relative">
            <button class="video-close ${castActive ? 'cast-active' : ''}"
              onClick=${async () => {
                if (castActive) {
                  await platform.cast.chromecastDisconnect().catch(() => {});
                  await platform.cast.stop();
                  setCastActive(false); castActiveRef.current = false;
                  setCastUrl(null);
                  setCastDeviceName(null);
                  castDeviceRef.current = null;
                } else if (castCodecRef.current && initSegmentRef.current) {
                  if (castPickerOpen) {
                    setCastPickerOpen(false);
                  } else {
                    setCastPickerOpen(true);
                    setCastScanning(true);
                    setCastDevices([]);
                    platform.cast.discover().then((devices) => {
                      setCastDevices(devices || []);
                      setCastScanning(false);
                    }).catch(() => setCastScanning(false));
                  }
                }
              }}
              title="${castActive ? t('cast.stop') : t('cast.start')}">
              <${Icon} name="cast" /></button>
            ${castPickerOpen && html`
              <div class="cast-picker">
                ${castScanning && html`
                  <div class="cast-picker-item cast-picker-scanning">
                    <span class="spinner" style="width:14px;height:14px"></span>
                    ${t('cast.scanning')}
                  </div>
                `}
                ${castDevices.map(d => html`
                  <button class="cast-picker-item" onClick=${() => {
                    setCastPickerOpen(false);
                    setCastDeviceName(d.name);
                    setCastActive(true); castActiveRef.current = true;
                    castRestartPendingRef.current = true;
                    castDeviceRef.current = d;
                    if (videoRef.current && requestSeekRef.current) {
                      requestSeekRef.current(videoRef.current.currentTime);
                    }
                  }}>
                    <${Icon} name="cast" /> ${d.name}
                  </button>
                `)}
                ${!castScanning && castDevices.length === 0 && html`
                  <div class="cast-picker-item cast-picker-empty">
                    ${t('cast.no_devices')}
                  </div>
                `}
                <div class="cast-picker-sep"></div>
                <button class="cast-picker-item" onClick=${async () => {
                  setCastPickerOpen(false);
                  setCastActive(true); castActiveRef.current = true;
                  castRestartPendingRef.current = true;
                  if (videoRef.current && requestSeekRef.current) {
                    requestSeekRef.current(videoRef.current.currentTime);
                  }
                }}>
                  <${Icon} name="clip" /> ${t('cast.copy_url')}
                </button>
              </div>
            `}
          </div>
        `}
        ${castUrl && html`
          <span class="cast-status-label">
            ${castDeviceName
              ? castDeviceName
              : html`<input class="cast-url-input" readOnly value=${castUrl}
                  onClick=${(e) => {
                    e.target.select();
                    navigator.clipboard.writeText(castUrl).catch(() => {});
                  }}
                  title="${t('cast.copy_url')}" />`
            }
          </span>
        `}
        ${onDownload && html`
          <button class="video-close ${dlBusy ? 'dl-active' : ''}" disabled=${dlBusy}
            onClick=${() => {
              if (!dlBusy) {
                setDlBusy(true);
                onDownload();
                setTimeout(() => setDlBusy(false), 1500);
              }
            }}
            title="${t('group.download')}">
            ${dlBusy
              ? html`<span class="spinner"></span>`
              : html`<${Icon} name="download" />`}</button>
        `}
        <button class="video-close" onClick=${onClose} title="${t('video.close')}">
          <${Icon} name="close" /></button>
      </div>

      ${phase === 'loading' && html`
        <div class="video-loading">
          <div class="video-loading-label">
            <span class="spinner"></span>${' '}${t('video.buffering')}
          </div>
        </div>
      `}

      ${(phase === 'streaming' || phase === 'loading') && html`
        <div class="video-container">
          <video ref=${videoRef} controls autoplay />
          ${resumedFrom > 0 && html`
            <div class="video-resumed">
              ${t('video.resumed_at', { time: formatClock(resumedFrom) })}
              <button class="linklike" onClick=${() => {
                setResumedFrom(0);
                writeResumePosition(entry.id, 0, durationRef.current);
                if (requestSeekRef.current) requestSeekRef.current(0);
              }}>${t('video.from_start')}</button>
            </div>
          `}
        </div>
      `}

      ${phase === 'error' && html`
        <div class="video-error">${error}</div>
      `}
    </div>
  `;
}

// ── Search Page (cross-group file search) ───────────────────────────────────

/**
 * "3 hours ago", in the reader's language.
 *
 * The search page needs it because its results come from a cache: a file that
 * was deleted an hour ago is still listed until the group is opened again, and
 * the honest thing is to say how old the answer is rather than to imply it is
 * live.
 */
function formatAgo(ts) {
  if (!ts) return '';
  const rtf = new Intl.RelativeTimeFormat(getLocale(), { numeric: 'auto' });
  let delta = (ts - Date.now()) / 1000;
  const steps = [['second', 60], ['minute', 60], ['hour', 24],
                 ['day', 7], ['week', 4.35], ['month', 12], ['year', Infinity]];
  for (const [unit, span] of steps) {
    if (Math.abs(delta) < span || span === Infinity) {
      return rtf.format(Math.round(delta), unit);
    }
    delta /= span;
  }
  return '';
}

function SearchPage() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);
  const [searched, setSearched] = useState(false);

  const doSearch = useCallback(async (q) => {
    const term = q.trim().toLowerCase();
    if (!term) { setResults([]); setSearched(false); return; }
    const indexes = await getAllCachedIndexes();
    const hits = [];
    for (const idx of indexes) {
      for (const e of (idx.entries || [])) {
        if (e.name.toLowerCase().includes(term) ||
            (e.path && e.path.toLowerCase().includes(term))) {
          hits.push({ ...e, groupId: idx.groupId, groupName: idx.groupName,
                      syncedAt: idx.cachedAt });
        }
      }
    }
    setResults(hits);
    setSearched(true);
  }, []);

  const onInput = useCallback((e) => {
    const q = e.target.value;
    setQuery(q);
    doSearch(q);
  }, [doSearch]);

  return html`
    <div>
      <h2>${t('search.title')}</h2>
      <div class="file-toolbar" style="margin-bottom:16px">
        <input type="text" class="admin-search" style="width:100%"
          placeholder="${t('search.placeholder')}"
          value=${query} onInput=${onInput} autofocus />
      </div>
      ${searched && results.length === 0 && html`
        <p class="page-message">${t('search.no_results')}</p>
      `}
      ${results.length > 0 && html`
        <table class="file-table">
          <thead>
            <tr>
              <th></th>
              <th>${t('group.col_name')}</th>
              <th>${t('group.col_size')}</th>
              <th>${t('search.col_group')}</th>
              <th>${t('group.col_type')}</th>
            </tr>
          </thead>
          <tbody>
            ${results.map(r => html`
              <tr class="file-row" key=${r.id + r.groupId}>
                <td>${FILE_ICONS[r.type] || FILE_ICONS.other}</td>
                <td class="file-name">
                  <a href="#/group/${r.groupId}" style="color:inherit">${r.name}</a>
                </td>
                <td class="file-size">${formatSize(r.size)}</td>
                <td>
                  <a href="#/group/${r.groupId}" class="badge">${r.groupName || r.groupId.slice(0, 8)}</a>
                  ${r.syncedAt && html`
                    <div class="search-synced">
                      ${t('search.synced', { ago: formatAgo(r.syncedAt) })}
                    </div>
                  `}
                </td>
                <td class="file-type">${r.type}</td>
              </tr>
            `)}
          </tbody>
        </table>
        <p class="settings-value" style="margin-top:8px">
          ${t('search.result_count', { n: results.length })}
        </p>
      `}
      ${!searched && html`
        <p class="page-message">${t('search.hint')}</p>
      `}
      <p class="settings-hint" style="margin-top:12px">${t('search.cache_note')}</p>
    </div>
  `;
}

// ── Settings Page ───────────────────────────────────────────────────────────

const THEME_OPTIONS = ['light', 'dark', 'system'];

// ── Profile Page ────────────────────────────────────────────────────────────
//
// Split out of Settings: these four are about *you* — who the account is, the
// node you operate, the node identities this browser has pinned, and closing
// the account. Settings is about how the application behaves. Mixing them put
// an irreversible button two scrolls under a theme picker.

function ProfilePage({ user, onLogout }) {
  const [nodeKey, setNodeKey] = useState('');
  const [currentNodeKey, setCurrentNodeKey] = useState(null);
  const [nodeKeyStatus, setNodeKeyStatus] = useState('');
  const [nodeKeyLoading, setNodeKeyLoading] = useState(false);
  const [email, setEmail] = useState('');
  const [emailDraft, setEmailDraft] = useState('');
  const [emailEditing, setEmailEditing] = useState(false);
  const [emailSaving, setEmailSaving] = useState(false);
  const [emailStatus, setEmailStatus] = useState('');
  const [pinCount, setPinCount] = useState(
    () => (window.MeshBayTransport?.pinnedNodeCount?.() ?? 0));
  const [delOpen, setDelOpen] = useState(false);
  const [delPass, setDelPass] = useState('');
  const [delError, setDelError] = useState('');
  const [deleting, setDeleting] = useState(false);

  const deleteAccount = useCallback(async (e) => {
    e.preventDefault();
    setDeleting(true);
    setDelError('');
    try {
      const authKey = await window.MeshBayKeys.deriveAuthKey(delPass, user.username);
      await hubFetch('/v1/users/me', {
        method: 'DELETE', token: user.token, body: { auth_key: authKey },
      });
      onLogout();
    } catch (err) {
      setDelError(err.message);
    } finally {
      setDeleting(false);
    }
  }, [delPass, user]);

  const clearPins = useCallback(() => {
    window.MeshBayTransport?.clearNodePin?.();
    setPinCount(window.MeshBayTransport?.pinnedNodeCount?.() ?? 0);
  }, []);

  useEffect(() => {
    hubFetch('/v1/users/me', { token: user.token })
      .then(data => {
        if (data.email) { setEmail(data.email); setEmailDraft(data.email); }
      })
      .catch(() => {});
    hubFetch(`/v1/users/${user.username}/pubkeys`, { token: user.token })
      .then(data => {
        if (data.pk_node_ed25519) setCurrentNodeKey(data.pk_node_ed25519);
      })
      .catch(() => {});
  }, [user.username, user.token]);

  const saveEmail = useCallback(async () => {
    const val = emailDraft.trim();
    if (!val || val === email) { setEmailEditing(false); return; }
    setEmailSaving(true);
    setEmailStatus('');
    try {
      await hubFetch('/v1/users/me', {
        method: 'PATCH', token: user.token, body: { email: val },
      });
      setEmail(val);
      setEmailEditing(false);
      setEmailStatus(t('settings.email_saved'));
      setTimeout(() => setEmailStatus(''), 3000);
    } catch (e) {
      setEmailStatus(e.message);
    } finally {
      setEmailSaving(false);
    }
  }, [emailDraft, email, user.token]);

  const submitNodeKey = useCallback(async () => {
    const key = nodeKey.trim();
    if (!key) return;
    setNodeKeyLoading(true);
    setNodeKeyStatus('');
    try {
      await hubFetch('/v1/users/me/node_key', {
        method: 'PUT', token: user.token,
        body: { pk_node_ed25519: key },
      });
      setCurrentNodeKey(key);
      setNodeKey('');
      setNodeKeyStatus(t('settings.node_key_success'));
    } catch (e) {
      setNodeKeyStatus(e.message);
    } finally {
      setNodeKeyLoading(false);
    }
  }, [nodeKey, user.token]);

  return html`
    <div>
      <h2>${t('profile.title')}</h2>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.profile')}</h3>
        <div class="settings-row">
          <span class="settings-label">${t('settings.username')}</span>
          <span class="settings-value">${user.username}</span>
        </div>
        <div class="settings-row">
          <span class="settings-label">${t('settings.email')}</span>
          ${emailEditing
            ? html`<span style="display:flex;gap:8px;align-items:center">
                <input type="email" value=${emailDraft}
                  onInput=${e => setEmailDraft(e.target.value)}
                  onKeyDown=${e => e.key === 'Enter' && saveEmail()}
                  style="font-size:0.9em;padding:4px 8px;border:1px solid var(--border);border-radius:4px" />
                <button class="admin-btn" onClick=${saveEmail}
                  disabled=${emailSaving}>${t('settings.email_save')}</button>
                <button class="btn-secondary" onClick=${() => {
                  setEmailEditing(false); setEmailDraft(email);
                }}>${t('settings.cancel')}</button>
              </span>`
            : html`<span style="display:flex;gap:8px;align-items:center">
                <span class="settings-value">${email || '—'}</span>
                <button class="link-btn" onClick=${() => setEmailEditing(true)}>
                  <${Icon} name="pencil" /></button>
              </span>`
          }
        </div>
        ${emailStatus && html`<p class="settings-hint" style="margin-top:4px">${emailStatus}</p>`}
      </div>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.node_key')}</h3>
        <p style="font-size:0.85em;color:var(--text-dim);margin-bottom:8px">${t('settings.node_key_desc')}</p>
        ${currentNodeKey && html`
          <div class="settings-row" style="margin-top:8px">
            <span class="settings-label">${t('settings.node_key_current')}</span>
            <code class="settings-value" style="font-size:0.8em;word-break:break-all">${currentNodeKey}</code>
          </div>
        `}
        <div style="display:flex;gap:8px;margin-top:10px;align-items:center">
          <input type="text" class="admin-search" style="flex:1;font-family:monospace;font-size:0.85em"
            placeholder=${t('settings.node_key_placeholder')}
            value=${nodeKey} onInput=${e => setNodeKey(e.target.value)}
            onKeyDown=${e => e.key === 'Enter' && submitNodeKey()} />
          <button class="admin-btn" onClick=${submitNodeKey}
            disabled=${nodeKeyLoading || !nodeKey.trim()}>
            ${t('settings.node_key_submit')}
          </button>
        </div>
        ${nodeKeyStatus && html`
          <p style="margin-top:6px;font-size:0.85em;color:${nodeKeyStatus === t('settings.node_key_success') ? 'var(--success)' : 'var(--error)'}">
            ${nodeKeyStatus}
          </p>
        `}
      </div>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.node_pins')}</h3>
        <p class="settings-hint">${t('settings.node_pins_hint')}</p>
        <div class="settings-row">
          <span class="settings-label">${t('settings.node_pins_count', { n: pinCount })}</span>
          <button class="btn-secondary" onClick=${clearPins} disabled=${pinCount === 0}>
            ${t('settings.node_pins_clear')}
          </button>
        </div>
      </div>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.danger')}</h3>
        <p class="settings-hint">${t('settings.delete_hint')}</p>
        ${delError && html`<p class="error-msg">${delError}</p>`}
        ${!delOpen
          ? html`<button class="btn-danger" onClick=${() => setDelOpen(true)}>
              ${t('settings.delete_account')}
            </button>`
          : html`
            <form onSubmit=${deleteAccount}>
              <p class="settings-hint">${t('settings.delete_confirm')}</p>
              <div style="display:flex;gap:8px;margin-top:8px">
                <input type="password" placeholder=${t('login.password')}
                  autocomplete="current-password"
                  value=${delPass} onInput=${e => setDelPass(e.target.value)} required />
                <button class="btn-danger" type="submit" disabled=${deleting}>
                  ${deleting ? '…' : t('settings.delete_confirm_btn')}
                </button>
                <button class="btn-secondary" type="button"
                  onClick=${() => { setDelOpen(false); setDelPass(''); setDelError(''); }}>
                  ${t('settings.cancel')}
                </button>
              </div>
            </form>
          `}
      </div>

    </div>
  `;
}

function SettingsPage({ user, theme, onThemeChange, groups, onPrefsChange }) {
  const [locale, setLoc] = useState(getLocale);
  const [muted, setMuted] = useState(
    () => Object.fromEntries((groups || []).map(g => [g.id, !!g.muted])));
  const [globalMute, setGlobalMute] = useState(false);
  const [defaultTab, setDefaultTab] = useState('chat');

  const onLocaleChange = useCallback((e) => {
    const code = e.target.value;
    setLocale(code);
    setLoc(code);
    window.location.reload();
  }, []);

  const onThemeSelect = useCallback((e) => {
    onThemeChange(e.target.value);
  }, [onThemeChange]);

  useEffect(() => {
    hubFetch('/v1/users/me/preferences', { token: user.token })
      .then(prefs => {
        if (prefs.notifications_disabled === 'true') setGlobalMute(true);
        if (prefs.default_tab) setDefaultTab(prefs.default_tab);
      })
      .catch(() => {});
  }, [user.token]);

  const toggleGlobalMute = useCallback(async () => {
    const next = !globalMute;
    setGlobalMute(next);
    try {
      await hubFetch('/v1/users/me/preferences/notifications_disabled', {
        method: 'PUT', token: user.token,
        body: { value: next ? 'true' : 'false' },
      });
      if (onPrefsChange) onPrefsChange({ notifications_disabled: next });
    } catch (err) {
      setGlobalMute(!next);
    }
  }, [globalMute, user.token, onPrefsChange]);

  const toggleMute = useCallback(async (gid) => {
    const next = !muted[gid];
    setMuted(prev => ({ ...prev, [gid]: next }));
    try {
      await hubFetch(`/v1/groups/${gid}/mute`, {
        method: 'POST', token: user.token, body: { muted: next },
      });
    } catch (err) {
      setMuted(prev => ({ ...prev, [gid]: !next }));
    }
  }, [muted, user.token]);

  const changeDefaultTab = useCallback(async (e) => {
    const val = e.target.value;
    setDefaultTab(val);
    try {
      await hubFetch('/v1/users/me/preferences/default_tab', {
        method: 'PUT', token: user.token,
        body: { value: val },
      });
      if (onPrefsChange) onPrefsChange({ default_tab: val });
    } catch { setDefaultTab(defaultTab); }
  }, [defaultTab, user.token, onPrefsChange]);

  const [dlMode, setDlMode] = useState(() => downloads.getMode());
  const [dlDir, setDlDir] = useState(null);
  const [dlError, setDlError] = useState('');
  // Read from the hub rather than written here: the two constants that used to
  // sit in this markup said 0.1.0 and MNP 0.1 long after both had moved on.
  const [hubInfo, setHubInfo] = useState(null);
  // On a desktop build, whether the OS is really holding the keys. Electron's
  // safeStorage falls back to a fixed key when no keyring is running — a
  // headless session, a minimal desktop — and does it silently. Somebody who
  // believes the OS is protecting their keys deserves to be told when it is not.
  const [keyBackend, setKeyBackend] = useState('');
  // Changing the hub after the first run. Without this a typo on the first
  // screen was permanent: the prompt only appears when no hub is set, so a
  // wrong one left editing a JSON file by hand as the only way out.
  const [hubInput, setHubInput] = useState('');
  const [hubError, setHubError] = useState('');
  useEffect(() => {
    if (!platform.secrets.available) return;
    platform.secrets.backend().then(setKeyBackend).catch(() => {});
  }, []);

  useEffect(() => {
    hubFetch('/v1/hub/version').then(setHubInfo).catch(() => {});
  }, []);

  useEffect(() => {
    // The desktop build remembers a path; the browser remembers a handle. Both
    // answer "where do downloads go", and the row below renders either.
    if (platform.folder.available) platform.folder.get().then(setDlDir);
    else downloads.savedDirectory().then(setDlDir);
  }, []);

  const pickFolder = useCallback(async () => {
    try {
      if (platform.folder.available) {
        const dir = await platform.folder.choose();
        if (dir) setDlDir(dir);
        return;
      }
      const handle = await downloads.chooseDirectory();
      setDlDir(handle);
    } catch (err) {
      // Reported where the folder controls are. This used to be written into
      // the node-key status, two sections away, where nobody was looking.
      if (err.name !== 'AbortError') setDlError(err.message);
    }
  }, []);


  return html`
    <div>
      <h2>${t('settings.title')}</h2>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.downloads')}</h3>
        ${(downloads.SUPPORTED || platform.folder.available) && html`
            <label class="settings-choice">
              <input type="radio" name="dlmode" checked=${dlMode === 'auto'}
                onChange=${() => { downloads.setMode('auto'); setDlMode('auto'); }} />
              <span>
                <strong>${t('settings.dl_auto')}</strong>
                <span class="settings-hint">${t('settings.dl_auto_hint')}</span>
              </span>
            </label>
            <label class="settings-choice">
              <input type="radio" name="dlmode" checked=${dlMode === 'ask'}
                onChange=${() => { downloads.setMode('ask'); setDlMode('ask'); }} />
              <span>
                <strong>${t('settings.dl_ask')}</strong>
                <span class="settings-hint">${t('settings.dl_ask_hint')}</span>
              </span>
            </label>
            <div class="settings-row" style="margin-top:10px">
              <span class="settings-label">
                ${dlDir ? t('settings.dl_folder',
                            { name: dlDir.name || String(dlDir) })
                        : t('settings.dl_no_folder')}
              </span>
              <span>
                <button class="admin-btn" onClick=${pickFolder}>
                  ${dlDir ? t('settings.dl_change') : t('settings.dl_choose')}
                </button>
                ${dlDir && !dlDir.isDefault && html`
                  <button class="btn-secondary" onClick=${async () => {
                    if (platform.folder.available) await platform.folder.forget();
                    else await downloads.forgetDirectory();
                    setDlDir(null);
                  }}>${t('settings.dl_forget')}</button>
                `}
              </span>
            </div>
            ${dlError && html`<p class="error-msg">${dlError}</p>`}
        `}
      </div>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.appearance')}</h3>
        <div class="settings-row">
          <span class="settings-label">${t('settings.theme')}</span>
          <select class="settings-select" value=${theme} onChange=${onThemeSelect}>
            <option value="light">${t('settings.theme_light')}</option>
            <option value="dark">${t('settings.theme_dark')}</option>
            <option value="system">${t('settings.theme_system')}</option>
          </select>
        </div>
        <div class="settings-row">
          <span class="settings-label">${t('settings.language')}</span>
          <select class="settings-select" value=${locale} onChange=${onLocaleChange}>
            ${LOCALES.map(l => html`
              <option key=${l.code} value=${l.code}>${l.name}</option>
            `)}
          </select>
        </div>
      </div>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.groups')}</h3>
        <div class="settings-row">
          <span class="settings-label">${t('settings.notif_global_disable')}</span>
          <label class="settings-value" style="cursor:pointer">
            <input type="checkbox" checked=${globalMute}
              onChange=${toggleGlobalMute} />
          </label>
        </div>
        ${!globalMute && html`
          <p class="settings-hint" style="margin-bottom:8px">${t('settings.notif_global_hint')}</p>
          ${groups.map(g => html`
            <div class="settings-row" key=${g.id}>
              <span class="settings-label">${g.name}</span>
              <label class="settings-value" style="cursor:pointer">
                <input type="checkbox" checked=${!muted[g.id]}
                  onChange=${() => toggleMute(g.id)} />
                ${' '}${t('settings.notifications')}
              </label>
            </div>
          `)}
        `}
      </div>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.defaults')}</h3>
        <div class="settings-row">
          <span class="settings-label">${t('settings.default_tab')}</span>
          <select class="settings-select" value=${defaultTab}
            onChange=${changeDefaultTab}>
            <option value="chat">${t('group.tab_chat')}</option>
            <option value="files">${t('group.tab_files')}</option>
            <option value="settings">${t('group.tab_settings')}</option>
          </select>
        </div>
        <p class="settings-hint">${t('settings.default_tab_hint')}</p>
      </div>

      ${platform.isNative && html`
        <div class="settings-section">
          <h3 class="settings-heading">${t('settings.hub_heading')}</h3>
          <div class="settings-row">
            <span class="settings-label">${t('settings.hub_current')}</span>
            <span class="settings-value">${platform.hubBase() || '—'}</span>
          </div>
          <p class="settings-hint">${t('settings.hub_hint')}</p>
          <form onSubmit=${async (e) => {
            e.preventDefault();
            setHubError('');
            try {
              await window.meshbay.setHubBase(hubInput.trim());
            } catch (err) { setHubError(platform.bridgeMessage(err)); }
          }} style="display:flex;gap:8px">
            <input type="text" placeholder=${platform.hubBase()}
              value=${hubInput} onInput=${e => setHubInput(e.target.value)} />
            <button class="admin-btn" type="submit">${t('settings.hub_change')}</button>
          </form>
          ${hubError && html`<p class="error-msg">${hubError}</p>`}
        </div>
      `}

      ${keyBackend && html`
        <div class="settings-section">
          <h3 class="settings-heading">${t('settings.keys_heading')}</h3>
          <div class="settings-row">
            <span class="settings-label">${t('settings.keys_where')}</span>
            <span class="settings-value">${keyBackend}</span>
          </div>
          ${keyBackend === 'unprotected_fallback' && html`
            <p class="error-msg">${t('settings.keys_unprotected')}</p>
          `}
          ${keyBackend === 'unavailable' && html`
            <p class="error-msg">${t('settings.keys_unavailable')}</p>
          `}
        </div>
      `}

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.about')}</h3>
        <div class="settings-row">
          <span class="settings-label">${t('settings.version')}</span>
          <span class="settings-value">${hubInfo ? hubInfo.hub : '—'}</span>
        </div>
        <div class="settings-row">
          <span class="settings-label">${t('settings.protocol')}</span>
          <span class="settings-value">
            ${hubInfo ? `MNP ${hubInfo.mnp} / MHP ${hubInfo.mhp}` : '—'}
          </span>
        </div>
      </div>
    </div>
  `;
}

// ── Admin Panel ─────────────────────────────────────────────────────────────

function AdminPage({ token }) {
  const [tab, setTab] = useState('stats');
  const [stats, setStats] = useState(null);
  const [users, setUsers] = useState([]);
  const [usersTotal, setUsersTotal] = useState(0);
  const [userSearch, setUserSearch] = useState('');
  const [groups, setGroups] = useState([]);
  const [groupsTotal, setGroupsTotal] = useState(0);
  const [logs, setLogs] = useState([]);
  const [logEvent, setLogEvent] = useState('');
  const [logOffset, setLogOffset] = useState(0);
  const [blocklist, setBlocklist] = useState([]);
  const [nodes, setNodes] = useState([]);
  const [detailUser, setDetailUser] = useState(null);
  const [error, setError] = useState('');

  const headers = { Authorization: `Bearer ${token}` };

  const loadStats = useCallback(async () => {
    try {
      const data = await hubFetch('/v1/admin/stats', { token });
      setStats(data);
    } catch (e) { setError(e.message); }
  }, [token]);

  const loadUsers = useCallback(async (q = '') => {
    try {
      const data = await hubFetch(`/v1/admin/users?q=${encodeURIComponent(q)}&limit=100`, { token });
      setUsers(data.users);
      setUsersTotal(data.total);
    } catch (e) { setError(e.message); }
  }, [token]);

  const loadGroups = useCallback(async () => {
    try {
      const data = await hubFetch('/v1/admin/groups?limit=100', { token });
      setGroups(data.groups);
      setGroupsTotal(data.total);
    } catch (e) { setError(e.message); }
  }, [token]);

  const loadLogs = useCallback(async (event = '', offset = 0, append = false) => {
    try {
      let url = `/v1/admin/logs?limit=50&offset=${offset}`;
      if (event) url += `&event=${encodeURIComponent(event)}`;
      const data = await hubFetch(url, { token });
      setLogs(prev => append ? [...prev, ...data.logs] : data.logs);
    } catch (e) { setError(e.message); }
  }, [token]);

  const loadBlocklist = useCallback(async () => {
    try {
      const data = await hubFetch('/v1/admin/blocklist', { token });
      setBlocklist(data.entries);
    } catch (e) { setError(e.message); }
  }, [token]);

  useEffect(() => {
    setError('');
    if (tab === 'stats') loadStats();
    else if (tab === 'users') loadUsers(userSearch);
    else if (tab === 'groups') loadGroups();
    else if (tab === 'nodes') {
      hubFetch('/v1/admin/nodes', { token })
        .then(d => setNodes(d.nodes || [])).catch(e => setError(e.message));
    }
    else if (tab === 'logs') { setLogOffset(0); loadLogs(logEvent, 0); }
    else if (tab === 'blocklist') loadBlocklist();
  }, [tab]);

  const deleteUser = useCallback(async (u) => {
    // Suspension is the reversible tool and stays one click away; this one is
    // not, so it names the account and says what it cannot reach.
    if (!confirm(t('admin.delete_confirm', { user: u.username }))) return;
    try {
      await hubFetch(`/v1/admin/users/${u.id}`, { method: 'DELETE', token });
      loadUsers(userSearch);
    } catch (err) {
      alert(err.message);
    }
  }, [token, userSearch, loadUsers]);

  const patchUser = useCallback(async (userId, patch) => {
    try {
      await hubFetch(`/v1/admin/users/${userId}`, { method: 'PATCH', body: patch, token });
      loadUsers(userSearch);
      if (detailUser && detailUser.id === userId) setDetailUser(null);
    } catch (e) { setError(e.message); }
  }, [token, userSearch, detailUser]);

  const patchGroup = useCallback(async (groupId, patch) => {
    try {
      await hubFetch(`/v1/admin/groups/${groupId}`, { method: 'PATCH', body: patch, token });
      loadGroups();
    } catch (e) { setError(e.message); }
  }, [token]);

  const showUserDetail = useCallback(async (userId) => {
    try {
      const data = await hubFetch(`/v1/admin/users/${userId}`, { token });
      setDetailUser(data);
    } catch (e) { setError(e.message); }
  }, [token]);

  const addToBlocklist = useCallback(async (hash, reason) => {
    try {
      await hubFetch('/v1/admin/blocklist', { method: 'POST', body: { content_hash: hash, reason }, token });
      loadBlocklist();
    } catch (e) { setError(e.message); }
  }, [token]);

  const removeFromBlocklist = useCallback(async (hash) => {
    try {
      await hubFetch(`/v1/admin/blocklist/${hash}`, { method: 'DELETE', token });
      loadBlocklist();
    } catch (e) { setError(e.message); }
  }, [token]);

  const TABS = ['stats', 'users', 'groups', 'nodes', 'logs', 'blocklist'];

  return html`
    <div>
      <h2>${t('admin.title')}</h2>
      ${error && html`<div class="error-msg" style="margin-bottom:12px">${error}</div>`}

      <div class="admin-tabs">
        ${TABS.map(k => html`
          <button key=${k} class="admin-tab ${tab === k ? 'active' : ''}"
            onClick=${() => setTab(k)}>${t('admin.tab_' + k)}</button>
        `)}
      </div>

      ${tab === 'stats' && stats && html`
        <div class="admin-stats">
          ${[['users', 'stat_users'], ['groups', 'stat_groups'],
             ['nodes', 'stat_nodes'], ['online_nodes', 'stat_online']].map(([k, label]) => html`
            <div class="stat-card" key=${k}>
              <div class="stat-value">${stats[k]}</div>
              <div class="stat-label">${t('admin.' + label)}</div>
            </div>
          `)}
        </div>
      `}

      ${tab === 'users' && html`
        <div class="admin-toolbar">
          <input class="admin-search" type="text" placeholder="${t('admin.users_search')}"
            value=${userSearch} onInput=${e => { setUserSearch(e.target.value); loadUsers(e.target.value); }} />
          <span class="settings-value">${usersTotal} total</span>
        </div>
      <table class="admin-table">
          <thead><tr>
            <th>${t('admin.col_username')}</th>
            <th>${t('admin.col_role')}</th>
            <th>${t('admin.col_status')}</th>
            <th>${t('admin.col_created')}</th>
            <th>${t('admin.col_actions')}</th>
          </tr></thead>
          <tbody>
            ${users.length === 0 && html`<tr><td colspan="5" class="admin-empty">${t('admin.no_users')}</td></tr>`}
            ${users.map(u => html`
              <tr key=${u.id}>
                <td>${u.username}</td>
                <td>
                  <select class="admin-role-select" value=${u.role}
                    onChange=${e => patchUser(u.id, { role: e.target.value })}>
                    <option value="user">user</option>
                    <option value="moderator">moderator</option>
                    <option value="admin">admin</option>
                  </select>
                </td>
                <td><span class="badge ${u.status === 'active' ? 'badge-ok' : u.status === 'suspended' ? 'badge-err' : ''}">${u.status}</span></td>
                <td>${new Date(u.created_at).toLocaleDateString()}</td>
                <td class="admin-actions">
                  <button class="admin-btn" onClick=${() => showUserDetail(u.id)}>${t('admin.btn_details')}</button>
                  ${u.status === 'active'
                    ? html`<button class="admin-btn danger" onClick=${() => patchUser(u.id, { status: 'suspended' })}>${t('admin.btn_suspend')}</button>`
                    : u.status === 'suspended'
                      ? html`<button class="admin-btn" onClick=${() => patchUser(u.id, { status: 'active' })}>${t('admin.btn_unsuspend')}</button>`
                      : null
                  }
                  ${u.status !== 'deleted' && html`
                    <button class="admin-btn danger"
                      onClick=${() => deleteUser(u)}>${t('admin.btn_delete')}</button>
                  `}
                </td>
              </tr>
            `)}
          </tbody>
        </table>
      `}

      ${tab === 'groups' && html`
        <div class="admin-toolbar">
          <span class="settings-value">${groupsTotal} total</span>
        </div>
        <table class="admin-table">
          <thead><tr>
            <th>${t('admin.col_name')}</th>
            <th>${t('admin.col_visibility')}</th>
            <th>${t('admin.col_members')}</th>
            <th>${t('admin.col_status')}</th>
            <th>${t('admin.col_created')}</th>
            <th>${t('admin.col_actions')}</th>
          </tr></thead>
          <tbody>
            ${groups.length === 0 && html`<tr><td colspan="6" class="admin-empty">${t('admin.no_groups')}</td></tr>`}
            ${groups.map(g => html`
              <tr key=${g.id}>
                <td>${g.name}</td>
                <td><span class="badge">${g.visibility}</span></td>
                <td>${g.member_count}</td>
                <td><span class="badge ${g.status === 'active' ? 'badge-ok' : g.status === 'suspended' ? 'badge-err' : ''}">${g.status}</span></td>
                <td>${new Date(g.created_at).toLocaleDateString()}</td>
                <td class="admin-actions">
                  ${g.status === 'active'
                    ? html`<button class="admin-btn danger" onClick=${() => patchGroup(g.id, { status: 'suspended' })}>${t('admin.btn_suspend')}</button>`
                    : g.status === 'suspended'
                      ? html`<button class="admin-btn" onClick=${() => patchGroup(g.id, { status: 'active' })}>${t('admin.btn_unsuspend')}</button>`
                      : null
                  }
                </td>
              </tr>
            `)}
          </tbody>
        </table>
      `}

      ${tab === 'nodes' && html`
        <p class="settings-hint" style="margin-bottom:10px">
          ${t('admin.nodes_hint')}
        </p>
        <table class="admin-table">
          <thead><tr>
            <th>${t('admin.col_username')}</th>
            <th>${t('admin.col_observed_ip')}</th>
            <th>${t('admin.col_hint')}</th>
            <th>${t('admin.col_last_seen')}</th>
            <th>${t('admin.col_status')}</th>
          </tr></thead>
          <tbody>
            ${nodes.length === 0 && html`
              <tr><td colspan="5" class="admin-empty">${t('admin.no_nodes')}</td></tr>
            `}
            ${nodes.map(n => html`
              <tr key=${n.id}>
                <td>${n.username || n.user_id.slice(0, 8)}</td>
                <td style="font-family:monospace">${n.observed_ip || '—'}</td>
                <td style="font-family:monospace;color:var(--text-dim)">
                  ${n.endpoint_hint || '—'}
                </td>
                <td>${n.last_seen ? new Date(n.last_seen).toLocaleString() : '—'}</td>
                <td>
                  <span class="badge ${n.online ? 'badge-ok' : ''}">
                    ${n.online ? t('admin.node_online') : t('admin.node_offline')}
                  </span>
                </td>
              </tr>
            `)}
          </tbody>
        </table>
      `}

      ${tab === 'logs' && html`
        <div class="admin-toolbar">
          <select class="admin-select" value=${logEvent} onChange=${e => {
            setLogEvent(e.target.value);
            setLogOffset(0);
            loadLogs(e.target.value, 0);
          }}>
            <option value="">${t('admin.filter_all')}</option>
            ${['login', 'login_fail', 'account_create', 'token_refresh', 'group_create',
               'group_join', 'group_leave', 'node_announce', 'revoke_user', 'revoke_group',
               'admin_user_update', 'admin_group_update'].map(ev => html`
              <option key=${ev} value=${ev}>${ev}</option>
            `)}
          </select>
        </div>
        <table class="admin-table">
          <thead><tr>
            <th>${t('admin.col_time')}</th>
            <th>${t('admin.col_user')}</th>
            <th>${t('admin.col_event')}</th>
            <th>${t('admin.col_ip')}</th>
            <th>${t('admin.col_detail')}</th>
          </tr></thead>
          <tbody>
            ${logs.length === 0 && html`<tr><td colspan="5" class="admin-empty">${t('admin.no_logs')}</td></tr>`}
            ${logs.map(lg => html`
              <tr key=${lg.id}>
                <td style="white-space:nowrap">${new Date(lg.timestamp).toLocaleString()}</td>
                <td>${lg.username || ''}</td>
                <td><span class="badge">${lg.event}</span></td>
                <td>${lg.ip_address}</td>
                <td>${lg.detail || ''}</td>
              </tr>
            `)}
          </tbody>
        </table>
        ${logs.length > 0 && logs.length % 50 === 0 && html`
          <button class="admin-btn admin-load-more" onClick=${() => {
            const next = logOffset + 50;
            setLogOffset(next);
            loadLogs(logEvent, next, true);
          }}>${t('admin.btn_load_more')}</button>
        `}
      `}

      ${tab === 'blocklist' && html`
        <${BlocklistForm} onAdd=${addToBlocklist} />
        <table class="admin-table">
          <thead><tr>
            <th>${t('admin.col_hash')}</th>
            <th>${t('admin.col_reason')}</th>
            <th>${t('admin.col_date')}</th>
            <th>${t('admin.col_added_by')}</th>
            <th>${t('admin.col_actions')}</th>
          </tr></thead>
          <tbody>
            ${blocklist.length === 0 && html`<tr><td colspan="5" class="admin-empty">${t('admin.no_blocked')}</td></tr>`}
            ${blocklist.map(b => html`
              <tr key=${b.hash}>
                <td style="font-family:monospace;font-size:0.8em">${b.hash.slice(0, 16)}...</td>
                <td>${b.reason}</td>
                <td>${new Date(b.added_at).toLocaleDateString()}</td>
                <td>${b.added_by || ''}</td>
                <td>
                  <button class="admin-btn" onClick=${() => removeFromBlocklist(b.hash)}>${t('admin.btn_unblock')}</button>
                </td>
              </tr>
            `)}
          </tbody>
        </table>
      `}

      ${detailUser && html`
        <div class="admin-detail-overlay" onClick=${e => {
          if (e.target.classList.contains('admin-detail-overlay')) setDetailUser(null);
        }}>
          <div class="admin-detail-card">
            <h3>${t('admin.user_detail')}</h3>
            ${[
              ['admin.col_username', detailUser.username],
              ['admin.col_email', detailUser.email],
              ['admin.col_role', detailUser.role],
              ['admin.col_status', detailUser.status],
              ['admin.col_created', new Date(detailUser.created_at).toLocaleString()],
              ['admin.col_groups', detailUser.group_count],
            ].map(([label, val]) => html`
              <div class="admin-detail-row" key=${label}>
                <span class="admin-detail-label">${t(label)}</span>
                <span class="admin-detail-value">${val}</span>
              </div>
            `)}
            <button class="admin-btn" style="margin-top:16px;width:100%"
              onClick=${() => setDetailUser(null)}>${t('admin.btn_close')}</button>
          </div>
        </div>
      `}
    </div>
  `;
}

function BlocklistForm({ onAdd }) {
  const [hash, setHash] = useState('');
  const [reason, setReason] = useState('');

  const submit = (e) => {
    e.preventDefault();
    if (hash.length === 64 && reason) {
      onAdd(hash, reason);
      setHash('');
      setReason('');
    }
  };

  return html`
    <form class="blocklist-form" onSubmit=${submit}>
      <input type="text" placeholder="${t('admin.hash_placeholder')}"
        value=${hash} onInput=${e => setHash(e.target.value)}
        pattern="[0-9a-f]{64}" required />
      <input type="text" placeholder="${t('admin.reason_placeholder')}"
        value=${reason} onInput=${e => setReason(e.target.value)} required />
      <button class="admin-btn" type="submit">${t('admin.btn_block')}</button>
    </form>
  `;
}

// ── Node management (D5) ────────────────────────────────────────────────────

function NodePage({ token, username, userId, groups }) {
  const [status, setStatus] = useState('idle');
  const [error, setError] = useState('');
  const [nodeGroups, setNodeGroups] = useState([]);
  const [busy, setBusy] = useState(false);
  const [actionMsg, setActionMsg] = useState('');
  const [roster, setRoster] = useState(null);
  const [rosterGroup, setRosterGroup] = useState('');
  const [denylist, setDenylist] = useState(null);
  const [showDenylist, setShowDenylist] = useState(false);
  const [attachGroup_, setAttachGroup_] = useState('');
  const [attachDir, setAttachDir] = useState('');
  const [attachUpload, setAttachUpload] = useState('');
  const transportRef = useRef(null);

  const connectAndFetch = useCallback(async () => {
    if (!groups.length) {
      setStatus('no_groups');
      return;
    }
    setStatus('connecting');
    setError('');
    try {
      if (!_bundleKey) _bundleKey = await _loadBundleKey();
      const live = (await ensureFreshToken()) || token;

      const nodeCandidates = (await Promise.all(
        groups.map(g =>
          hubFetch(`/v1/groups/${g.id}/nodes`, { token: live })
            .then(d => (d.nodes || []).map(n => ({ groupId: g.id, nodeId: n.node_id })))
            .catch(() => []))
      )).flat();

      if (!nodeCandidates.length) {
        setError(t('node.offline'));
        setStatus('error');
        return;
      }

      // Group candidates by node, preserving all groupIds. The same node
      // is reachable through any group it serves; a group that was just
      // attached but not yet loaded will fail, so we try every groupId
      // before giving up on a node.
      const byNode = new Map();
      for (const c of nodeCandidates) {
        if (!byNode.has(c.nodeId)) byNode.set(c.nodeId, []);
        const ids = byNode.get(c.nodeId);
        if (!ids.includes(c.groupId)) ids.push(c.groupId);
      }

      console.log('[NodePage] candidates:', byNode.size, 'node(s)',
                   [...byNode.entries()].map(([n, gs]) => n.slice(0, 8) + '×' + gs.length));
      let lastErr = null;
      for (const [nodeId, groupIds] of byNode) {
        for (const groupId of groupIds) {
          const transport = new window.MeshBayTransport(HUB, live);
          try {
            console.log('[NodePage] connecting via group', groupId.slice(0, 8),
                        'node', nodeId.slice(0, 8));
            await transport.connect(nodeId, live, groupId,
                                   null, null, _bundleKey, username, userId);
            console.log('[NodePage] connected, fetching status');
            const result = await transport.fetchNodeStatus();
            console.log('[NodePage] got status:', result.groups?.length, 'groups');
            transportRef.current = transport;
            setNodeGroups(result.groups || []);
            setStatus('connected');
            return;
          } catch (err) {
            console.warn('[NodePage] candidate failed:', nodeId.slice(0, 8),
                         'group', groupId.slice(0, 8), err.message);
            try { transport.close(); } catch {}
            lastErr = err;
          }
        }
      }
      setError(lastErr ? lastErr.message : t('node.not_operator'));
      setStatus('error');
    } catch (err) {
      setError(err.message);
      setStatus('error');
    }
  }, [token, username, userId, groups]);

  useEffect(() => {
    connectAndFetch();
    return () => {
      const tr = transportRef.current;
      if (tr && tr.connected) try { tr.close(); } catch {}
    };
  }, [connectAndFetch]);

  const refresh = useCallback(async () => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    try {
      const result = await transport.fetchNodeStatus();
      setNodeGroups(result.groups || []);
    } catch {}
  }, []);

  const signFn = useCallback(async (transcript) => {
    const transport = transportRef.current;
    if (!transport || !transport.sessionKeys || !transport.sessionKeys.skEdB64)
      throw new Error('No signing key');
    return window.MeshBayKeys.signBytes(transport.sessionKeys.skEdB64, transcript);
  }, []);

  const addRoot = useCallback(async (groupId) => {
    const chosen = await platform.rootPicker.choose();
    if (!chosen) return;
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    setBusy(true);
    setActionMsg('');
    try {
      await transport.addRoot(groupId, chosen.path, {}, signFn);
      await refresh();
      setActionMsg(t('node.root_added'));
    } catch (err) {
      setActionMsg(err.message);
    } finally {
      setBusy(false);
    }
  }, [signFn, refresh]);

  const removeRoot = useCallback(async (groupId, rootName) => {
    if (!confirm(t('node.root_remove_confirm', { name: rootName }))) return;
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    setBusy(true);
    setActionMsg('');
    try {
      await transport.removeRoot(groupId, rootName, signFn);
      await refresh();
      setActionMsg(t('node.root_removed'));
    } catch (err) {
      setActionMsg(err.message);
    } finally {
      setBusy(false);
    }
  }, [signFn, refresh]);

  const loadRoster = useCallback(async (groupId) => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    setBusy(true);
    try {
      const result = await transport.fetchRoster(groupId);
      setRoster(result);
      setRosterGroup(groupId);
    } catch (err) {
      setActionMsg(err.message);
    } finally {
      setBusy(false);
    }
  }, []);

  const unpinMember = useCallback(async (userId) => {
    if (!confirm(t('node.unpin_confirm', { name: userId }))) return;
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    setBusy(true);
    setActionMsg('');
    try {
      await transport.unpinMember(userId, signFn);
      setActionMsg(t('node.unpin_done'));
      if (rosterGroup) await loadRoster(rosterGroup);
    } catch (err) {
      setActionMsg(err.message);
    } finally {
      setBusy(false);
    }
  }, [signFn, rosterGroup, loadRoster]);

  const rotateGek = useCallback(async (groupId) => {
    if (!confirm(t('node.gek_rotate_confirm'))) return;
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    setBusy(true);
    setActionMsg('');
    try {
      await transport.rotateGek(groupId, signFn);
      setActionMsg(t('node.gek_rotated'));
    } catch (err) {
      setActionMsg(err.message);
    } finally {
      setBusy(false);
    }
  }, [signFn]);

  const loadDenylist = useCallback(async () => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    setBusy(true);
    try {
      const result = await transport.fetchDenylist();
      setDenylist(result);
      setShowDenylist(true);
    } catch (err) {
      setActionMsg(err.message);
    } finally {
      setBusy(false);
    }
  }, []);

  const clearDenylist = useCallback(async (subject) => {
    const label = subject || t('node.denylist_clear_all');
    if (!confirm(t('node.denylist_clear_confirm', { subject: label }))) return;
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    setBusy(true);
    setActionMsg('');
    try {
      await transport.clearDenylist(subject);
      setActionMsg(t('node.denylist_cleared'));
      await loadDenylist();
    } catch (err) {
      setActionMsg(err.message);
    } finally {
      setBusy(false);
    }
  }, [loadDenylist]);

  const pickAttachDir = useCallback(async (setter) => {
    const chosen = await platform.rootPicker.choose();
    if (chosen) setter(chosen.path);
  }, []);

  const detachGroup = useCallback(async (name) => {
    if (!confirm(t('node.detach_confirm', { name }))) return;
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    setBusy(true);
    setActionMsg('');
    try {
      await transport.detachGroup(name, signFn);
      setActionMsg(t('node.detached'));
      await refresh();
    } catch (err) {
      setActionMsg(err.message);
    } finally {
      setBusy(false);
    }
  }, [signFn, refresh]);

  const attachGroup = useCallback(async () => {
    if (!attachGroup_ || !attachDir.trim()) return;
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    setBusy(true);
    setActionMsg('');
    try {
      const ack = await transport.attachGroup(attachGroup_, attachDir.trim(),
                                  attachUpload.trim(), signFn);
      setActionMsg(t('node.attached', { name: ack.name || attachGroup_ }));
      setAttachGroup_('');
      setAttachDir('');
      setAttachUpload('');
      await refresh();
    } catch (err) {
      setActionMsg(err.message);
    } finally {
      setBusy(false);
    }
  }, [attachGroup_, attachDir, attachUpload, signFn]);

  const reloadConfig = useCallback(async () => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    setBusy(true);
    setActionMsg('');
    try {
      await transport.reloadConfig();
      setActionMsg(t('node.reloaded'));
      await refresh();
    } catch (err) {
      setActionMsg(err.message);
    } finally {
      setBusy(false);
    }
  }, [refresh]);

  if (status === 'idle' || status === 'connecting') {
    return html`<div class="page-content">
      <p class="page-message"><span class="spinner"></span>${' '}${t('status.connecting')}</p>
    </div>`;
  }
  if (status === 'no_groups') {
    return html`<div class="page-content">
      <p class="page-message">${t('node.no_groups')}</p>
    </div>`;
  }
  if (status === 'error') {
    return html`<div class="page-content">
      <h2>${t('node.title')}</h2>
      <p class="error-msg">${error}</p>
      <button class="btn btn-primary" onClick=${connectAndFetch}>
        ${t('node.retry')}</button>
    </div>`;
  }

  return html`
    <div class="page-content node-page">
      <div class="node-header">
        <h2>${t('node.title')}</h2>
        <button class="btn btn-small btn-secondary" disabled=${busy}
          onClick=${reloadConfig}>
          ${t('node.reload')}</button>
      </div>
      ${actionMsg && html`<div class="node-message">${actionMsg}</div>`}
      ${(() => {
        const hubIds = new Set((groups || []).map(g => g.id));
        return nodeGroups.map(g => {
          const stale = !hubIds.has(g.id);
          return html`
        <div class="node-group ${stale ? 'node-group-stale' : ''}" key=${g.id}>
          <div class="node-group-header">
            <h3>${g.name}${stale ? html` <span class="node-warn">${t('node.stale')}</span>` : ''}</h3>
            <div class="node-group-stats">
              <span>${t('node.files', { n: g.file_count })}</span>
              <span>${t('node.peers', { n: g.peers })}</span>
              ${!g.has_gek && html`
                <span class="node-warn">${t('node.no_gek')}</span>`}
            </div>
          </div>
          <div class="node-roots">
            <div class="node-roots-header">
              <span class="settings-heading">${t('node.roots')}</span>
            </div>
            ${(g.roots || []).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>
                ${(g.roots || []).length > 1 && !r.upload && html`
                  <button class="btn btn-small btn-danger"
                    disabled=${busy} onClick=${() => removeRoot(g.id, r.name)}>
                    ${t('node.remove_root')}</button>`}
              </div>
            `)}
            <button class="btn btn-small btn-secondary"
              disabled=${busy} onClick=${() => addRoot(g.id)}>
              <${Icon} name="folder-plus" /> ${t('node.add_root')}
            </button>
          </div>

          <div class="node-section">
            <span class="settings-heading">${t('node.gek')}</span>
            ${g.has_gek ? (g.visibility !== 'public' ? html`
              <button class="btn btn-small btn-secondary" disabled=${busy}
                onClick=${() => rotateGek(g.id)}>
                ${t('node.gek_rotate')}</button>
            ` : html`<p class="node-hint">${t('node.gek_public_hint')}</p>`) : html`
              <p class="node-hint">${t('node.gek_init_hint')}</p>
            `}
          </div>

          <div class="node-section">
            <div class="node-section-header">
              <span class="settings-heading">${t('node.roster')}</span>
              <button class="btn btn-small btn-secondary" disabled=${busy}
                onClick=${() => loadRoster(g.id)}>
                ${t('node.roster_load')}</button>
            </div>
            ${roster && rosterGroup === g.id && html`
              <div class="node-roster">
                ${(roster.members || []).length === 0 ? html`
                  <p class="node-hint">${t('node.roster_empty')}</p>
                ` : html`
                  <table class="node-table">
                    <thead><tr>
                      <th>${t('node.roster_user')}</th>
                      <th>${t('node.roster_role')}</th>
                      <th>${t('node.roster_status')}</th>
                      <th>${t('node.roster_via')}</th>
                      <th></th>
                    </tr></thead>
                    <tbody>
                      ${(roster.members || []).map(m => html`
                        <tr key=${m.user_id}>
                          <td>${m.username || m.user_id.slice(0, 12)}</td>
                          <td>${m.role}</td>
                          <td>${m.status}</td>
                          <td>${m.pinned_via || ''}</td>
                          <td>${m.pk_ed25519 && m.user_id !== userId && html`
                            <button class="btn btn-small btn-danger"
                              disabled=${busy}
                              onClick=${() => unpinMember(m.user_id)}>
                              ${t('node.unpin')}</button>
                          `}</td>
                        </tr>
                      `)}
                    </tbody>
                  </table>
                `}
                ${(roster.invites || []).length > 0 && html`
                  <p class="node-hint">${t('node.roster_invites',
                    { n: roster.invites.length })}</p>
                `}
              </div>
            `}
          </div>

          <div class="node-section">
            <button class="btn btn-small btn-danger" disabled=${busy}
              onClick=${() => detachGroup(g.name)}>
              ${t('node.detach_group')}</button>
          </div>
        </div>
      `;
        });
      })()}

      <div class="node-group">
        <div class="node-section-header">
          <span class="settings-heading">${t('node.denylist')}</span>
          <button class="btn btn-small btn-secondary" disabled=${busy}
            onClick=${loadDenylist}>
            ${t('node.denylist_load')}</button>
        </div>
        ${showDenylist && denylist && html`
          <div class="node-denylist">
            ${denylist.count === 0 ? html`
              <p class="node-hint">${t('node.denylist_empty')}</p>
            ` : html`
              <p class="node-hint">${t('node.denylist_count',
                { n: denylist.count })}</p>
              ${(denylist.users || []).map(u => html`
                <div class="node-deny-entry" key=${'u:' + u}>
                  <span>user: ${u}</span>
                  <button class="btn btn-small btn-danger" disabled=${busy}
                    onClick=${() => clearDenylist(u)}>
                    ${t('node.denylist_remove')}</button>
                </div>
              `)}
              ${(denylist.groups || []).map(g => html`
                <div class="node-deny-entry" key=${'g:' + g}>
                  <span>group: ${g}</span>
                  <button class="btn btn-small btn-danger" disabled=${busy}
                    onClick=${() => clearDenylist(g)}>
                    ${t('node.denylist_remove')}</button>
                </div>
              `)}
              ${(denylist.jtis || []).map(j => html`
                <div class="node-deny-entry" key=${'j:' + j}>
                  <span>token: ${j.slice(0, 16)}</span>
                  <button class="btn btn-small btn-danger" disabled=${busy}
                    onClick=${() => clearDenylist(j)}>
                    ${t('node.denylist_remove')}</button>
                </div>
              `)}
              <button class="btn btn-small btn-danger" disabled=${busy}
                onClick=${() => clearDenylist('')}>
                ${t('node.denylist_clear_all')}</button>
            `}
          </div>
        `}
      </div>

      ${/* In Electron, the Create Group wizard handles attaching. Keep for
            browser users who manage nodes via MNP. */
        !platform.node.available && (() => {
        const hostedIds = new Set(nodeGroups.map(g => g.id));
        const unhosted = (groups || []).filter(g => !hostedIds.has(g.id));
        if (!unhosted.length) return null;
        return html`
          <div class="node-group">
            <span class="settings-heading">${t('node.attach_group')}</span>
            <div class="node-attach-form">
              <label>${t('node.attach_pick')}</label>
              <select value=${attachGroup_}
                onChange=${e => setAttachGroup_(e.target.value)}>
                <option value="">---</option>
                ${unhosted.map(g => html`
                  <option key=${g.id} value=${g.name}>${g.name}</option>
                `)}
              </select>
              <label>${t('node.attach_dir')}</label>
              <div class="node-attach-dir-row">
                <input type="text" placeholder=${t('node.attach_dir')}
                  value=${attachDir} readOnly
                  onInput=${e => setAttachDir(e.target.value)} />
                ${platform.rootPicker && html`
                  <button class="btn btn-small btn-secondary"
                    onClick=${() => pickAttachDir(setAttachDir)}>
                    <${Icon} name="folder" /></button>
                `}
              </div>
              <label>${t('node.attach_upload_label')}</label>
              <div class="node-attach-dir-row">
                <input type="text" placeholder=${t('node.attach_upload_dir')}
                  value=${attachUpload} readOnly
                  onInput=${e => setAttachUpload(e.target.value)} />
                ${platform.rootPicker && html`
                  <button class="btn btn-small btn-secondary"
                    onClick=${() => pickAttachDir(setAttachUpload)}>
                    <${Icon} name="folder" /></button>
                `}
              </div>
              <button class="btn btn-primary"
                disabled=${busy || !attachGroup_ || !attachDir.trim()}
                onClick=${attachGroup}>
                ${t('node.attach_group')}</button>
            </div>
            <p class="node-hint">${t('node.restart_needed')}</p>
          </div>
        `;
      })()}
    </div>
  `;
}

// ── App ──────────────────────────────────────────────────────────────────────

function App() {
  const route = useRoute();
  const [theme, setTheme] = useState(getInitialTheme);
  const [user, setUser] = useState(loadAuth);
  // A desktop build with a remembered device signs in without asking. Null
  // until it has tried, so nothing renders a sign-in form the user is about to
  // be taken past.
  const [deviceTried, setDeviceTried] = useState(!platform.device.available);
  // Native, and nowhere to talk to yet.
  const [needsHub, setNeedsHub] = useState(
    platform.isNative && !platform.hubBase());
  const [groups, setGroups] = useState([]);
  const [menuOpen, setMenuOpen] = useState(false);
  const [notifications, setNotifications] = useState([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [notifDisabled, setNotifDisabled] = useState(false);
  const [userPrefs, setUserPrefs] = useState({});
  const [hasNodeKey, setHasNodeKey] = useState(false);

  const resolved = resolveTheme(theme);

  // Keep the session alive without anyone having to think about it.
  useEffect(() => {
    // A renewal can happen inside hubFetch, well away from any render. This is
    // how the component learns about it — including a failed one, which sets
    // null and lands on the login page instead of failing every later call.
    _onAuthChange = (auth) => setUser(auth);

    // On mount above all: a tab reopened tomorrow holds an hour-old access
    // token and a refresh token good for a month, and used to greet its owner
    // with "invalid token" rather than spending the second on renewing it.
    ensureFreshToken();

    const timer = setInterval(ensureFreshToken, TOKEN_CHECK_MS);
    // A backgrounded tab has its timers throttled hard, so the check above may
    // not have run for the whole time it was away. Coming back is exactly when
    // the token is most likely to be stale.
    const onVisible = () => {
      if (document.visibilityState === 'visible') ensureFreshToken();
    };
    document.addEventListener('visibilitychange', onVisible);
    return () => {
      _onAuthChange = null;
      clearInterval(timer);
      document.removeEventListener('visibilitychange', onVisible);
    };
  }, []);

  useEffect(() => {
    document.documentElement.className = `theme-${resolved}`;
    localStorage.setItem(THEME_KEY, theme);
  }, [theme, resolved]);

  const fetchNotifications = useCallback(() => {
    if (!user || notifDisabled) {
      setNotifications([]); setUnreadCount(0); return;
    }
    hubFetch('/v1/notifications?limit=20', { token: user.token })
      .then(data => {
        setNotifications(data.notifications || []);
        setUnreadCount(data.unread_count || 0);
      })
      .catch(() => {});
  }, [user, notifDisabled]);

  useEffect(() => {
    if (!user) { setGroups([]); setNotifications([]); setUnreadCount(0); setHasNodeKey(false); return; }
    hubFetch('/v1/groups/mine', { token: user.token })
      .then(data => setGroups(data.groups || []))
      .catch(() => setGroups([]));
    hubFetch('/v1/users/me/preferences', { token: user.token })
      .then(prefs => {
        setUserPrefs(prefs || {});
        if (prefs.notifications_disabled === 'true') setNotifDisabled(true);
      })
      .catch(() => {});
    if (platform.capabilities.nodeAdmin) {
      hubFetch(`/v1/users/${user.username}/pubkeys`, { token: user.token })
        .then(data => setHasNodeKey(Boolean(data.pk_node_ed25519)))
        .catch(() => {});
    }
    fetchNotifications();
  }, [user]);

  // The group list lives here, so an edit made three components down has to come
  // back up rather than be re-fetched: a reload would drop the WebRTC connection
  // the page is holding.
  const updateGroup = useCallback((gid, patch) => {
    setGroups(prev => prev.map(g => (g.id === gid ? { ...g, ...patch } : g)));
  }, []);

  // What this browser saw for itself, which beats what the hub reported. Held
  // for the session only: it is a cache of observations, not a source of truth,
  // and a reload should go back to asking.
  const [presence, setPresence] = useState({});
  const notePresence = useCallback((gid, state) => {
    setPresence(prev => (prev[gid] === state ? prev : { ...prev, [gid]: state }));
  }, []);

  const handleLeftGroup = useCallback((gid) => {
    setGroups(prev => prev.filter(g => g.id !== gid));
    setPresence(prev => {
      const next = { ...prev };
      delete next[gid];
      return next;
    });
    navigate('/');
  }, []);

  const markRead = useCallback((id) => {
    if (!user) return;
    // Drop it here and now. Waiting for the round trip leaves it on screen while
    // the page navigates, which reads as "the click did nothing".
    setNotifications(prev => prev.filter(n => n.id !== id));
    setUnreadCount(c => Math.max(0, c - 1));
    hubFetch(`/v1/notifications/${id}/read`, { method: 'POST', token: user.token })
      .catch(() => fetchNotifications());
  }, [user, fetchNotifications]);

  const purgeNotifications = useCallback(() => {
    if (!user) return;
    setNotifications([]);
    setUnreadCount(0);
    hubFetch('/v1/notifications', { method: 'DELETE', token: user.token })
      .catch(() => fetchNotifications());
  }, [user, fetchNotifications]);

  /** Clear the invitation for a group once its code has actually been redeemed. */
  const dismissGroupNotifications = useCallback((groupId) => {
    if (!user) return;
    setNotifications(prev => {
      const gone = prev.filter(n => n.group_id === groupId && n.kind === 'group_invite');
      gone.forEach(n => hubFetch(`/v1/notifications/${n.id}/read`,
        { method: 'POST', token: user.token }).catch(() => {}));
      if (gone.length) setUnreadCount(c => Math.max(0, c - gone.length));
      return prev.filter(n => !gone.includes(n));
    });
  }, [user]);

  // Sign in with this device's key, once, at startup.
  //
  // The passphrase stays the account's credential and its recovery path; this
  // is what saves entering it every launch. A refusal is not an error worth
  // showing — the key may have been retired from another device, or the hub may
  // have forgotten it — so it falls through to the ordinary form.
  useEffect(() => {
    // Nothing to do when a session was restored from storage, or when this is
    // a browser. `user` is read once here on purpose: this runs at startup and
    // must not re-fire when the session it just created lands.
    if (deviceTried || user) { setDeviceTried(true); return; }
    let cancelled = false;
    (async () => {
      try {
        // `loadAuth` keeps the username even when the tokens in it are stale,
        // and `app://meshbay` is a stable origin, so localStorage survives a
        // relaunch. A fresh install has nothing here and asks for a passphrase,
        // which is right: the first sign-in is what registers the device.
        const saved = loadAuth();
        const username = saved && saved.username;
        if (!username) return;
        const signed = await platform.device.sign(username);
        if (!signed) return;
        const data = await hubFetch('/v1/users/auth', {
          method: 'POST',
          body: { username, timestamp: signed.timestamp,
                  signature: signed.signature },
        });
        const me = await hubFetch('/v1/users/me', { token: data.access_token });
        if (cancelled) return;
        const u = { username, userId: me.user_id, token: data.access_token,
                    refreshToken: data.refresh_token, role: me.role };
        setAuth(u);
        setUser(u);
      } catch {
        // Falls through to the sign-in form, which is the honest outcome.
      } finally {
        if (!cancelled) setDeviceTried(true);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  useEffect(() => { setMenuOpen(false); }, [route]);

  const changeTheme = useCallback((val) => {
    setTheme(val);
  }, []);

  /**
   * Register this device's hub key, once, after a passphrase sign-in.
   *
   * Deliberately not fatal: a hub that refuses it, or a machine with no key
   * storage, means the passphrase is asked for again next time — which is
   * exactly what a browser does, and is a worse experience rather than a
   * broken one.
   */
  const registerThisDevice = useCallback(async (token) => {
    if (!platform.device.available) return;
    try {
      const backend = await platform.secrets.backend();
      if (backend === 'unavailable') return;
      const pk = await platform.device.ensure();
      if (!pk) return;
      await hubFetch('/v1/users/devices', {
        method: 'POST', token,
        body: { pk_auth_ed25519: pk, label: t('device.this_device') },
      });
    } catch (err) {
      console.warn('device not registered:', err.message);
    }
  }, []);

  const authCtx = {
    user,
    login: async (username, password) => {
      let token, refreshToken;
      if (window.MeshBayKeys) {
        const data = await window.MeshBayKeys.loginAndRecover(username, password);
        token = data.accessToken;
        refreshToken = data.refreshToken;
        // The only thing sign-in produces: the key that opens a node's bundle.
        // Which identity we use is decided per node, when we get there.
        _bundleKey = data.bundleKey;
        await _storeBundleKey(_bundleKey);
      } else {
        const data = await hubFetch('/v1/users/login', {
          method: 'POST',
          body: { username, password },
        });
        token = data.access_token;
        refreshToken = data.refresh_token;
      }
      const me = await hubFetch('/v1/users/me', { token });
      const u = { username, userId: me.user_id, token, refreshToken, role: me.role };
      // On a desktop build, remember this device so the next launch does not ask
      // for the passphrase again. The key is generated and held by the main
      // process; what travels here is only its public half.
      await registerThisDevice(token);
      // setAuth, not saveAuth: it is the one writer that also updates the copy
      // hubFetch renews from. Storing the session without it left the renewal
      // path with no refresh token to present.
      setAuth(u);
      setUser(u);
    },
    logout: () => {
      // Navigating away leaves transfers running; signing out does not. They
      // are moving data on tokens that are about to stop being ours.
      transfers.reset();
      setAuth(null);
      setUser(null);
      setGroups([]);
      navigate('/login');
    },
  };

  // Group membership is baked into the access token at login and the hub does not
  // push updates, so someone invited after they signed in carries a token that
  // says they are in nothing. Refreshing re-reads membership from the database.
  // Goes through refreshAccessToken like everything else. It used to call the
  // endpoint here and keep only the access token, dropping the rotated refresh
  // token that came back with it — so the refresh token was spent on first use,
  // and presenting the spent one again revoked the whole family. Which is how
  // a session that should last a month ended at "invalid token" with signing
  // out as the only way back.
  const refreshAuth = useCallback(() => refreshAccessToken(), []);

  let page;
  // A desktop build with no hub configured cannot do anything at all, so it
  // asks before showing a sign-in form that could not work. Deliberately not
  // defaulted to meshbay.org: a client that picks its own hub is a client that
  // can be pointed at one.
  if (needsHub) {
    page = html`<${FirstRunPage} onSet=${() => setNeedsHub(false)} />`;
  } else if (!deviceTried) {
    // Signing in with this device's key. Showing a form here would be showing
    // one the user is about to be taken past.
    page = html`<p class="page-message">${t('status.connecting')}</p>`;
  } else if (route === '/login' || route === '/register') {
    page = route === '/register'
      ? html`<${RegisterPage} />`
      : html`<${LoginPage} />`;
  } else if (!user) {
    page = html`<${LoginPage} />`;
  } else if (route === '/search') {
    page = html`<${SearchPage} />`;
  } else if (route === '/explore') {
    page = html`<${ExplorePage} token=${user.token}
      myGroupIds=${groups.map(g => g.id)} />`;
  } else if (route === '/create-group') {
    page = html`<${CreateGroupPage} token=${user.token}
      onCreated=${() => {
        hubFetch('/v1/groups/mine', { token: user.token })
          .then(data => setGroups(data.groups || []))
          .catch(() => {});
      }} />`;
  } else if (route === '/node' && platform.capabilities.nodeAdmin && hasNodeKey) {
    page = html`<${NodePage} token=${user.token} username=${user.username}
      userId=${user.userId} groups=${groups} />`;
  } else if (route.startsWith('/group/')) {
    const groupId = route.slice(7);
    const group = groups.find(g => g.id === groupId);
    page = html`<${GroupPage}
      groupId=${groupId} group=${group} token=${user.token}
      username=${user.username} userId=${user.userId}
      userPrefs=${userPrefs}
      onRefreshAuth=${refreshAuth} onJoined=${dismissGroupNotifications}
      onGroupUpdated=${updateGroup} onPresence=${notePresence}
      onLeft=${handleLeftGroup} />`;
  } else if (route === '/admin') {
    page = (user.role === 'moderator' || user.role === 'admin')
      ? html`<${AdminPage} token=${user.token} />`
      : html`<${HomePage} groups=${groups} notifications=${notifications}
          onMarkRead=${markRead} onPurge=${purgeNotifications} />`;
  } else if (route === '/settings') {
    page = html`<${SettingsPage} user=${user} theme=${theme}
      onThemeChange=${setTheme} groups=${groups}
      onPrefsChange=${(p) => {
        if ('notifications_disabled' in p) {
          setNotifDisabled(p.notifications_disabled);
          if (p.notifications_disabled) { setNotifications([]); setUnreadCount(0); }
          else fetchNotifications();
        }
        setUserPrefs(prev => ({ ...prev, ...p }));
      }} />`;
  } else if (route === '/profile') {
    page = html`<${ProfilePage} user=${user} onLogout=${authCtx.logout} />`;
  } else {
    page = html`<${HomePage} groups=${groups} notifications=${notifications}
      onMarkRead=${markRead} onPurge=${purgeNotifications} />`;
  }

  return html`
    <${AuthContext.Provider} value=${authCtx}>
      <${Nav}
        user=${user}
        theme=${theme}
        onThemeChange=${changeTheme}
        onLogout=${authCtx.logout}
        onMenuToggle=${() => setMenuOpen(o => !o)}
        unreadCount=${unreadCount} hubUnset=${needsHub} />
      <div class="layout">
        ${user && html`<${Sidebar}
          groups=${groups}
          presence=${presence}
          route=${route}
          menuOpen=${menuOpen}
          role=${user.role}
          hasNodeKey=${hasNodeKey} />`}
        ${menuOpen && html`<div class="overlay visible"
          onClick=${() => setMenuOpen(false)} />`}
        <main class="main">
          ${page}
        </main>
      </div>
    <//>
  `;
}

// ── Boot ─────────────────────────────────────────────────────────────────────

// Catalogues are fetched, so the first render waits for one: mounting earlier
// would paint the interface in English and then swap every string. initLocale()
// falls back to English rather than rejecting, so this cannot strand the page.
const mount = () => render(html`<${App} />`, document.getElementById('app'));
initLocale().then(mount, (err) => {
  // Nothing in initLocale() is supposed to reject. If something does, an
  // English interface is still an interface; an unhandled rejection here is a
  // blank page.
  console.error('[MeshBay] locale init failed, continuing in English:', err);
  mount();
});