/ldg/ Collage Script

Updated version of https://rentry.org/ldgcollage
This version adds support for catbox/litterbox and adds some failsafes to prevent video failures when tabbing away during processing (this is all done by Fable)

Last Changes as of 2026-08-06 (written by Fable)

  • 2026-08-06 - support uguu.se, show thumbnails of external videos in highlight review modal page
  • 2026-08-03 - support catbox, adds some failsafes to prevent video failures when tabbing away during processing
   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
// ==UserScript==
// @name         4chan Thumbnail Viewer & Collage Creator
// @namespace    http://tampermonkey.net/
// @version      1.3.0
// @description  Mark posts as highlights on the thread or in a thumbnail grid, review your selection, and make collages (image or video) out of them. Also supports custom collages via drag-and-drop, and external media linked via files.catbox.moe / litter.catbox.moe / uguu.se.
// @match        https://boards.4channel.org/*/thread/*
// @match        https://boards.4chan.org/*/thread/*
// @require      https://cdn.jsdelivr.net/npm/fix-webm-duration@1.0.6/fix-webm-duration.js
// @grant        GM_xmlhttpRequest
// @connect      i.4cdn.org
// @connect      files.catbox.moe
// @connect      litter.catbox.moe
// @connect      uguu.se
// ==/UserScript==

(function() {
    'use strict';

    // =========================
    // 1. CSS Styles
    // =========================
    const style = document.createElement('style');
    style.innerHTML = `
        /* Base highlight button */
        .highlight-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background: rgba(255,255,0,0.7);
            border: 1px solid #000;
            padding: 2px 5px;
            cursor: pointer;
            z-index: 10;
            font-weight: bold;
        }
        .highlighted {
            border: 3px solid red !important;
        }
        /* Inline highlight button for external links (catbox/litter/uguu) */
        .ext-highlight-btn {
            display: inline-block;
            background: rgba(255,255,0,0.7);
            border: 1px solid #000;
            padding: 0px 4px;
            margin-left: 4px;
            cursor: pointer;
            font-weight: bold;
            border-radius: 3px;
            user-select: none;
        }
        /* Generic overlay for views */
        .overlay {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.8);
            z-index: 1000;
            overflow: auto;
            padding: 10px;
            display: flex;
            flex-direction: column;
        }
        .overlay-content {
            flex: 1;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            position: relative;
        }
        /* Info button and content */
        .overlay-info-button {
            position: absolute;
            top: 10px;
            left: 10px;
            background: #008;
            color: #fff;
            border: none;
            padding: 4px 8px;
            cursor: pointer;
            z-index: 1100;
            border-radius: 3px;
            font-size: 14px;
        }
        .overlay-info-content {
            position: absolute;
            top: 45px;
            left: 10px;
            background: rgba(0,0,0,0.7);
            color: #fff;
            font-size: 12px;
            padding: 5px;
            border-radius: 3px;
            z-index: 1100;
            display: none;
            max-width: 300px;
        }
        .overlay-close-button {
            position: absolute;
            top: 10px;
            left: 70px;  /* Adjust this value to position it right next to the '?' button */
            background: red;
            color: #fff;
            border: none;
            padding: 4px 8px;
            cursor: pointer;
            z-index: 1100;
            border-radius: 3px;
            font-size: 14px;
        }
        /* Thumbnail item */
        .thumb-item {
            margin: 5px;
            position: relative;
            cursor: pointer;
        }
        .thumb-item img {
            transition: all 0.3s;
            /* Default unexpanded size */
            max-width: 150px;
            max-height: 150px;
        }
        /* Selected thumbnails get a green border */
        .thumb-item.selected {
            outline: 4px solid #0f0;
        }
        /* Options (Collage) menu in bottom right */
        .chan-hv-options-menu {
            position: fixed;
            bottom: 10px;
            right: 10px;
            background: rgba(0,0,0,0.8);
            padding: 5px;
            border-radius: 3px;
            z-index: 1001;
        }
        .chan-hv-menu-header {
            cursor: pointer;
            color: #fff;
            font-size: 16px;
            user-select: none;
        }
        .chan-hv-menu-content {
            display: none;
            margin-top: 5px;
        }
        .chan-hv-menu-content button {
            display: block;
            margin: 3px 0;
            background: #008;
            color: #fff;
            border: none;
            padding: 5px 10px;
            cursor: pointer;
            font-size: 14px;
        }
        /* Collage button */
        .collage-btn {
            position: fixed;
            top: 10px;
            right: 10px;
            z-index: 1100;
            padding: 8px 12px;
            background: #080;
            color: #fff;
            border: none;
            cursor: pointer;
            font-size: 14px;
        }
        /* Zoom slider styling */
        .zoom-slider {
            width: 200px;
        }
        /* Thread Thumbnails view */
        .thumbnails-grid img {
            margin: 5px;
        }
        /* Remove preset image size limits for thread view */
        .thumbnails-grid .thumb-item img {
            max-width: none;
            max-height: none;
        }
        /* Header image input container in review view */
        .header-input-container {
            margin-bottom: 10px;
            color: #fff;
            font-size: 16px;
            background-color: rgba(0, 0, 0, 0.5);
            padding: 8px;
            border-radius: 5px;
            width: 100%;
            text-align: center;
        }
        /* Review highlights view layout */
        .review-highlights-container {
            display: block !important;
        }
        .thumbs-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
        }
        .review-highlights-container .thumbs-container {
             margin-top: 90px;
        }
        /* Counter style - NEW CENTERED LAYOUT */
        #selected-counter-container {
            position: absolute;
            top: 50px;
            left: 50%;
            transform: translateX(-50%);
            text-align: center;
            color: #fff;
            font-size: 16px;
            z-index: 1050;
            pointer-events: none; /* Make it non-interactive */
        }
        #selected-counter {
            margin-bottom: 5px;
        }
        #selection-hint {
            font-size: 12px;
            color: #ccc;
        }
        /* Custom collage drop zone */
        .custom-collage-container .drop-zone {
            width: 95%;
            height: calc(100% - 100px); /* Adjust height to fill space */
            border: 3px dashed #555;
            border-radius: 10px;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            align-content: flex-start;
            padding: 10px;
            margin-top: 90px; /* Space for the counter */
            color: #888;
            font-size: 20px;
            transition: background-color 0.3s, border-color 0.3s;
            overflow-y: auto; /* Allow scrolling within the drop zone */
        }
        .custom-collage-container .drop-zone.drag-over {
            background-color: rgba(255, 255, 255, 0.1);
            border-color: #aaa;
        }
        /* Lightbox overlay for expanded media */
        .lightbox-overlay {
            position: fixed;
            top: 0; left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0,0,0,0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1200;
        }
        .lightbox-overlay > * {
            max-width: 90vw;
            max-height: 90vh;
            object-fit: contain;
        }
        /* Video processing overlay */
        #processing-overlay {
            flex-direction: column;
        }
        #processing-message {
            margin-top: 20px;
        }
        .spinner {
            border: 8px solid #f3f3f3;
            border-top: 8px solid #3498db;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            animation: spin 1.5s linear infinite;
        }
        /* Non-blocking notification toast */
        .chan-hv-toast {
            position: fixed;
            bottom: 60px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0,0,0,0.85);
            color: #ffd24d;
            padding: 10px 16px;
            border-radius: 5px;
            z-index: 10000;
            font-size: 14px;
            max-width: 80vw;
            text-align: center;
            pointer-events: none;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    `;
    document.head.appendChild(style);

    // =========================
    // 2. Global Variables & Scroll Management
    // =========================
    let selectedHeaderImage = null; // Object: { src, width, height }
    let highlightedImages = [];
    let originalBodyOverflowState = null; // For robust scroll lock management

    function lockBodyScroll() {
        if (originalBodyOverflowState === null) {
            originalBodyOverflowState = document.body.style.overflow;
            document.body.style.overflow = 'hidden';
        }
    }

    function unlockBodyScroll() {
        if (originalBodyOverflowState !== null) {
            document.body.style.overflow = originalBodyOverflowState;
            originalBodyOverflowState = null;
        }
    }

    function getThreadKey() {
        const threadMatch = window.location.href.match(/thread\/(\d+)/);
        return threadMatch ? `highlightedImages_${threadMatch[1]}` : 'highlightedImages';
    }

    function loadHighlights() {
        const saved = localStorage.getItem(getThreadKey());
        if (saved) {
            try {
                highlightedImages = JSON.parse(saved);
            } catch (e) {
                console.error("Failed to parse saved highlights:", e);
            }
        }
    }

    function saveHighlights() {
        localStorage.setItem(getThreadKey(), JSON.stringify(highlightedImages));
    }


    // =========================
    // Global: UI Update Functions
    // =========================
    function updateReviewCounter() {
      const counterDiv = document.getElementById('selected-counter');
      if (counterDiv) {
        const activeContainer = document.querySelector('.review-highlights-container, .custom-collage-container');
        if (activeContainer) {
            const count = activeContainer.querySelectorAll('.thumb-item.selected').length;
            counterDiv.textContent = 'Selected: ' + count;
        }
      }
    }

    // Helper: is a given source (URL string or File) a video?
    function isVideoSource(src) {
        if (src instanceof File) return src.type.startsWith('video/');
        const clean = String(src).split(/[?#]/)[0].toLowerCase();
        return clean.endsWith('.webm') || clean.endsWith('.mp4');
    }

    function updateCollageButtonText() {
        const collageBtn = document.querySelector('.collage-btn');
        const activeContainer = document.querySelector('.review-highlights-container, .custom-collage-container');
        if (!collageBtn || !activeContainer) return;

        const selectedItems = activeContainer.querySelectorAll('.thumb-item.selected');
        let hasVideo = false;

        for (const item of selectedItems) {
            const img = item.querySelector('img');
            const src = img.dataset.full || img.fileData;
            if (isVideoSource(src)) {
                hasVideo = true;
                break;
            }
        }

        collageBtn.textContent = hasVideo ? "Create Video Collage" : "Create Image Collage";
    }

    // =========================
    // 3. Add Highlight Buttons to Posts
    // =========================
    function addHighlightButtons() {
    const posts = document.querySelectorAll('.post');
    const savedFullSrcs = highlightedImages.map(h => h.fullSrc);

    posts.forEach(post => {
        if (post.querySelector('.highlight-btn')) return; // Skip if already added
        const thumbLink = post.querySelector('a.fileThumb');
        if (!thumbLink) return;
        const img = thumbLink.querySelector('img');
        if (!img) return;

        const fullSrc = thumbLink.href;
        const btn = document.createElement('div');
        btn.textContent = '★';
        btn.className = 'highlight-btn';
        post.style.position = 'relative';

        // Restore highlight state from saved data
        if (savedFullSrcs.includes(fullSrc)) {
            post.classList.add('highlighted');
            btn.style.background = 'rgba(0,255,0,0.7)';
        }

        btn.addEventListener('click', e => {
            e.stopPropagation();
            const index = highlightedImages.findIndex(item => item.fullSrc === fullSrc);
            if (post.classList.contains('highlighted')) {
                post.classList.remove('highlighted');
                btn.style.background = 'rgba(255,255,0,0.7)';
                if (index > -1) highlightedImages.splice(index, 1);
            } else {
                post.classList.add('highlighted');
                btn.style.background = 'rgba(0,255,0,0.7)';
                highlightedImages.push({ post: null, thumbSrc: img.src, fullSrc });
            }
            saveHighlights(); // <--- this is what persists it
        });

        post.appendChild(btn);
    });
}

    // =========================
    // 3b. External Media Link Support (catbox / litter / uguu)
    // =========================
    // Matches media links on supported external hosts:
    //   https://files.catbox.moe/xxxxxx.<ext>     (permanent)
    //   https://litter.catbox.moe/xxxxxx.<ext>    (temporary, expires)
    //   https://uguu.se/xxxxxx.<ext> and any subdomain like
    //   https://a.uguu.se/xxxxxx.<ext>            (temporary, expires)
    // Videos (webm/mp4) AND images (jpg/png/gif) are supported.
    const EXTERNAL_LINK_REGEX = /https?:\/\/(?:(?:files|litter)\.catbox\.moe|(?:[a-z0-9-]+\.)?uguu\.se)\/[^\s<>"'()]+?\.(?:webm|mp4|jpe?g|png|gif)/gi;
    const EXTERNAL_HOST_HINT = /(?:files|litter)\.catbox\.moe|uguu\.se/;

    function isExternalUrl(src) {
        return typeof src === 'string' && EXTERNAL_HOST_HINT.test(src);
    }

    function externalHostLabel(url) {
        if (url.includes('litter.catbox.moe')) return 'litter video (temp)';
        if (url.includes('catbox.moe')) return 'catbox video';
        if (url.includes('uguu.se')) return 'uguu video (temp)';
        return 'external video';
    }

    // Generate a placeholder thumbnail (data URL) for an external video link.
    // We don't download the whole video at highlight time; a real frame-grab
    // thumbnail is generated lazily when the Review Highlights view is opened
    // (see upgradeExternalThumbs), and cached afterwards.
    function makeExternalVideoPlaceholder(url) {
        const canvas = document.createElement('canvas');
        canvas.width = 150;
        canvas.height = 150;
        const ctx = canvas.getContext('2d');
        ctx.fillStyle = '#1a1a2e';
        ctx.fillRect(0, 0, 150, 150);
        ctx.fillStyle = '#e0e0e0';
        ctx.font = '48px sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText('▶', 75, 78);
        ctx.font = 'bold 13px sans-serif';
        ctx.fillText(externalHostLabel(url), 75, 110);
        ctx.font = '11px sans-serif';
        let name = url.split('/').pop();
        if (name.length > 22) name = name.slice(0, 19) + '…';
        ctx.fillText(name, 75, 130);
        return canvas.toDataURL('image/png');
    }

    // Initial thumbnail for a newly-highlighted external URL:
    //  - images: hotlink the image itself (real thumbnail immediately)
    //  - videos: placeholder, upgraded later in the review view
    function externalThumbFor(url) {
        return isVideoSource(url) ? makeExternalVideoPlaceholder(url) : url;
    }

    // Download a video and capture a real frame as a small JPEG data URL,
    // with a play-badge drawn on top so it's still recognizable as a video.
    async function generateVideoThumb(url) {
        const blob = await fetchImageAsBlob(url);
        const blobUrl = URL.createObjectURL(blob);
        return new Promise((resolve, reject) => {
            const video = document.createElement('video');
            video.muted = true;
            video.playsInline = true;
            video.onloadeddata = () => {
                const d = video.duration;
                video.currentTime = (isFinite(d) && d > 0) ? Math.min(1, d / 2) : 0;
            };
            video.onseeked = () => {
                try {
                    const canvas = document.createElement('canvas');
                    const maxSide = 250;
                    const s = Math.min(1, maxSide / Math.max(video.videoWidth, video.videoHeight));
                    canvas.width = Math.max(1, Math.round(video.videoWidth * s));
                    canvas.height = Math.max(1, Math.round(video.videoHeight * s));
                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                    // Play badge
                    const cx = canvas.width / 2, cy = canvas.height / 2;
                    const r = Math.min(canvas.width, canvas.height) * 0.14;
                    ctx.fillStyle = 'rgba(0,0,0,0.45)';
                    ctx.beginPath(); ctx.arc(cx, cy, r * 1.6, 0, Math.PI * 2); ctx.fill();
                    ctx.fillStyle = 'rgba(255,255,255,0.9)';
                    ctx.beginPath();
                    ctx.moveTo(cx - r * 0.5, cy - r * 0.85);
                    ctx.lineTo(cx - r * 0.5, cy + r * 0.85);
                    ctx.lineTo(cx + r * 0.95, cy);
                    ctx.closePath(); ctx.fill();
                    const dataUrl = canvas.toDataURL('image/jpeg', 0.85);
                    URL.revokeObjectURL(blobUrl);
                    resolve(dataUrl);
                } catch (e) {
                    URL.revokeObjectURL(blobUrl);
                    reject(e);
                }
            };
            video.onerror = () => {
                URL.revokeObjectURL(blobUrl);
                reject(new Error('Could not decode video for thumbnail: ' + url));
            };
            video.src = blobUrl;
        });
    }

    // Lazily replace placeholder thumbnails of highlighted external videos
    // with real frame grabs. Runs one download at a time (external videos can
    // be large), stops as soon as the container is closed, and persists the
    // generated thumbnails so each video is only downloaded once.
    let thumbUpgradeRunning = false;
    async function upgradeExternalThumbs(container) {
        if (thumbUpgradeRunning) return;
        thumbUpgradeRunning = true;
        try {
            const pending = highlightedImages.filter(item =>
                isExternalUrl(item.fullSrc) &&
                isVideoSource(item.fullSrc) &&
                !item.realThumb
            );
            for (const item of pending) {
                if (!document.body.contains(container)) return; // view closed — stop downloading
                try {
                    const thumb = await generateVideoThumb(item.fullSrc);
                    item.thumbSrc = thumb;
                    item.realThumb = true;
                    saveHighlights();
                    // Update any currently-visible copies of this thumbnail
                    document.querySelectorAll('.thumb-item img').forEach(img => {
                        if (img.dataset.full === item.fullSrc) {
                            img.src = thumb;
                            img.dataset.thumb = thumb;
                        }
                    });
                } catch (e) {
                    // Expired litter/uguu link, blocked request, etc. — keep placeholder.
                    console.warn('Thumbnail generation failed for', item.fullSrc, e);
                }
            }
        } finally {
            thumbUpgradeRunning = false;
        }
    }

    function isExternalHighlighted(url) {
        return highlightedImages.some(item => item.fullSrc === url);
    }

    function refreshExternalBtns(url) {
        document.querySelectorAll('.ext-highlight-btn').forEach(b => {
            if (url && b.dataset.extUrl !== url) return;
            b.style.background = isExternalHighlighted(b.dataset.extUrl)
                ? 'rgba(0,255,0,0.7)' : 'rgba(255,255,0,0.7)';
        });
    }

    function createExternalToggleBtn(url) {
        const btn = document.createElement('span');
        btn.className = 'ext-highlight-btn';
        btn.textContent = '★';
        btn.title = 'Add/remove this external file from highlights';
        btn.dataset.extUrl = url;
        btn.style.background = isExternalHighlighted(url) ? 'rgba(0,255,0,0.7)' : 'rgba(255,255,0,0.7)';
        return btn;
    }

    // Delegated click handler: works for star buttons inside 4chan X's
    // cloned posts (hover previews / inline quotes), which are cloneNode'd
    // and would otherwise lose per-element listeners. Capture phase so we
    // beat 4chan X's own handlers.
    document.addEventListener('click', e => {
        const btn = e.target.closest && e.target.closest('.ext-highlight-btn');
        if (!btn) return;
        e.preventDefault();
        e.stopPropagation();
        const url = btn.dataset.extUrl;
        if (!url) return;
        if (isExternalHighlighted(url)) {
            removeFromHighlights(url);
        } else {
            highlightedImages.push({ post: null, thumbSrc: externalThumbFor(url), fullSrc: url });
        }
        saveHighlights();
        refreshExternalBtns(url);
    }, true);

    // --- 4chan X coexistence -------------------------------------------------
    // 4chan X's Linkifier ONLY converts URLs found in plain text nodes (it skips
    // text inside <a>), and its pass over pre-existing anchors only accepts
    // 4chan's own image hosts (SW.yotsuba.isLinkified -> ImageHost.test). So if
    // we wrap an external URL in our own <a> before 4chan X processes the post,
    // 4chan X can never add its "(embed)" button to it.
    //
    // Strategy:
    //   1. Anchor pass (always, purely additive): put our ★ after any existing
    //      external anchor — after 4chan X's "(embed)" button when present.
    //   2. Text pass (destructive linkification): DEFERRED. Only run once we're
    //      confident 4chan X isn't going to linkify this message itself
    //      (its '4chanXInitFinished' event fired, or a grace timeout passed,
    //      and the URL is still plain text — e.g. vanilla 4chan, or 4chan X
    //      with the Linkify option disabled).
    // New posts inserted by 4chan X's thread updater are already linkified
    // before insertion, so they're handled instantly by the anchor pass.

    let fourchanXFinished = false;
    const pendingExternalMsgs = new Set();

    document.addEventListener('4chanXInitFinished', () => {
        fourchanXFinished = true;
        // Anything still plain text at this point is ours to linkify.
        pendingExternalMsgs.forEach(msg => {
            pendingExternalMsgs.delete(msg);
            processExternalMsg(msg, true);
        });
    });

    function has4chanX() {
        return document.documentElement.classList.contains('fourchan-x');
    }

    // Text of the message *excluding* anchors, with <wbr> splits joined
    // (textContent naturally concatenates across <wbr>). Non-destructive.
    function plainExternalUrlsIn(msg) {
        const clone = msg.cloneNode(true);
        clone.querySelectorAll('a').forEach(a => a.remove());
        EXTERNAL_LINK_REGEX.lastIndex = 0;
        return clone.textContent.match(EXTERNAL_LINK_REGEX) || [];
    }

    // Pass 1: additive only. Star every external anchor, positioned after
    // 4chan X's "(embed)" button when one exists.
    function externalAnchorPass(msg) {
        msg.querySelectorAll('a[href*="files.catbox.moe"], a[href*="litter.catbox.moe"], a[href*="uguu.se"]').forEach(a => {
            if (a.dataset.extStar) return;
            EXTERNAL_LINK_REGEX.lastIndex = 0;
            const m = a.href.match(EXTERNAL_LINK_REGEX);
            if (!m) return;
            a.dataset.extStar = '1';
            let insertAfter = a;
            const next = a.nextElementSibling; // skips the " " text node 4chan X adds
            if (next && next.classList.contains('embedder')) insertAfter = next;
            insertAfter.insertAdjacentElement('afterend', createExternalToggleBtn(m[0]));
        });
    }

    // Pass 2: destructive. Linkify plain-text external URLs ourselves.
    // Must only run when 4chan X definitely won't handle this message.
    function externalTextPass(msg) {
        // 4chan splits long strings across text nodes with <wbr>; merge first.
        msg.querySelectorAll('wbr').forEach(w => w.remove());
        msg.normalize();

        const walker = document.createTreeWalker(msg, NodeFilter.SHOW_TEXT);
        const textNodes = [];
        while (walker.nextNode()) {
            const node = walker.currentNode;
            if (node.parentElement && node.parentElement.closest('a')) continue;
            EXTERNAL_LINK_REGEX.lastIndex = 0;
            if (EXTERNAL_LINK_REGEX.test(node.nodeValue)) textNodes.push(node);
        }

        textNodes.forEach(node => {
            const text = node.nodeValue;
            const frag = document.createDocumentFragment();
            let last = 0;
            let match;
            EXTERNAL_LINK_REGEX.lastIndex = 0;
            while ((match = EXTERNAL_LINK_REGEX.exec(text)) !== null) {
                frag.appendChild(document.createTextNode(text.slice(last, match.index)));
                const a = document.createElement('a');
                a.href = match[0];
                a.textContent = match[0];
                a.target = '_blank';
                a.rel = 'noreferrer';
                frag.appendChild(a);
                last = match.index + match[0].length;
            }
            frag.appendChild(document.createTextNode(text.slice(last)));
            node.parentNode.replaceChild(frag, node);
        });
        // Stars are added by the anchor pass — single code path for all anchors.
        externalAnchorPass(msg);
    }

    function processExternalMsg(msg, force) {
        if (!document.body.contains(msg)) return;
        externalAnchorPass(msg);
        if (plainExternalUrlsIn(msg).length === 0) return; // fully handled

        if (force || fourchanXFinished) {
            // 4chan X is done (or absent past grace) and left this as plain
            // text — its Linkify is off or it isn't installed. Ours now.
            externalTextPass(msg);
            return;
        }
        // Defer: give 4chan X a chance to linkify it first.
        if (msg.dataset.extDeferred) {
            pendingExternalMsgs.add(msg);
            return;
        }
        msg.dataset.extDeferred = '1';
        pendingExternalMsgs.add(msg);
        const grace = has4chanX() ? 3000 : 750;
        setTimeout(() => {
            if (pendingExternalMsgs.delete(msg)) processExternalMsg(msg, true);
        }, grace);
    }

    function addExternalButtons() {
        document.querySelectorAll('.postMessage').forEach(msg => {
            if (!EXTERNAL_HOST_HINT.test(msg.textContent)) return;
            processExternalMsg(msg, false);
        });
    }

    // =========================
    // 4. Unified Thumbnail Behavior
    // =========================
    function setupUnifiedThumbnailBehavior(container, context = 'default') {
        const thumbItems = container.querySelectorAll('.thumb-item');
        thumbItems.forEach(item => {
            const img = item.querySelector('img');
            const fullSrc = img.dataset.full || img.fileData;

            if (!img.dataset.thumb) {
                img.dataset.thumb = img.src;
            }
            item.addEventListener('click', e => {
                if (e.ctrlKey) {
                    if (context === 'review') {
                        item.classList.toggle('selected');
                    } else { // 'default' context for thread thumbnails view
                        if (item.classList.contains('selected')) {
                            item.classList.remove('selected');
                            removeFromHighlights(fullSrc);
                        } else {
                            item.classList.add('selected');
                            addToHighlights(fullSrc, img.dataset.thumb);
                        }
                        saveHighlights();
                    }
                    updateReviewCounter();
                    updateCollageButtonText(); // Update button text on selection change
                } else {
                    const mediaList = Array.from(container.querySelectorAll('.thumb-item img')).map(i => {
                        const src = i.dataset.full || i.fileData;
                        return { src, type: isVideoSource(src) ? 'video' : 'image' };
                    });
                    const currentIndex = mediaList.findIndex(m => m.src === fullSrc);
                    showLightbox(mediaList, currentIndex);
                }
                e.stopPropagation();
            });
        });
        container.tabIndex = 0;
        container.focus();
    }
    function addToHighlights(fullSrc, thumbSrc) {
        if (!highlightedImages.find(item => item.fullSrc === fullSrc)) {
            highlightedImages.push({ post: null, thumbSrc, fullSrc });
        }
    }
    function removeFromHighlights(fullSrc) {
        const idx = highlightedImages.findIndex(item => item.fullSrc === fullSrc);
        if (idx > -1) highlightedImages.splice(idx, 1);
    }

    // =========================
    // Lightbox Overlay with Navigation (Handles Video and Files)
    // =========================
    async function showLightbox(mediaList, currentIndex) {
        let currentMediaElement = null;
        const overlay = document.createElement('div');
        overlay.className = 'lightbox-overlay';

        async function showMedia(index) {
            if (currentMediaElement) {
                if(currentMediaElement.src.startsWith('blob:')) {
                    URL.revokeObjectURL(currentMediaElement.src);
                }
                overlay.removeChild(currentMediaElement);
            }
            const mediaItem = mediaList[index];
            if (!mediaItem) return;

            let mediaUrl;
            if (mediaItem.src instanceof File) {
                mediaUrl = URL.createObjectURL(mediaItem.src);
            } else {
                mediaUrl = mediaItem.src;
            }

            if (mediaItem.type === 'video') {
                currentMediaElement = document.createElement('video');
                currentMediaElement.autoplay = true;
                currentMediaElement.loop = true;
                currentMediaElement.controls = true;
                currentMediaElement.muted = true;
            } else {
                currentMediaElement = document.createElement('img');
            }
            currentMediaElement.src = mediaUrl;
            overlay.appendChild(currentMediaElement);
        }

        function keyHandler(e) {
            if (e.key === 'ArrowLeft') {
                currentIndex = (currentIndex - 1 + mediaList.length) % mediaList.length;
                showMedia(currentIndex);
                e.preventDefault();
            } else if (e.key === 'ArrowRight') {
                currentIndex = (currentIndex + 1) % mediaList.length;
                showMedia(currentIndex);
                e.preventDefault();
            } else if (e.key === 'Escape') {
                cleanup();
                e.preventDefault();
            }
        }
        function cleanup() {
            if(currentMediaElement && currentMediaElement.src.startsWith('blob:')) {
                URL.revokeObjectURL(currentMediaElement.src);
            }
            document.body.removeChild(overlay);
            window.removeEventListener('keydown', keyHandler);
        }

        window.addEventListener('keydown', keyHandler);
        overlay.addEventListener('click', cleanup);
        await showMedia(currentIndex);
        document.body.appendChild(overlay);
    }

    // =========================
    // 5. Create a Generic Overlay View
    // =========================
    function createOverlayView(contentGenerator, closeCallback) {
        const existing = document.querySelector('.overlay');
        if (existing) {
            existing.parentNode.removeChild(existing);
        }
        lockBodyScroll();

        const overlay = document.createElement('div');
        overlay.className = 'overlay';
        overlay.tabIndex = 0;
        overlay.addEventListener('keydown', e => {
            if (e.key === 'Escape' && !document.querySelector('.lightbox-overlay')) {
                cleanup();
            }
        });
        const infoButton = document.createElement('button');
        infoButton.className = 'overlay-info-button';
        infoButton.textContent = '?';
        const infoContent = document.createElement('div');
        infoContent.className = 'overlay-info-content';
        infoContent.textContent = 'Click: Preview media. Ctrl+Click: Select/Deselect for collage. Esc: Close view.';
        infoButton.addEventListener('click', () => {
            infoContent.style.display = (infoContent.style.display === 'none' || infoContent.style.display === '')
                ? 'block'
                : 'none';
        });
        const closeButton = document.createElement('button');
        closeButton.className = 'overlay-close-button';
        closeButton.textContent = 'X';
        closeButton.addEventListener('click', cleanup);

        overlay.appendChild(infoButton);
        overlay.appendChild(infoContent);
        overlay.appendChild(closeButton);
        const content = contentGenerator();
        overlay.appendChild(content);
        overlay.focus();
        function cleanup() {
            unlockBodyScroll();
            document.body.removeChild(overlay);
            if (closeCallback) closeCallback();
        }
        overlay.addEventListener('click', e => {
            if (e.target === overlay) cleanup();
        });
        document.body.appendChild(overlay);
    }

    // =========================
    // 6. Review Highlights View
    // =========================
    function showReviewHighlightsView() {
        const contentGenerator = () => {
            const container = document.createElement('div');
            container.className = 'overlay-content review-highlights-container';
            const headerContainer = document.createElement('div');
            headerContainer.className = 'header-input-container';
            headerContainer.innerHTML = `<label style="margin-right:5px;">Header image (optional):</label>`;
            const headerInput = document.createElement('input');
            headerInput.type = 'file';
            headerInput.accept = 'image/*';
            headerInput.addEventListener('change', e => {
                const file = e.target.files[0];
                if (!file) return;
                const reader = new FileReader();
                reader.onload = function(evt) {
                    const tempImg = new Image();
                    tempImg.onload = function() {
                        selectedHeaderImage = {
                            src: evt.target.result,
                            width: tempImg.naturalWidth,
                            height: tempImg.naturalHeight
                        };
                    };
                    tempImg.src = evt.target.result;
                };
                reader.readAsDataURL(file);
            });
            headerContainer.appendChild(headerInput);
            container.appendChild(headerContainer);

            const counterContainer = document.createElement('div');
            counterContainer.id = 'selected-counter-container';
            counterContainer.innerHTML = `
                <div id="selected-counter">Selected: 0</div>
                <div id="selection-hint">(Ctrl+Click to temporarily select/deselect)</div>
            `;
            container.appendChild(counterContainer);

            const thumbsContainer = document.createElement('div');
            thumbsContainer.className = 'thumbs-container';
            highlightedImages.forEach(item => {
                const thumbDiv = document.createElement('div');
                thumbDiv.className = 'thumb-item selected';
                const img = document.createElement('img');
                img.src = item.thumbSrc;
                img.dataset.thumb = item.thumbSrc;
                img.dataset.full = item.fullSrc;
                thumbDiv.appendChild(img);
                thumbsContainer.appendChild(thumbDiv);
            });
            container.appendChild(thumbsContainer);
            const collageBtn = document.createElement('button');
            collageBtn.className = "collage-btn";
            collageBtn.addEventListener("click", createCollage);
            container.appendChild(collageBtn);
            // Pass 'review' context to enable special deselection loogic
            setTimeout(() => {
                setupUnifiedThumbnailBehavior(thumbsContainer, 'review');
                updateReviewCounter();
                updateCollageButtonText();
                // Replace external-video placeholders with real frame grabs
                // (downloads run in the background, one at a time, and the
                // results are cached in localStorage).
                upgradeExternalThumbs(thumbsContainer);
            }, 0);
            return container;
        };
        createOverlayView(contentGenerator);
    }

    // =========================
    // 6b. Custom Collage View
    // =========================
    function showCustomCollageView() {
        const contentGenerator = () => {
            const container = document.createElement('div');
            container.className = 'overlay-content custom-collage-container';

            const counterContainer = document.createElement('div');
            counterContainer.id = 'selected-counter-container';
            counterContainer.innerHTML = `
                <div id="selected-counter">Selected: 0</div>
                <div id="selection-hint">(Ctrl+Click to select/deselect)</div>
            `;
            container.appendChild(counterContainer);

            const dropZone = document.createElement('div');
            dropZone.className = 'drop-zone thumbs-container';
            dropZone.innerHTML = '<p style="align-self: center; text-align: center;">Drag & Drop Images (jpg, png) or Videos (webm, mp4) Here</p>';
            container.appendChild(dropZone);

            const allowedTypes = ['image/jpeg', 'image/png', 'video/webm', 'video/mp4'];

            const handleFiles = async (files) => {
                const promptText = dropZone.querySelector('p');
                if (promptText) promptText.remove();

                const filePromises = [];
                for (const file of files) {
                    if (!allowedTypes.includes(file.type)) {
                        console.warn(`Skipping unsupported file type: ${file.name} (${file.type})`);
                        continue;
                    }

                    const promise = new Promise(resolve => {
                        const thumbDiv = document.createElement('div');
                        thumbDiv.className = 'thumb-item selected';
                        const imgThumb = document.createElement('img');
                        imgThumb.fileData = file;
                        thumbDiv.appendChild(imgThumb);

                        if (file.type.startsWith('image/')) {
                            imgThumb.src = URL.createObjectURL(file);
                            imgThumb.onload = () => resolve(thumbDiv);
                            imgThumb.onerror = () => resolve(null);
                        } else if (file.type.startsWith('video/')) {
                            const video = document.createElement('video');
                            const canvas = document.createElement('canvas');
                            video.src = URL.createObjectURL(file);
                            video.onloadeddata = () => { video.currentTime = Math.min(1, video.duration / 2); };
                            video.onseeked = () => {
                                canvas.width = video.videoWidth;
                                canvas.height = video.videoHeight;
                                canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
                                imgThumb.src = canvas.toDataURL('image/jpeg');
                                URL.revokeObjectURL(video.src);
                                resolve(thumbDiv);
                            };
                            video.onerror = () => resolve(null);
                        }
                    });
                    filePromises.push(promise);
                }

                const thumbDivs = await Promise.all(filePromises);
                thumbDivs.forEach(div => { if (div) dropZone.appendChild(div); });

                setupUnifiedThumbnailBehavior(dropZone, 'review');
                updateReviewCounter();
                updateCollageButtonText();
            };

            dropZone.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation(); dropZone.classList.add('drag-over'); });
            dropZone.addEventListener('dragleave', (e) => { e.preventDefault(); e.stopPropagation(); dropZone.classList.remove('drag-over'); });
            dropZone.addEventListener('drop', (e) => { e.preventDefault(); e.stopPropagation(); dropZone.classList.remove('drag-over'); handleFiles(e.dataTransfer.files); });

            const collageBtn = document.createElement('button');
            collageBtn.className = "collage-btn";
            collageBtn.addEventListener("click", createCollage);
            container.appendChild(collageBtn);

            setTimeout(() => { // Set initial button text
                 updateCollageButtonText();
            }, 0);

            return container;
        };
        createOverlayView(contentGenerator);
    }

    // =========================
    // 7. Thread Thumbnails View
    // =========================
    function showThreadThumbnailsView() {
        const contentGenerator = () => {
            const container = document.createElement('div');
            container.className = 'overlay-content thumbnails-grid';
            const sliderContainer = document.createElement('div');
            sliderContainer.style.textAlign = 'center';
            sliderContainer.style.width = '100%';
            sliderContainer.style.marginBottom = '10px';
            const zoomLabel = document.createElement('label');
            zoomLabel.textContent = 'Zoom: ';
            const zoomSlider = document.createElement('input');
            zoomSlider.type = 'range';
            zoomSlider.className = 'zoom-slider';
            zoomSlider.min = 50;
            zoomSlider.max = 400;
            zoomSlider.value = 100;
            zoomSlider.style.margin = '10px';
            sliderContainer.appendChild(zoomLabel);
            sliderContainer.appendChild(zoomSlider);
            container.appendChild(sliderContainer);
            const thumbsContainer = document.createElement('div');
            thumbsContainer.className = 'thumbs-container';
            const thumbs = document.querySelectorAll('a.fileThumb img');
            thumbs.forEach(imgEl => {
                const thumbDiv = document.createElement('div');
                thumbDiv.className = 'thumb-item';
                const clone = document.createElement('img');
                clone.src = imgEl.src;
                clone.dataset.thumb = imgEl.src;
                const parentLink = imgEl.closest('a.fileThumb');
                clone.dataset.full = parentLink ? parentLink.href : imgEl.src;
                clone.onload = function() {
                    const naturalW = clone.naturalWidth;
                    const baseW = naturalW > 200 ? 200 : naturalW;
                    clone.dataset.baseWidth = baseW;
                    const scale = zoomSlider.value / 100;
                    clone.style.width = (baseW * scale) + 'px';
                };
                if (highlightedImages.some(item => item.fullSrc === clone.dataset.full)) {
                    thumbDiv.classList.add('selected');
                }
                thumbDiv.appendChild(clone);
                thumbsContainer.appendChild(thumbDiv);
            });
            // Also include highlighted external media (catbox/litter/uguu) in
            // the grid so they're visible/toggleable
            highlightedImages.forEach(item => {
                if (isExternalUrl(item.fullSrc)) {
                    const thumbDiv = document.createElement('div');
                    thumbDiv.className = 'thumb-item selected';
                    const clone = document.createElement('img');
                    clone.src = item.thumbSrc;
                    clone.dataset.thumb = item.thumbSrc;
                    clone.dataset.full = item.fullSrc;
                    clone.dataset.baseWidth = 150;
                    thumbDiv.appendChild(clone);
                    thumbsContainer.appendChild(thumbDiv);
                }
            });
            container.appendChild(thumbsContainer);
            // Use default context here for permanent selection
            setTimeout(() => { setupUnifiedThumbnailBehavior(thumbsContainer); }, 0);
            zoomSlider.addEventListener('input', () => {
                const scale = zoomSlider.value / 100;
                const images = thumbsContainer.querySelectorAll('img');
                images.forEach(img => {
                    if (!img.closest('.thumb-item').classList.contains('expanded')) {
                        const base = img.dataset.baseWidth ? parseFloat(img.dataset.baseWidth) : 150;
                        img.style.width = (base * scale) + 'px';
                        img.style.height = 'auto';
                    }
                });
            });
            return container;
        };
        createOverlayView(contentGenerator);
    }

    // =========================
    // 8. Get Collage Items & Create Collage
    // =========================
    function getItemsForCollage() {
        const reviewContainer = document.querySelector('.review-highlights-container');
        const customContainer = document.querySelector('.custom-collage-container');

        if (customContainer) {
            const selectedThumbs = customContainer.querySelectorAll('.thumb-item.selected');
            return Array.from(selectedThumbs).map(thumb => {
                const img = thumb.querySelector('img');
                return { fullSrc: img.fileData, thumbSrc: img.src }; // fullSrc is a File object
            });
        }
        if (reviewContainer) {
            const selectedThumbs = reviewContainer.querySelectorAll('.thumb-item.selected');
            return Array.from(selectedThumbs).map(thumb => {
                const img = thumb.querySelector('img');
                return { fullSrc: img.dataset.full, thumbSrc: img.dataset.thumb };
            });
        }
        return highlightedImages; // Fallback for thread context
    }

    async function createCollage() {
        const isCustomCollage = !!document.querySelector('.custom-collage-container');
        const itemsForCollage = getItemsForCollage();
        if (itemsForCollage.length === 0) {
            alert("No items selected for collage.");
            return;
        }

        const hasVideo = itemsForCollage.some(item => isVideoSource(item.fullSrc));

        if (hasVideo) {
            console.log("Video detected in selection. Switching to video collage mode.");
            createVideoCollage(itemsForCollage, isCustomCollage);
            return;
        }

        createImageCollage(itemsForCollage, isCustomCollage);
    }

    // =========================
    // 8a. Image Collage Creation
    // =========================
    async function createImageCollage(itemsForCollage, isCustomCollage = false) {
        const numCollages = parseInt(prompt("Enter number of collages:", "1"), 10);
        const targetMP = parseFloat(prompt("Enter target megapixels per image (e.g., 1 for 1MP):", "0.3"));
        const targetAspect = parseFloat(prompt("Enter target aspect ratio (e.g., 1 for square, 1.33 for 4:3):", "1"));
        if (!numCollages || !targetMP || !targetAspect) {
            alert("Invalid input.");
            return;
        }

        const targetArea = targetMP * 1e6;
        let L = [];
        const droppedImgs = [];
        for (let i = 0; i < itemsForCollage.length; i++) {
            const imgData = itemsForCollage[i];
            try {
                const dims = await getMediaDimensions(imgData.fullSrc);
                L.push({ src: imgData.fullSrc, width: dims.width, height: dims.height, type: dims.type });
            } catch (err) {
                // Expired litter.catbox.moe / uguu.se links etc. — drop, don't abort.
                const name = (imgData.fullSrc instanceof File) ? imgData.fullSrc.name : String(imgData.fullSrc).split('/').pop();
                droppedImgs.push(name);
                console.warn("Skipping unavailable media:", imgData.fullSrc, err);
            }
        }

        if (droppedImgs.length > 0) {
            showToast(`Skipped ${droppedImgs.length} unavailable file(s) (expired link?): ${droppedImgs.join(', ')}`, 6000);
        }

        if (L.length === 0) {
            alert("No images available for collage.");
            return;
        }

        const collages = roundRobinCollageLayout(L, numCollages, targetArea, selectedHeaderImage, targetAspect);
        if (!collages || collages.length === 0) {
            alert("Collage layout failed.");
            return;
        }

        let collagePromises = collages.map((collage, collageIndex) => {
            return new Promise(resolve => {
                const canvas = document.createElement("canvas");
                canvas.width = collage.width;
                canvas.height = collage.height;
                const ctx = canvas.getContext("2d");
                ctx.fillStyle = "#fff";
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                let placementPromises = collage.placements.map(placement => {
                    return new Promise(r => {
                        fetchImageAsBlob(placement.image.src)
                            .then(blob => {
                                const blobUrl = URL.createObjectURL(blob);
                                const imageEl = new Image();
                                imageEl.onload = function() {
                                    ctx.drawImage(imageEl, placement.x, placement.y, placement.width, placement.height);
                                    URL.revokeObjectURL(blobUrl);
                                    r();
                                };
                                imageEl.onerror = e => { console.error("Error loading image:", placement.image.src, e); r(); };
                                imageEl.src = blobUrl;
                            })
                            .catch(err => { console.error("Fetch/GM_xmlhttpRequest error:", err); r(); });
                    });
                });

                Promise.all(placementPromises).then(() => {
                    const dataUrl = canvas.toDataURL('image/png');
                    const currentUnixTime = Math.floor(Date.now() / 1000);
                    let filename;

                    if (isCustomCollage) {
                        filename = `collage_${currentUnixTime}_${collageIndex + 1}.png`;
                    } else {
                        const url = window.location.href;
                        const boardMatch = url.match(/boards\.4chan(?:nel)?\.org\/([^\/]+)\//);
                        const board = boardMatch ? boardMatch[1] : "unknown";
                        const threadMatch = url.match(/thread\/(\d+)/);
                        const thread = threadMatch ? threadMatch[1] : "unknown";
                        filename = `highlights_${board}_${thread}_${currentUnixTime}_${collageIndex+1}.png`;
                    }

                    const downloadContainer = document.createElement('div');
                    Object.assign(downloadContainer.style, {
                        position: 'fixed', top: '20px', left: '50%', transform: 'translateX(-50%)',
                        background: 'rgba(0, 0, 0, 0.9)', padding: '20px', zIndex: '2000',
                        borderRadius: '10px', color: '#fff', textAlign: 'center'
                    });

                    const pngBtn = document.createElement('button');
                    Object.assign(pngBtn.style, {
                        margin: '10px', padding: '10px', background: '#008', color: '#fff',
                        border: 'none', cursor: 'pointer', fontSize: '16px'
                    });
                    pngBtn.textContent = 'Download Raw .png';
                    pngBtn.addEventListener('click', () => {
                        const a = document.createElement('a'); a.href = dataUrl; a.download = filename;
                        document.body.appendChild(a); a.click(); document.body.removeChild(a);
                        document.body.removeChild(downloadContainer);
                        unlockBodyScroll(); // Restore scroll
                    });

                    const jpgBtn = document.createElement('button');
                    Object.assign(jpgBtn.style, {
                        margin: '10px', padding: '10px', background: '#080', color: '#fff',
                        border: 'none', cursor: 'pointer', fontSize: '16px'
                    });
                    jpgBtn.textContent = 'Download Compressed .jpg';
                    jpgBtn.addEventListener('click', async () => {
                        let quality = 0.92;
                        let blob;
                        do {
                            const jpegDataUrl = canvas.toDataURL('image/jpeg', quality);
                            blob = dataURLToBlob(jpegDataUrl);
                            if (blob.size <= 3.99 * 1024 * 1024) {
                                const a = document.createElement('a'); a.href = URL.createObjectURL(blob);
                                a.download = filename.replace('.png', '.jpg');
                                document.body.appendChild(a); a.click(); document.body.removeChild(a);
                                document.body.removeChild(downloadContainer);
                                unlockBodyScroll(); // Restore scroll
                                return;
                            }
                            quality -= 0.05;
                        } while (quality > 0.1);
                        alert("Couldn't compress JPG under 3.99MB!");
                    });

                    downloadContainer.appendChild(pngBtn);
                    downloadContainer.appendChild(jpgBtn);
                    document.body.appendChild(downloadContainer);
                    resolve();
                });
            });
        });

        Promise.all(collagePromises).then(() => {
            const existing = document.querySelector('.overlay');
            if (existing) existing.parentNode.removeChild(existing);
        });
    }

    // =========================
    // 8b. Video Collage Creation
    // =========================
    async function createVideoCollage(itemsForCollage, isCustomCollage = false) {
        let duration = parseInt(prompt("Enter collage duration in seconds (1-10):", "5"), 10);
        if (isNaN(duration) || duration < 1 || duration > 10) {
            alert("Invalid duration. Please enter a number between 1 and 10.");
            return;
        }
        const targetMP = parseFloat(prompt("Enter target megapixels per element (e.g., 0.3):", "0.3"));
        const targetAspect = parseFloat(prompt("Enter target collage aspect ratio (e.g., 1 for square):", "1"));
        if (!targetMP || !targetAspect) {
            alert("Invalid input.");
            return;
        }

        showProcessingOverlay("Preparing media...");
        setProcessingWarning("⚠ Rendering happens live in this tab. If you switch away at ANY point, it will pause and automatically resume when you come back — it just takes longer.");
        const targetArea = targetMP * 1e6;

        // Fetch every source at most ONCE. External files can be huge; the old
        // code downloaded each file twice (dimension pass + load pass).
        const blobCache = new Map();
        const getBlob = (src) => {
            const key = (src instanceof File) ? src : String(src);
            if (!blobCache.has(key)) blobCache.set(key, fetchImageAsBlob(src));
            return blobCache.get(key);
        };

        let L = [];
        const dropped = [];
        const shortName = (src) => (src instanceof File) ? src.name : String(src).split('/').pop();
        const mediaPromises = itemsForCollage.map(item => getMediaDimensions(item.fullSrc, getBlob).then(dims => {
            L.push({ src: item.fullSrc, width: dims.width, height: dims.height, type: dims.type });
        }).catch(err => {
            // e.g. expired litter.catbox.moe / uguu.se links 404 — drop them
            // from the collage instead of aborting.
            dropped.push(shortName(item.fullSrc));
            console.warn("Skipping unavailable media:", item.fullSrc, err);
        }));
        await Promise.all(mediaPromises);

        if (dropped.length > 0) {
            showToast(`Skipped ${dropped.length} unavailable file(s) (expired link?): ${dropped.join(', ')}`, 6000);
        }

        if (L.length === 0) {
            alert("None of the selected media could be loaded.\nCatbox/litter/uguu links may have expired, or the script wasn't allowed to access those hosts when Tampermonkey asked.");
            hideProcessingOverlay();
            return;
        }

        const collages = roundRobinCollageLayout(L, 1, targetArea, selectedHeaderImage, targetAspect);
        if (!collages || collages.length === 0) {
            alert("Collage layout failed.");
            hideProcessingOverlay();
            return;
        }
        const layout = collages[0];

        let canvas = document.createElement('canvas');
        let scale = 1.0;
        if (layout.width > 2048 || layout.height > 2048) {
            scale = Math.min(2048 / layout.width, 2048 / layout.height);
        }
        canvas.width = Math.round(layout.width * scale);
        canvas.height = Math.round(layout.height * scale);
        const ctx = canvas.getContext('2d');
        ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height);

        updateProcessingOverlay("Loading videos and images...");
        const mediaElements = {};

        const getUniqueKey = (src) => {
            return (src instanceof File) ? `${src.name}_${src.size}_${src.lastModified}` : src;
        };

        const loadPromises = layout.placements.map(p => {
            return new Promise(async (resolve, reject) => {
                const itemSrc = p.image.src;
                const uniqueKey = getUniqueKey(itemSrc);

                if (uniqueKey in mediaElements) return resolve();
                mediaElements[uniqueKey] = null; // reserve to avoid double-loading

                let blob;
                try { blob = await getBlob(itemSrc); }
                catch (err) { return reject(new Error("Download failed: " + (itemSrc.name || itemSrc))); }
                const blobUrl = URL.createObjectURL(blob);

                if (p.image.type === 'video') {
                    const video = document.createElement('video');
                    video.muted = true; video.loop = true; video.playsInline = true;
                    video.volume = 0; // belt-and-suspenders: no audio anywhere
                    // The blob is fully local, so 'loadeddata' (first frame
                    // decodable) is enough and more reliable than canplaythrough.
                    video.onloadeddata = () => { mediaElements[uniqueKey] = video; resolve(); };
                    video.onerror = () => reject(new Error("Could not decode video: " + (itemSrc.name || itemSrc)));
                    video.src = blobUrl;
                } else {
                    const img = new Image();
                    img.onload = () => { mediaElements[uniqueKey] = img; resolve(); };
                    img.onerror = () => reject(new Error("Could not decode image: " + (itemSrc.name || itemSrc)));
                    img.src = blobUrl;
                }
            });
        });
        try {
            await Promise.all(loadPromises);
        } catch (err) {
            alert("Video collage aborted.\n" + err.message);
            hideProcessingOverlay();
            return;
        }

        const selectedFormat = { mimeType: 'video/webm; codecs=vp8', extension: 'webm' };
        if (!MediaRecorder.isTypeSupported(selectedFormat.mimeType)) {
            console.warn(`'video/webm; codecs=vp8' is not supported. Trying 'video/webm'.`);
            selectedFormat.mimeType = 'video/webm';
            if (!MediaRecorder.isTypeSupported(selectedFormat.mimeType)) {
                alert("Your browser does not support the required video format (WebM).");
                hideProcessingOverlay();
                return;
            }
        }
        console.log(`Using supported video format: ${selectedFormat.mimeType}`);

        const targetBitrate = (3.8 * 1024 * 1024 * 8) / duration;
        const stream = canvas.captureStream(30); // capture at 30fps
        // canvas.captureStream() is video-only, but explicitly strip any audio
        // tracks to guarantee the output file contains no audio.
        stream.getAudioTracks().forEach(t => { t.stop(); stream.removeTrack(t); });
        const recorder = new MediaRecorder(stream, { mimeType: selectedFormat.mimeType, videoBitsPerSecond: targetBitrate });

        const chunks = [];
        // Recording time accounting that survives pause/resume: we only count
        // time while the recorder is actually in the 'recording' state.
        let segStart = 0;
        let accumulatedMs = 0;
        recorder.onstart = () => { segStart = performance.now(); };
        recorder.onpause = () => { accumulatedMs += performance.now() - segStart; };
        recorder.onresume = () => { segStart = performance.now(); };
        const activeMs = () => accumulatedMs + (recorder.state === 'recording' ? performance.now() - segStart : 0);

        recorder.ondataavailable = e => { if (e.data && e.data.size > 0) chunks.push(e.data); };
        recorder.onstop = async () => {
            const actualDurationMs = Math.max(1, Math.round(accumulatedMs));
            let blob = new Blob(chunks, { type: selectedFormat.mimeType });
            // Chrome/Firefox MediaRecorder writes WebM files WITHOUT duration
            // metadata, so players report 0:00 / a bogus length and can't
            // seek. Patch the real duration into the EBML header.
            try {
                if (typeof ysFixWebmDuration === 'function') {
                    blob = await ysFixWebmDuration(blob, actualDurationMs);
                }
            } catch (e) { console.warn("webm duration patch failed:", e); }

            const videoURL = URL.createObjectURL(blob);
            Object.values(mediaElements).forEach(el => {
                if (el && el.src && el.src.startsWith('blob:')) URL.revokeObjectURL(el.src);
            });
            const currentUnixTime = Math.floor(Date.now()/1000);
            let filename;

            if (isCustomCollage) {
                filename = `collage_${currentUnixTime}.${selectedFormat.extension}`;
            } else {
                const url = window.location.href;
                const boardMatch = url.match(/boards\.4chan(?:nel)?\.org\/([^\/]+)\//);
                const board = boardMatch ? boardMatch[1] : "unknown";
                const threadMatch = url.match(/thread\/(\d+)/);
                const thread = threadMatch ? threadMatch[1] : "unknown";
                filename = `highlights_${board}_${thread}_${currentUnixTime}.${selectedFormat.extension}`;
            }

            const a = document.createElement('a'); a.href = videoURL; a.download = filename;
            document.body.appendChild(a); a.click(); document.body.removeChild(a);

            hideProcessingOverlay();
            const existingOverlay = document.querySelector('.overlay');
            if (existingOverlay) existingOverlay.parentNode.removeChild(existingOverlay);
            unlockBodyScroll();
        };

        let animationFrameId = null;
        let drawIntervalId = null;
        let drawErrorLogged = false;
        function draw() {
            try {
                ctx.fillStyle = "#fff";
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                layout.placements.forEach(p => {
                    const uniqueKey = getUniqueKey(p.image.src);
                    const mediaEl = mediaElements[uniqueKey];
                    if (!mediaEl) return;
                    // Skip videos that have no decodable frame yet.
                    if (mediaEl.tagName === 'VIDEO' && mediaEl.readyState < 2) return;
                    const x = p.x * scale, y = p.y * scale, w = p.width * scale, h = p.height * scale;
                    ctx.drawImage(mediaEl, x, y, w, h);
                });
            } catch (e) {
                // Never let one bad frame kill the whole render loop.
                if (!drawErrorLogged) { drawErrorLogged = true; console.error("draw error:", e); }
            }
        }
        function rafLoop() {
            draw();
            animationFrameId = requestAnimationFrame(rafLoop);
        }
        function stopDrawing() {
            if (animationFrameId !== null) cancelAnimationFrame(animationFrameId);
            if (drawIntervalId !== null) clearInterval(drawIntervalId);
        }

        // Start all videos and wait until they are ACTUALLY producing frames
        // before recording — this is what prevents white/blank output.
        updateProcessingOverlay("Starting playback...");
        const videos = Object.values(mediaElements).filter(el => el && el.tagName === 'VIDEO');
        await Promise.all(videos.map(v => new Promise(resolve => {
            const timeout = setTimeout(resolve, 3000); // never hang forever
            v.addEventListener('playing', () => { clearTimeout(timeout); resolve(); }, { once: true });
            v.play().catch(e => { console.error("play() failed:", e); clearTimeout(timeout); resolve(); });
        })));

        // If the tab was hidden while media was downloading/decoding, do NOT
        // start recording into a throttled void — wait here until it's
        // visible again.
        if (document.hidden) {
            updateProcessingOverlay("Waiting for you — rendering starts when this tab is visible again.");
            await new Promise(resolve => {
                const onVis = () => {
                    if (!document.hidden) {
                        document.removeEventListener('visibilitychange', onVis);
                        resolve();
                    }
                };
                document.addEventListener('visibilitychange', onVis);
            });
        }

        const renderMsg = `Rendering video (${duration}s)...`;
        updateProcessingOverlay(renderMsg);

        // Drive drawing with BOTH requestAnimationFrame (smooth while the tab
        // is focused) and a setInterval fallback: rAF is throttled to ZERO in
        // background tabs. Redundant draws are harmless.
        rafLoop();
        drawIntervalId = setInterval(draw, 1000 / 30);

        // While recording, hiding the tab pauses the recorder and the source
        // videos (instead of silently recording throttled garbage); returning
        // to the tab resumes them. The stop condition below counts only
        // actively-recorded time, so pausing simply extends wall-clock time.
        const visHandler = () => {
            if (document.hidden && recorder.state === 'recording') {
                recorder.pause();
                videos.forEach(v => v.pause());
                updateProcessingOverlay("Paused — come back to this tab to finish rendering.");
            } else if (!document.hidden && recorder.state === 'paused') {
                videos.forEach(v => v.play().catch(() => {}));
                recorder.resume();
                updateProcessingOverlay(renderMsg);
            }
        };
        document.addEventListener('visibilitychange', visHandler);

        function finishRecording() {
            document.removeEventListener('visibilitychange', visHandler);
            // Fold in the final active segment before stopping, so the
            // duration patch is accurate (onpause won't fire for stop()).
            if (recorder.state === 'recording') {
                accumulatedMs += performance.now() - segStart;
            }
            recorder.stop(); // valid from both 'recording' and 'paused'
            stopDrawing();
            videos.forEach(v => v.pause());
            updateProcessingOverlay("Finalizing video file...");
        }

        // Small settle delay so the first recorded frame already has content,
        // then record with a timeslice so data is flushed periodically.
        // Stop is based on ACTIVELY RECORDED time, not wall-clock time, so
        // pauses while the tab is hidden don't cut the video short.
        setTimeout(() => {
            recorder.start(250);
            visHandler(); // apply current visibility state (tab may have been re-hidden during the settle delay)
            const stopChecker = setInterval(() => {
                if (activeMs() >= duration * 1000) {
                    clearInterval(stopChecker);
                    finishRecording();
                }
            }, 100);
        }, 150);
    }

    // =========================
    // 8c. Video Creation UI Helpers
    // =========================
    function showProcessingOverlay(message) {
        let overlay = document.getElementById('processing-overlay');
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.id = 'processing-overlay';
            Object.assign(overlay.style, {
                position: 'fixed', top: '0', left: '0', width: '100vw', height: '100vh',
                backgroundColor: 'rgba(0, 0, 0, 0.75)', color: 'white', display: 'flex',
                alignItems: 'center', justifyContent: 'center', zIndex: '9999',
                fontSize: '24px', flexDirection: 'column'
            });
            overlay.innerHTML = `<div class="spinner"></div><span id="processing-message"></span><span id="processing-warning" style="margin-top:12px;font-size:15px;color:#ffd24d;max-width:80vw;text-align:center;"></span>`;
            document.body.appendChild(overlay);
        }
        overlay.style.display = 'flex';
        document.getElementById('processing-message').textContent = message;
        setProcessingWarning(''); // cleared until a phase sets it
    }
    function updateProcessingOverlay(message) {
        const msgElement = document.getElementById('processing-message');
        if (msgElement) msgElement.textContent = message;
    }
    function setProcessingWarning(message) {
        const warnElement = document.getElementById('processing-warning');
        if (warnElement) warnElement.textContent = message;
    }
    function hideProcessingOverlay() {
        const overlay = document.getElementById('processing-overlay');
        if (overlay) overlay.style.display = 'none';
    }

    function showToast(message, ms = 5000) {
        const toast = document.createElement('div');
        toast.className = 'chan-hv-toast';
        toast.textContent = message;
        document.body.appendChild(toast);
        setTimeout(() => toast.remove(), ms);
    }


    // =========================
    // 9. Round-Robin Collage Layout
    // =========================
    function roundRobinCollageLayout(L, numCollages, targetArea, headerImage, targetAspect) {
        L.forEach(img => {
            let s = Math.sqrt(targetArea / (img.width * img.height));
            img.scaledWidth = img.width * s;
            img.scaledHeight = img.height * s;
        });
        L.sort((a, b) => (a.width / a.height) - (b.width / b.height));
        let groups = [];
        for (let i = 0; i < numCollages; i++) { groups.push([]); }
        for (let i = 0; i < L.length; i++) { groups[i % numCollages].push(L[i]); }
        let collages = [];
        groups.forEach((group, groupIndex) => {
            if (group.length === 0) return;
            let m = group.length;
            let numColumns = Math.ceil(Math.sqrt(m) * targetAspect);
            let rows = [];
            for (let i = 0; i < m; i += numColumns) { rows.push(group.slice(i, i + numColumns)); }
            let allBoxes = rows.flat();
            let sortedByWidth = [...allBoxes].sort((a, b) => b.scaledWidth - a.scaledWidth);
            for (let r = 0; r < rows.length - 1; r++) {
                let desired = sortedByWidth[r];
                if (rows[r][0] !== desired) {
                    for (let r2 = r; r2 < rows.length; r2++) {
                        let idx = rows[r2].indexOf(desired);
                        if (idx !== -1) { [rows[r][0], rows[r2][idx]] = [rows[r2][idx], rows[r][0]]; break; }
                    }
                }
            }
            if (rows.length > 1) {
                const rowMetrics = rows.map(row => {
                    const baseHeight = row[0].scaledHeight;
                    let totalWidth = 0;
                    for (const img of row) { totalWidth += img.scaledWidth * (baseHeight / img.scaledHeight); }
                    return { baseHeight, totalWidth };
                });
                const maxRowWidth = Math.max(...rowMetrics.map(m => m.totalWidth));
                const finalHeights = rowMetrics.map(m => m.baseHeight * (maxRowWidth / m.totalWidth));
                const bottomFinalHeight = finalHeights[finalHeights.length - 1];
                let minFinalHeight = Infinity;
                for (let i = 0; i < finalHeights.length - 1; i++) {
                    if (finalHeights[i] < minFinalHeight) minFinalHeight = finalHeights[i];
                }
                if (bottomFinalHeight > 1.8 * minFinalHeight) {
                    const bottomRow = rows[rows.length - 1];
                    if (bottomRow.length === 1) {
                        let tallestRowIndex = -1, maxFinalHeight = -Infinity;
                        for (let i = 0; i < finalHeights.length - 1; i++) {
                            if (finalHeights[i] > maxFinalHeight) { maxFinalHeight = finalHeights[i]; tallestRowIndex = i; }
                        }
                        if (tallestRowIndex !== -1) {
                            rows[tallestRowIndex].push(bottomRow.pop());
                            if (bottomRow.length === 0) rows.pop();
                        }
                    } else {
                        let donorRowIndex = -1, minRowFinalHeight = Infinity;
                        for (let i = 0; i < finalHeights.length - 1; i++) {
                            if (finalHeights[i] < minRowFinalHeight) { minRowFinalHeight = finalHeights[i]; donorRowIndex = i; }
                        }
                        if (donorRowIndex !== -1 && rows[donorRowIndex].length > 0) {
                            const donorRow = rows[donorRowIndex];
                            let widestImageIndex = donorRow.reduce((maxIdx, img, i, arr) => (img.scaledWidth > arr[maxIdx].scaledWidth) ? i : maxIdx, 0);
                            bottomRow.push(donorRow.splice(widestImageIndex, 1)[0]);
                        }
                    }
                }
            }
            rows = rows.map(row => row.sort(() => Math.random() - 0.5));
            if (headerImage) {
                let narrowestRowIndex = 0, minRowWidth = Infinity;
                rows.forEach((row, idx) => {
                    let width = row.reduce((sum, img) => sum + img.scaledWidth, 0);
                    if (width < minRowWidth) { minRowWidth = width; narrowestRowIndex = idx; }
                });
                const baseHeight = rows[narrowestRowIndex][0].scaledHeight;
                const factor = baseHeight / headerImage.height;
                const headerScaled = { src: headerImage.src, width: headerImage.width, height: headerImage.height, scaledWidth: headerImage.width * factor, scaledHeight: baseHeight, type: 'image' };
                rows[narrowestRowIndex].unshift(headerScaled);
            }
            let rowLayouts = rows.map(row => {
                let baseHeight = row[0].scaledHeight;
                let cells = row.map(img => ({ image: img, width: img.scaledWidth * (baseHeight / img.scaledHeight), height: baseHeight }));
                let totalWidth = cells.reduce((sum, cell) => sum + cell.width, 0);
                return { cells, width: totalWidth, height: baseHeight };
            });
            let maxRowWidth = Math.max(...rowLayouts.map(r => r.width));
            rowLayouts = rowLayouts.map(r => {
                if (r.width < maxRowWidth) {
                    let factor = maxRowWidth / r.width;
                    return { cells: r.cells.map(cell => ({ image: cell.image, width: cell.width * factor, height: cell.height * factor })), width: r.width * factor, height: r.height * factor };
                } else {
                    return r;
                }
            });
            let placements = []; let y = 0;
            rowLayouts.forEach(r => {
                let x = 0;
                r.cells.forEach(cell => {
                    placements.push({ image: cell.image, x: x, y: y, width: cell.width, height: cell.height });
                    x += cell.width;
                });
                y += r.height;
            });
            collages.push({ width: maxRowWidth, height: y, placements });
        });
        return collages;
    }

    // =========================
    // 10. Utility: Fetch media as blob (Handles URLs and Files)
    // =========================
    function fetchImageAsBlob(source) {
        if (source instanceof File) {
            return Promise.resolve(source);
        }
        if (String(source).startsWith('data:')) {
            return fetch(source).then(res => res.blob());
        }
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: "GET", url: source, responseType: "blob",
                onload: res => (res.status === 200) ? resolve(res.response) : reject(new Error("Fetch failed: " + res.status)),
                onerror: err => reject(err)
            });
        });
    }

    function dataURLToBlob(dataURL) {
        const binary = atob(dataURL.split(',')[1]);
        const array = [];
        for (let i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); }
        return new Blob([new Uint8Array(array)], { type: 'image/jpeg' });
    }

    // =========================
    // 11. Utility: Get media dimensions (Handles URLs and Files)
    // =========================
    function getMediaDimensions(source, fetchBlob = fetchImageAsBlob) {
        return new Promise((resolve, reject) => {
            const isVideo = isVideoSource(source);

            fetchBlob(source).then(blob => {
                const blobUrl = URL.createObjectURL(blob);
                if (isVideo) {
                    const video = document.createElement('video');
                    video.muted = true;
                    video.onloadedmetadata = () => { resolve({ width: video.videoWidth, height: video.videoHeight, type: 'video' }); URL.revokeObjectURL(blobUrl); };
                    video.onerror = () => { reject(new Error("Failed to load video " + (source.name || source))); URL.revokeObjectURL(blobUrl); };
                    video.src = blobUrl;
                } else {
                    const img = new Image();
                    img.onload = () => { resolve({ width: img.naturalWidth, height: img.naturalHeight, type: 'image' }); URL.revokeObjectURL(blobUrl); };
                    img.onerror = () => { reject(new Error("Failed to load image " + (source.name || source))); URL.revokeObjectURL(blobUrl); };
                    img.src = blobUrl;
                }
            }).catch(reject);
        });
    }

    // =========================
    // 12. Options Menu
    // =========================
    function addOptionsMenu() {
        const menu = document.createElement('div');
        menu.className = 'chan-hv-options-menu';
        const header = document.createElement('div');
        header.className = 'chan-hv-menu-header';
        header.textContent = '► Collage';
        header.addEventListener('click', () => {
            const content = menu.querySelector('.chan-hv-menu-content');
            if (content.style.display === 'block') {
                content.style.display = 'none'; header.textContent = '► Collage';
            } else {
                content.style.display = 'block'; header.textContent = '▼ Collage';
            }
        });
        menu.appendChild(header);
        const content = document.createElement('div');
        content.className = 'chan-hv-menu-content';
        content.style.display = 'none';

        const reviewBtn = document.createElement('button');
        reviewBtn.textContent = 'Review Highlights';
        reviewBtn.addEventListener('click', showReviewHighlightsView);

        const threadBtn = document.createElement('button');
        threadBtn.textContent = 'View Thread Thumbnails';
        threadBtn.addEventListener('click', showThreadThumbnailsView);

        const customCollageBtn = document.createElement('button');
        customCollageBtn.textContent = 'Custom Collage';
        customCollageBtn.addEventListener('click', showCustomCollageView);

        const clearBtn = document.createElement('button');
        clearBtn.textContent = 'Clear All Selections';
        clearBtn.addEventListener('click', () => {
            if (!confirm("Are you sure you want to clear all highlighted posts?")) return;
            document.querySelectorAll('.post.highlighted').forEach(post => {
                post.classList.remove('highlighted');
                const btn = post.querySelector('.highlight-btn');
                if (btn) btn.style.background = 'rgba(255,255,0,0.7)';
            });
            highlightedImages = [];
            saveHighlights();
            // Reset any inline external star buttons back to yellow
            refreshExternalBtns();
        });

        content.appendChild(reviewBtn);
        content.appendChild(threadBtn);
        content.appendChild(customCollageBtn);
        content.appendChild(clearBtn);
        menu.appendChild(content);
        document.body.appendChild(menu);
    }

    // =========================
    // 13. Initialization
    // =========================
    function init() {
        loadHighlights();
        addHighlightButtons();
        addExternalButtons();
        addOptionsMenu();

        const observer = new MutationObserver(mutations => {
            for (const mutation of mutations) {
                if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                    addHighlightButtons();
                    addExternalButtons();
                }
            }
        });

        observer.observe(document.body, { childList: true, subtree: true });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
Edit

Pub: 03 Aug 2026 12:10 UTC

Edit: 06 Aug 2026 13:30 UTC

Views: 154