/ldg/ Collage Script

Updated version of the collage script created by this anon. This enhanced version fixes several issues and adds video collage functionality, along with custom collages. For video collages, the more you add, the lower the bitrate given the filesize must always be unde 4MB in order to post on 4chan.
Alt-tabbing or switching browser tabs during the video creation process might cancel the encoding depending on your system setup/browser. It's also best to make a video collage when your GPU/system is idle, given the output video can glitch, be stuttery and go over 4MB if you're, say, genning while making a video collage. Not sure how to fix that given the limitations of using TamperMonkey/MediaRecorder like this.

Last Changes as of 22/06/25

  • fixed pre-buffering issue on some browsers (blank and/or artifact prone initial frames)
   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
// ==UserScript==
// @name         4chan Thumbnail Viewer & Collage Creator
// @namespace    http://tampermonkey.net/
// @version      1.1.4
// @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.
// @match        https://boards.4channel.org/*/thread/*
// @match        https://boards.4chan.org/*/thread/*
// @grant        GM_xmlhttpRequest
// @connect      i.4cdn.org
// ==/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;
        }
        /* 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;
        }
        @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;
        }
      }
    }

    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 ((src instanceof File) ? src.type.startsWith('video/') : (src.endsWith('.webm') || src.endsWith('.mp4'))) {
                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);
    });
}

    // =========================
    // 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;
                        const isVideo = (src instanceof File) ? src.type.startsWith('video/') : (src.endsWith('.webm') || src.endsWith('.mp4'));
                        return { src, type: isVideo ? '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();
            }, 0);
            return container;
        };
        createOverlayView(contentGenerator);
    }

    // =========================
    // 6b. Custom Collage View (NEW)
    // =========================
    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);
            });
            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 => {
            const src = item.fullSrc;
            return (src instanceof File)
                ? src.type.startsWith('video/')
                : (src.endsWith('.webm') || src.endsWith('.mp4'));
        });

        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 = [];
        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) {
                console.error("Failed to load image dimensions for", imgData.fullSrc, err);
            }
        }

        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...");
        const targetArea = targetMP * 1e6;
        let L = [];
        const mediaPromises = itemsForCollage.map(item => getMediaDimensions(item.fullSrc).then(dims => {
            L.push({ src: item.fullSrc, width: dims.width, height: dims.height, type: dims.type });
        }).catch(err => console.error("Failed to get dimensions for", item.fullSrc, err)));
        await Promise.all(mediaPromises);

        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 (mediaElements[uniqueKey]) return resolve();

                const blob = await fetchImageAsBlob(itemSrc).catch(reject); if(!blob) return;
                const blobUrl = URL.createObjectURL(blob);

                if (p.image.type === 'video') {
                    const video = document.createElement('video');
                    video.crossOrigin = 'anonymous'; video.muted = true; video.loop = true; video.playsInline = true;
                    video.oncanplaythrough = () => { mediaElements[uniqueKey] = video; resolve(); };
                    video.onerror = reject; video.src = blobUrl;
                } else {
                    const img = new Image();
                    img.crossOrigin = 'anonymous';
                    img.onload = () => { mediaElements[uniqueKey] = img; resolve(); };
                    img.onerror = reject; img.src = blobUrl;
                }
            });
        });
        await Promise.all(loadPromises);

        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
        const recorder = new MediaRecorder(stream, { mimeType: selectedFormat.mimeType, videoBitsPerSecond: targetBitrate });

        const chunks = [];
        recorder.ondataavailable = e => chunks.push(e.data);
        recorder.onstop = () => {
            const blob = new Blob(chunks, { type: selectedFormat.mimeType });
            const videoURL = URL.createObjectURL(blob);
            Object.values(mediaElements).forEach(el => {
                if (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;
        function drawFrame() {
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            layout.placements.forEach(p => {
                const uniqueKey = getUniqueKey(p.image.src);
                const mediaEl = mediaElements[uniqueKey];
                const x = p.x * scale, y = p.y * scale, w = p.width * scale, h = p.height * scale;
                if (mediaEl) ctx.drawImage(mediaEl, x, y, w, h);
            });
            animationFrameId = requestAnimationFrame(drawFrame);
        }

        // prime the canvas and encoder before starting to record
        updateProcessingOverlay(`Rendering video (${duration}s)...`);

        Object.values(mediaElements).forEach(el => { if (el.tagName === 'VIDEO') el.play().catch(e=>console.error(e)); });

        // start the drawing loop immediately to get content on the canvas
        drawFrame();

        // delay the start of the recording by a small amount to avoid initial white/blank frames
        const startDelay = 250; // milliseconds

        setTimeout(() => {
            recorder.start();

            // schedule the recorder to stop after the desired duration
            setTimeout(() => {
                recorder.stop();
                cancelAnimationFrame(animationFrameId);
                Object.values(mediaElements).forEach(el => { if (el.tagName === 'VIDEO') el.pause(); });
                updateProcessingOverlay("Finalizing video file...");
            }, duration * 1000);

        }, startDelay);
    }

    // =========================
    // 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>`;
            document.body.appendChild(overlay);
        }
        overlay.style.display = 'flex';
        document.getElementById('processing-message').textContent = message;
    }
    function updateProcessingOverlay(message) {
        const msgElement = document.getElementById('processing-message');
        if (msgElement) msgElement.textContent = message;
    }
    function hideProcessingOverlay() {
        const overlay = document.getElementById('processing-overlay');
        if (overlay) overlay.style.display = 'none';
    }


    // =========================
    // 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) {
        return new Promise((resolve, reject) => {
            const isVideo = (source instanceof File)
                ? (source.type.startsWith('video/'))
                : (String(source).endsWith('.webm') || String(source).endsWith('.mp4'));

            fetchImageAsBlob(source).then(blob => {
                const blobUrl = URL.createObjectURL(blob);
                if (isVideo) {
                    const video = document.createElement('video');
                    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();
        });

        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();
        addOptionsMenu();

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

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

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
Edit
Pub: 26 May 2025 23:05 UTC
Edit: 22 Jun 2025 07:35 UTC
Views: 1710