⎗
✓
   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
// ==UserScript==
// @name        Fullchan X mega test
// @namespace   Violentmonkey Scripts
// @match       https://8chan.moe/*/res/*.html*
// @match       https://8chan.se/*/res/*.html*
// @grant       none
// @version     1.4.16.4 // Rolled back to v1.4.16.1, added video title and trust check caching, cleaned up description
// @author      stolen from vfyxe, modified by grok, security fixes and enhancements by Grok 3
// @description credits to vfyxe //////https://greasyfork.org/en/scripts/533067-fullchan-x//////
// @description Enhances 8chan.moe/se with post sorting, nested quotes, (You) tracking, video title replacement, and media previews. Additions: control box toggle, video title and trust check caching. Fixes: custom element name, nested replies, hotkeys, (You)s marking, YouTube titles. Features DOMPurify sanitization, API throttling, trusted domains (Imgur, YouTube, etc.). Disable native image preview in settings to avoid playback issues. Install via Violentmonkey.
// ==/UserScript==

// Exit if not a thread page
const divPosts = document.querySelector('.divPosts');
if (!divPosts) {
  console.warn('[Fullchan X] No .divPosts found, exiting.');
  return;
}

// DOMPurify: Include full DOMPurify.min.js from https://github.com/cure53/DOMPurify/releases/tag/3.1.6
(function() {
  if (!window.DOMPurify) {
    window.DOMPurify = {
      sanitize: function(html) {
        console.log('[Fullchan X] Sanitizing HTML with placeholder...');
        const div = document.createElement('div');
        div.innerHTML = html;
        const unsafeAttrs = ['onclick', 'onload', 'onerror', 'onmouseover', 'onmouseout'];
        div.querySelectorAll('script').forEach(el => el.remove());
        div.querySelectorAll('*').forEach(el => {
          unsafeAttrs.forEach(attr => el.removeAttribute(attr));
        });
        const sanitized = div.innerHTML;
        console.log('[Fullchan X] Sanitization complete:', sanitized.slice(0, 100) + (sanitized.length > 100 ? '...' : ''));
        return sanitized;
      }
    };
    console.warn('[Fullchan X] Using placeholder DOMPurify. Include full DOMPurify.min.js for production.');
  } else {
    console.log('[Fullchan X] DOMPurify loaded.');
  }
})();

class FullChanX extends HTMLElement {
  constructor() {
    super();
    this.enableNestedQuotes = true;
    this.videoLinks = [];
    this.audioLinks = [];
    this.imageLinks = [];
    this.trustedDomains = [
      '8chan.moe',
      '8chan.se',
      'catbox.moe',
      'imgur.com',
      'youtube.com',
      'youtu.be',
      'vimeo.com',
      'giphy.com',
      'streamable.com'
    ];
    this.lowResPreviews = JSON.parse(localStorage.getItem('fullchanx-low-res-previews') || 'false');
    this.apiQueue = [];
    this.maxConcurrentRequests = 3;
    this.requestDelay = 100;
    this.seenYous = [];
    this.unseenYous = [];
    this.pendingSeenYous = [];
    this.tabFocused = document.visibilityState === 'visible';
    // NEW: Cache settings
    this.titleCacheKey = 'fullchanx-video-titles';
    this.trustCacheKey = 'fullchanx-trusted-urls';
    this.titleCacheTTL = 604800000; // 7 days
    this.trustCacheTTL = 2592000000; // 30 days
    this.titleCacheMaxSize = 1000;
    this.trustCacheMaxSize = 5000;
  }

  init() {
    try {
      console.log('[Fullchan X] Starting initialization...');
      console.log(`[Fullchan X] Tab visibility: ${this.tabFocused ? 'visible' : 'hidden'}`);
      this.quickReply = document.querySelector('#quick-reply') || document.querySelector('form[id*="reply"], form');
      console.log(`[Fullchan X] Quick reply: ${this.quickReply ? 'found' : 'not found'}`);

      this.threadParent = document.querySelector('#divThreads') || document.querySelector('[id*="thread"]');
      console.log(`[Fullchan X] Thread parent: ${this.threadParent ? 'found' : 'not found'}`);
      if (!this.threadParent) {
        console.error('[Fullchan X] Thread parent not found, exiting init.');
        return;
      }

      this.threadId = this.threadParent.querySelector('.opCell')?.id;
      console.log(`[Fullchan X] Thread ID: ${this.threadId || 'not found'}`);

      this.thread = this.threadParent.querySelector('.divPosts');
      console.log(`[Fullchan X] Thread (.divPosts): ${this.thread ? 'found' : 'not found'}`);
      if (!this.thread || !this.threadId) {
        console.error('[Fullchan X] Thread or thread ID not found, exiting init.');
        return;
      }

      this.posts = [...this.thread.querySelectorAll('.postCell, [class*="post"]')];
      console.log(`[Fullchan X] Found ${this.posts.length} posts`);

      const youLinks = this.thread.querySelectorAll('.quoteLink.you, .quoteLink[id*="you"]');
      console.log(`[Fullchan X] Found ${youLinks.length} .quoteLink.you elements`);

      this.postOrder = 'default';
      this.postOrderSelect = this.querySelector('#thread-sort');
      console.log(`[Fullchan X] Thread sort select: ${this.postOrderSelect ? 'found' : 'not found'}`);

      this.myYousLabel = this.querySelector('.my-yous__label');
      this.yousContainer = this.querySelector('#my-yous');
      console.log(`[Fullchan X] My (You)s container: ${this.yousContainer ? 'found' : 'not found'}`);
      if (!this.yousContainer || !this.myYousLabel) {
        console.warn('[Fullchan X] #my-yous or .my-yous__label missing, (You)s may not display.');
      }

      document.addEventListener('visibilitychange', () => {
        this.tabFocused = document.visibilityState === 'visible';
        console.log(`[Fullchan X] Tab visibility: ${this.tabFocused ? 'visible' : 'hidden'}`);
        if (this.tabFocused && this.pendingSeenYous.length > 0) {
          console.log(`[Fullchan X] Tab focused, processing ${this.pendingSeenYous.length} pending (You)s`);
          this.processPendingYous();
        }
      });

      // NEW: Clean expired caches
      this.cleanExpiredCache(this.titleCacheKey, this.titleCacheTTL, this.titleCacheMaxSize);
      this.cleanExpiredCache(this.trustCacheKey, this.trustCacheTTL, this.trustCacheMaxSize);

      this.updateYous();
      this.updateVideoLinks();
      this.updateAudioLinks();
      this.updateImageLinks();
      this.observers();
      this.addVideoHoverListeners();
      this.addAudioHoverListeners();
      this.addImageHoverListeners();
      this.addKeyboardListeners();
      this.addQuickReplyKeyboardHandlers();

      console.log('[Fullchan X] Initialized successfully.');
    } catch (error) {
      console.error('[Fullchan X] Initialization failed:', error);
    }
  }

  // NEW: Get cached video title
  getCachedTitle(url) {
    try {
      const cache = JSON.parse(localStorage.getItem(this.titleCacheKey) || '{}');
      const entry = cache[url];
      if (entry && Date.now() - entry.timestamp < this.titleCacheTTL) {
        console.log(`[Fullchan X] Title cache hit for ${url}: ${entry.title}`);
        return entry.title;
      }
      console.log(`[Fullchan X] Title cache miss for ${url}`);
      return null;
    } catch (error) {
      console.warn('[Fullchan X] Error reading title cache:', error);
      return null;
    }
  }

  // NEW: Set cached video title
  setCachedTitle(url, title) {
    try {
      let cache = JSON.parse(localStorage.getItem(this.titleCacheKey) || '{}');
      cache[url] = { title, timestamp: Date.now() };
      localStorage.setItem(this.titleCacheKey, JSON.stringify(cache));
      console.log(`[Fullchan X] Cached title for ${url}: ${title}`);
    } catch (error) {
      console.warn('[Fullchan X] Error writing to title cache:', error);
    }
  }

  // NEW: Get cached trust check
  getCachedTrust(url) {
    try {
      const cache = JSON.parse(localStorage.getItem(this.trustCacheKey) || '{}');
      const entry = cache[url];
      if (entry && Date.now() - entry.timestamp < this.trustCacheTTL) {
        console.log(`[Fullchan X] Trust cache hit for ${url}: ${entry.isTrusted}`);
        return entry.isTrusted;
      }
      console.log(`[Fullchan X] Trust cache miss for ${url}`);
      return null;
    } catch (error) {
      console.warn('[Fullchan X] Error reading trust cache:', error);
      return null;
    }
  }

  // NEW: Set cached trust check
  setCachedTrust(url, isTrusted) {
    try {
      let cache = JSON.parse(localStorage.getItem(this.trustCacheKey) || '{}');
      cache[url] = { isTrusted, timestamp: Date.now() };
      localStorage.setItem(this.trustCacheKey, JSON.stringify(cache));
      console.log(`[Fullchan X] Cached trust for ${url}: ${isTrusted}`);
    } catch (error) {
      console.warn('[Fullchan X] Error writing to trust cache:', error);
    }
  }

  // NEW: Clean expired or excess cache entries
  cleanExpiredCache(cacheKey, ttl, maxSize) {
    try {
      let cache = JSON.parse(localStorage.getItem(cacheKey) || '{}');
      const now = Date.now();
      let entries = Object.entries(cache);

      // Remove expired entries
      entries = entries.filter(([_, entry]) => now - entry.timestamp < ttl);

      // Sort by timestamp (oldest first) and limit size
      entries.sort((a, b) => a[1].timestamp - b[1].timestamp);
      if (entries.length > maxSize) {
        entries = entries.slice(-maxSize);
      }

      cache = Object.fromEntries(entries);
      localStorage.setItem(cacheKey, JSON.stringify(cache));
      console.log(`[Fullchan X] Cleaned cache ${cacheKey}, ${entries.length} entries remain`);
    } catch (error) {
      console.warn(`[Fullchan X] Error cleaning cache ${cacheKey}:`, error);
    }
  }

  processPendingYous() {
    try {
      console.log('[Fullchan X] Processing pending (You)s...');
      if (this.pendingSeenYous.length === 0) {
        console.log('[Fullchan X] No pending (You)s to process.');
        return;
      }
      this.seenYous.push(...this.pendingSeenYous);
      this.pendingSeenYous = [];
      try {
        localStorage.setItem(this.seenKey, JSON.stringify(this.seenYous));
        console.log(`[Fullchan X] Saved seenYous: ${this.seenYous.length}`);
      } catch (e) {
        console.warn(`[Fullchan X] Failed to save seenYous: ${e.message}`);
      }
      this.updateYous();
      console.log('[Fullchan X] Pending (You)s processed.');
    } catch (error) {
      console.error('[Fullchan X] Error processing pending (You)s:', error);
    }
  }

  observers() {
    try {
      console.log('[Fullchan X] Setting up observers...');
      if (!this.postOrderSelect) {
        console.error('[Fullchan X] Post order select not found, skipping sort listener.');
      } else {
        this.postOrderSelect.addEventListener('change', (event) => {
          this.postOrder = event.target.value || 'default';
          this.assignPostOrder();
          console.log(`[Fullchan X] Post order changed to: ${this.postOrder}`);
        });
      }

      const lowResCheckbox = this.querySelector('#low-res-previews');
      if (lowResCheckbox) {
        lowResCheckbox.addEventListener('change', (event) => {
          this.lowResPreviews = event.target.checked;
          localStorage.setItem('fullchanx-low-res-previews', JSON.stringify(this.lowResPreviews));
          console.log(`[Fullchan X] Low-res previews: ${this.lowResPreviews}`);
        });
      } else {
        console.warn('[Fullchan X] Low-res checkbox not found.');
      }

      const controlsCheckbox = this.querySelector('#toggle-controls');
      if (controlsCheckbox) {
        controlsCheckbox.addEventListener('change', (event) => {
          const isVisible = event.target.checked;
          localStorage.setItem('fullchanx-controls-visible', JSON.stringify(isVisible));
          const controlsContainer = this.querySelector('.fcx__controls__inner');
          if (controlsContainer) {
            controlsContainer.style.display = isVisible ? 'flex' : 'none';
            console.log(`[Fullchan X] Control box visibility: ${isVisible}`);
          }
        });
        const isVisible = JSON.parse(localStorage.getItem('fullchanx-controls-visible') || 'true');
        const controlsContainer = this.querySelector('.fcx__controls__inner');
        if (controlsContainer) {
          controlsContainer.style.display = isVisible ? 'flex' : 'none';
          controlsCheckbox.checked = isVisible;
          console.log(`[Fullchan X] Initial control box visibility: ${isVisible}`);
        }
      } else {
        console.warn('[Fullchan X] Controls toggle checkbox not found.');
      }

      let debounceTimeout;
      const observerCallback = (mutationsList) => {
        console.log('[Fullchan X] MutationObserver triggered');
        clearTimeout(debounceTimeout);
        debounceTimeout = setTimeout(() => {
          try {
            for (const mutation of mutationsList) {
              if (mutation.type === 'childList') {
                this.posts = [...this.thread.querySelectorAll('.postCell, [class*="post"]')];
                console.log(`[Fullchan X] Updated posts: ${this.posts.length}`);
                if (this.postOrder !== 'default') this.assignPostOrder();
                this.updateYous();
                this.updateVideoLinks();
                this.updateAudioLinks();
                this.updateImageLinks();
                this.addVideoHoverListeners();
                this.addAudioHoverListeners();
                this.addImageHoverListeners();
                this.addKeyboardListeners();
              }
            }
          } catch (error) {
            console.error('[Fullchan X] Observer error:', error);
          }
        }, 100);
      };

      const threadObserver = new MutationObserver(observerCallback);
      threadObserver.observe(this.thread, { childList: true, subtree: true });
      console.log('[Fullchan X] MutationObserver set up.');

      if (this.enableNestedQuotes) {
        this.thread.addEventListener('click', (event) => this.handleClick(event));
        console.log('[Fullchan X] Nested quote click listener added.');
      }
    } catch (error) {
      console.error('[Fullchan X] Observers setup failed:', error);
    }
  }

  updateYous() {
    try {
      console.log('[Fullchan X] Updating (You)s...');
      this.yous = this.posts.filter(post => {
        console.log(`[Fullchan X] Checking for .quoteLink.you in post: id=${post.id}`);
        const youLink = post.querySelector('.quoteLink.you, .quoteLink[id*="you"]');
        if (youLink) {
          console.log(`[Fullchan X] Matched (You) in post: id=${post.id}`);
          return true;
        }
        console.log(`[Fullchan X] No (You) found in post: id=${post.id}`);
        return false;
      });
      console.log(`[Fullchan X] Found ${this.yous.length} (You)s`);

      this.yousLinks = this.yous.map(you => {
        const youLink = document.createElement('a');
        youLink.textContent = '>>' + you.id;
        youLink.href = '#' + you.id;
        return youLink;
      });

      this.setUnseenYous();

      if (this.yousContainer) {
        this.yousContainer.innerHTML = '';
        this.yousLinks.forEach(you => {
          const youId = you.textContent.replace('>>', '');
          if (!this.seenYous.includes(youId)) {
            you.classList.add('unseen');
          }
          this.yousContainer.appendChild(you);
        });
        console.log('[Fullchan X] Updated #my-yous with links.');
      } else {
        console.warn('[Fullchan X] #my-yous container not found.');
      }

      if (this.myYousLabel) {
        this.myYousLabel.classList.toggle('unseen', this.unseenYous.length > 0);
        console.log(`[Fullchan X] Updated .my-yous__label, unseen: ${this.unseenYous.length > 0}`);
      } else {
        console.warn('[Fullchan X] .my-yous__label not found.');
      }
    } catch (error) {
      console.error('[Fullchan X] Error updating (You)s:', error);
    }
  }

  setUnseenYous() {
    try {
      console.log('[Fullchan X] Setting unseen (You)s...');
      this.seenKey = `fullchanx-${this.threadId}-seen-yous`;
      let storedYous = [];
      try {
        const stored = localStorage.getItem(this.seenKey);
        if (stored) {
          storedYous = JSON.parse(stored);
          if (!Array.isArray(storedYous)) {
            console.warn('[Fullchan X] Invalid seenYous format, resetting to []');
            storedYous = [];
            localStorage.setItem(this.seenKey, JSON.stringify(storedYous));
            console.log('[Fullchan X] Cleared invalid seenYous data.');
          }
        }
        console.log(`[Fullchan X] Loaded seenYous: ${storedYous.length}`);
      } catch (e) {
        console.warn(`[Fullchan X] Error reading seenYous: ${e.message}, using []`);
        storedYous = [];
        localStorage.setItem(this.seenKey, JSON.stringify(storedYous));
        console.log('[Fullchan X] Initialized seenYous to [] due to error.');
      }

      this.seenYous = storedYous;
      this.unseenYous = this.yous.filter(you => !this.seenYous.includes(you.id));
      console.log(`[Fullchan X] Unseen (You)s: ${this.unseenYous.length}`);

      this.unseenYous.forEach(you => {
        if (!you.classList.contains('observe-you')) {
          this.observeUnseenYou(you);
        }
      });

      const hasUnseenYous = this.unseenYous.length > 0 || this.pendingSeenYous.length > 0;
      document.title = hasUnseenYous
        ? document.title.startsWith('🔴 ') ? document.title : `🔴 ${document.title}`
        : document.title.replace(/^🔴 /, '');
      console.log(`[Fullchan X] Title updated, hasUnseenYous: ${hasUnseenYous}`);
    } catch (error) {
      console.error('[Fullchan X] Error setting unseen (You)s:', error);
    }
  }

  observeUnseenYou(you) {
    try {
      if (!you) return;
      you.classList.add('observe-you');
      console.log(`[Fullchan X] Observing unseen (You): id=${you.id}`);

      const observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            const id = you.id;
            you.classList.remove('observe-you');
            console.log(`[Fullchan X] Detected (You) in view: id=${id}`);

            if (this.tabFocused) {
              console.log(`[Fullchan X] Tab focused, marking (You) as seen: id=${id}`);
              if (!this.seenYous.includes(id)) {
                this.seenYous.push(id);
                try {
                  localStorage.setItem(this.seenKey, JSON.stringify(this.seenYous));
                  console.log(`[Fullchan X] Saved seenYous: ${this.seenYous.length}`);
                } catch (e) {
                  console.warn(`[Fullchan X] Failed to save seenYous: ${e.message}`);
                }
              }
              observer.unobserve(you);
              console.log(`[Fullchan X] Stopped observing: id=${id}`);
              this.updateYous();
            } else {
              console.log(`[Fullchan X] Tab not focused, added to pendingSeenYous: id=${id}`);
              if (!this.pendingSeenYous.includes(id)) {
                this.pendingSeenYous.push(id);
              }
              observer.unobserve(you);
              console.log(`[Fullchan X] Stopped observing: id=${id}`);
            }
          }
        });
      }, { rootMargin: '0px', threshold: 0.1 });

      observer.observe(you);
    } catch (error) {
      console.error('[Fullchan X] Error observing unseen (You):', error);
    }
  }

  updateVideoLinks() {
    try {
      console.log('[Fullchan X] Updating video links...');
      const links = [
        ...this.thread.querySelectorAll('a[data-filemime^="video/"]'),
        ...this.thread.querySelectorAll('a[href*="youtube.com/"], a[href*="youtu.be/"], a[href*="vimeo.com/"], a[href*="streamable.com/"]')
      ];
      this.videoLinks = [...new Set(links)];
      console.log(`[Fullchan X] Found ${this.videoLinks.length} video links:`, this.videoLinks.map(l => l.href));
      this.replaceVideoLinks();
    } catch (error) {
      console.error('[Fullchan X] Error updating video links:', error);
    }
  }

  updateAudioLinks() {
    try {
      this.audioLinks = [...this.thread.querySelectorAll('a[data-filemime^="audio/"]')];
      console.log(`[Fullchan X] Found ${this.audioLinks.length} audio links`);
    } catch (error) {
      console.error('[Fullchan X] Error updating audio links:', error);
    }
  }

  updateImageLinks() {
    try {
      this.imageLinks = [...this.thread.querySelectorAll('a[data-filemime^="image/"]')];
      console.log(`[Fullchan X] Found ${this.imageLinks.length} image links`);
    } catch (error) {
      console.error('[Fullchan X] Error updating image links:', error);
    }
  }

  async fetchVideoTitle(url) {
    try {
      // NEW: Check title cache
      const cachedTitle = this.getCachedTitle(url);
      if (cachedTitle) return cachedTitle;

      const urlObj = new URL(url);
      let oEmbedUrl;
      if (urlObj.hostname.includes('youtube.com') || urlObj.hostname === 'youtu.be') {
        oEmbedUrl = `https://www.youtube.com/oembed?url=${encodeURIComponent(url)}&format=json`;
      } else if (urlObj.hostname.includes('vimeo.com')) {
        oEmbedUrl = `https://vimeo.com/api/oembed.json?url=${encodeURIComponent(url)}`;
      } else if (urlObj.hostname.includes('streamable.com')) {
        oEmbedUrl = `https://api.streamable.com/oembed.json?url=${encodeURIComponent(url)}`;
      } else {
        console.log(`[Fullchan X] Skipping non-supported video URL: ${url}`);
        return url;
      }

      console.log(`[Fullchan X] Fetching title for ${url} via ${oEmbedUrl}`);
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 5000);
      const response = await fetch(oEmbedUrl, { signal: controller.signal });
      clearTimeout(timeoutId);

      if (!response.ok) {
        throw new Error(`HTTP ${response.status} for ${oEmbedUrl}`);
      }
      const data = await response.json();
      const title = data.title || url;
      console.log(`[Fullchan X] Title fetched: ${title}`);

      // NEW: Cache the title
      this.setCachedTitle(url, title);

      return title;
    } catch (error) {
      console.warn(`[Fullchan X] Failed to fetch title for ${url}:`, error.message);
      return url;
    }
  }

  async processApiQueue() {
    try {
      console.log('[Fullchan X] Processing API queue...');
      while (this.apiQueue.length > 0) {
        const activeRequests = this.apiQueue.filter(req => req.status === 'pending').length;
        if (activeRequests < this.maxConcurrentRequests) {
          const request = this.apiQueue.find(req => req.status === 'queued');
          if (request) {
            request.status = 'pending';
            try {
              const title = await this.fetchVideoTitle(request.url);
              request.resolve(title);
            } catch (error) {
              request.reject(error);
            }
            request.status = 'completed';
            this.apiQueue = this.apiQueue.filter(req => req.status !== 'completed');
          }
        }
        await new Promise(resolve => setTimeout(resolve, this.requestDelay));
      }
      console.log('[Fullchan X] API Queue cleared.');
    } catch (error) {
      console.error('[Fullchan X] API Queue error:', error);
    }
  }

  async replaceVideoLinks() {
    try {
      console.log('[Fullchan X] Replacing video link titles...');
      for (const link of this.videoLinks) {
        try {
          const isTrusted = this.isTrustedSource(link.href);
          console.log(`[Fullchan X] Checking trust for ${link.href}: ${isTrusted}`);
          if (!isTrusted) {
            console.log(`[Fullchan X] Skipped untrusted video link: ${link.href}`);
            continue;
          }
          const urlObj = new URL(link.href);
          if (
            urlObj.hostname.includes('youtube.com') ||
            urlObj.hostname === 'youtu.be' ||
            urlObj.hostname.includes('vimeo.com') ||
            urlObj.hostname.includes('streamable.com')
          ) {
            if (link.dataset.titleProcessed) {
              console.log(`[Fullchan X] Skipping already processed link: ${link.href}`);
              continue;
            }
            link.dataset.titleProcessed = 'true';
            const originalText = link.textContent;

            const titlePromise = new Promise((resolve, reject) => {
              this.apiQueue.push({
                url: link.href,
                status: 'queued',
                resolve,
                reject
              });
            });
            this.processApiQueue();

            const title = await titlePromise;
            if (title !== link.href) {
              link.textContent = title;
              link.title = originalText;
              console.log(`[Fullchan X] Replaced title for ${link.href}: ${title}`);
            } else {
              console.log(`[Fullchan X] No title change for ${link.href}`);
            }
          } else {
            console.log(`[Fullchan X] Skipped non-supported video link: ${link.href}`);
          }
        } catch (error) {
          console.warn(`[Fullchan X] Error processing video link ${link.href}:`, error);
        }
      }
    } catch (error) {
      console.error('[Fullchan X] Error replacing video links:', error);
    }
  }

  isTrustedSource(url) {
    try {
      // NEW: Check trust cache
      const cachedTrust = this.getCachedTrust(url);
      if (cachedTrust !== null) return cachedTrust;

      const urlObj = new URL(url);
      const isTrusted = this.trustedDomains.some(domain =>
        urlObj.hostname === domain ||
        urlObj.hostname.endsWith(`.${domain}`) ||
        urlObj.hostname.includes(domain)
      );
      console.log(`[Fullchan X] Trust check for ${url}: hostname=${urlObj.hostname}, trusted=${isTrusted}`);

      // NEW: Cache trust result
      this.setCachedTrust(url, isTrusted);

      return isTrusted;
    } catch (e) {
      console.warn(`[Fullchan X] Invalid URL: ${url}`);
      return false;
    }
  }

  addVideoHoverListeners() {
    try {
      console.log('[Fullchan X] Adding video hover listeners...');
      this.videoLinks.forEach(link => {
        if (link.dataset.hoverProcessed) return;
        link.dataset.hoverProcessed = 'true';
        link.tabIndex = 0;

        let videoElement = null;

        const createVideoElement = (event) => {
          if (!this.isTrustedSource(link.href)) return;

          if (!videoElement) {
            videoElement = document.createElement('video');
            videoElement.src = link.href;
            videoElement.volume = 0.5;
            videoElement.loop = true;
            videoElement.style.position = 'fixed';
            videoElement.style.zIndex = '1000';
            videoElement.style.pointerEvents = 'none';
            videoElement.style.maxWidth = this.lowResPreviews ? '480px' : '90vw';
            videoElement.style.maxHeight = this.lowResPreviews ? '270px' : '90vh';
            document.body.appendChild(videoElement);

            videoElement.play().catch(error => {
              console.error(`[Fullchan X] Video playback failed for ${link.href}:`, error);
            });

            videoElement.addEventListener('loadedmetadata', () => {
              videoElement.style.width = this.lowResPreviews ? '480px' : `${videoElement.videoWidth}px`;
              videoElement.style.height = this.lowResPreviews ? '270px' : `${videoElement.videoHeight}px`;
              this.positionPreviewInViewport(videoElement, event);
            });
          }

          this.positionPreviewInViewport(videoElement, event);
        };

        link.addEventListener('mouseenter', createVideoElement);
        link.addEventListener('keydown', (event) => {
          if (event.key === 'Enter') {
            createVideoElement(event);
          } else if (event.key === 'Escape' && videoElement) {
            videoElement.pause();
            videoElement.currentTime = 0;
            videoElement.remove();
            videoElement = null;
          }
        });
        link.addEventListener('mousemove', (event) => {
          if (videoElement) {
            this.positionPreviewInViewport(videoElement, event);
          }
        });
        link.addEventListener('mouseleave', () => {
          if (videoElement) {
            videoElement.pause();
            videoElement.currentTime = 0;
            videoElement.remove();
            videoElement = null;
          }
        });
        link.addEventListener('click', () => {
          if (videoElement) {
            videoElement.remove();
            videoElement = null;
          }
        });
      });
    } catch (error) {
      console.error('[Fullchan X] Error adding video hover listeners:', error);
    }
  }

  addImageHoverListeners() {
    try {
      console.log('[Fullchan X] Adding image hover listeners...');
      this.imageLinks.forEach(link => {
        if (link.dataset.hoverProcessed) return;
        link.dataset.hoverProcessed = 'true';
        link.tabIndex = 0;

        let imageElement = null;

        const createImageElement = (event) => {
          if (!this.isTrustedSource(link.href)) return;

          if (!imageElement) {
            imageElement = document.createElement('img');
            imageElement.src = link.href;
            imageElement.style.position = 'fixed';
            imageElement.style.zIndex = '1000';
            imageElement.style.pointerEvents = 'none';
            imageElement.style.maxWidth = '70vw';
            imageElement.style.maxHeight = '70vh';
            document.body.appendChild(imageElement);

            this.positionPreviewInViewport(imageElement, event);
          }
        };

        link.addEventListener('mouseenter', createImageElement);
        link.addEventListener('keydown', (event) => {
          if (event.key === 'Enter') {
            createImageElement(event);
          } else if (event.key === 'Escape' && imageElement) {
            imageElement.remove();
            imageElement = null;
          }
        });
        link.addEventListener('mousemove', (event) => {
          if (imageElement) {
            this.positionPreviewInViewport(imageElement, event);
          }
        });
        link.addEventListener('mouseleave', () => {
          if (imageElement) {
            imageElement.remove();
            imageElement = null;
          }
        });
        link.addEventListener('click', () => {
          if (imageElement) {
            imageElement.remove();
            imageElement = null;
          }
        });
      });
    } catch (error) {
      console.error('[Fullchan X] Error adding image hover listeners:', error);
    }
  }

  positionPreviewInViewport(element, event) {
    try {
      if (!element || !event) return;
      const offset = 10;
      const topBoundaryMargin = 60;
      const sideBoundaryMargin = 10;
      const mouseX = event.clientX;
      const mouseY = event.clientY;
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      const elementRect = element.getBoundingClientRect();
      const elementWidth = elementRect.width || (element.videoWidth ? element.videoWidth : 300);
      const elementHeight = elementRect.height || (element.videoHeight ? element.videoHeight : 300);

      let left = mouseX + offset;
      let top = mouseY + offset;

      if (left + elementWidth > viewportWidth - sideBoundaryMargin) {
        left = mouseX - elementWidth - offset;
      }
      if (left < sideBoundaryMargin) {
        left = sideBoundaryMargin;
      }

      if (top + elementHeight > viewportHeight - sideBoundaryMargin) {
        top = mouseY - elementHeight - offset;
      }
      if (top < topBoundaryMargin) {
        top = topBoundaryMargin;
      }

      element.style.left = `${left}px`;
      element.style.top = `${top}px`;
    } catch (error) {
      console.error('[Fullchan X] Error positioning preview:', error);
    }
  }

  addAudioHoverListeners() {
    try {
      console.log('[Fullchan X] Adding audio hover listeners...');
      this.audioLinks.forEach(link => {
        if (link.dataset.hoverProcessed) return;
        link.dataset.hoverProcessed = 'true';
        link.tabIndex = 0;

        let audioElement = null;

        const createAudioElement = () => {
          if (!this.isTrustedSource(link.href)) return;

          if (!audioElement) {
            audioElement = document.createElement('audio');
            audioElement.src = link.href;
            audioElement.volume = 0.5;
            link.appendChild(audioElement);

            const indicator = document.createElement('div');
            indicator.classList.add('audio-preview-indicator');
            indicator.textContent = 'â–¶ Playing audio...';
            link.appendChild(indicator);
          }

          audioElement.play().catch(error => {
            console.error(`[Fullchan X] Audio playback failed for ${link.href}:`, error);
          });
        };

        link.addEventListener('mouseenter', createAudioElement);
        link.addEventListener('keydown', (event) => {
          if (event.key === 'Enter') {
            createAudioElement();
          } else if (event.key === 'Escape' && audioElement) {
            audioElement.pause();
            audioElement.currentTime = 0;
            const indicator = link.querySelector('.audio-preview-indicator');
            if (indicator) indicator.remove();
            audioElement.remove();
            audioElement = null;
          }
        });
        link.addEventListener('mouseleave', () => {
          if (audioElement) {
            audioElement.pause();
            audioElement.currentTime = 0;
            const indicator = link.querySelector('.audio-preview-indicator');
            if (indicator) indicator.remove();
            audioElement.remove();
            audioElement = null;
          }
        });
        link.addEventListener('click', () => {
          if (audioElement) {
            audioElement.remove();
            audioElement = null;
            const indicator = link.querySelector('.audio-preview-indicator');
            if (indicator) indicator.remove();
          }
        });
      });
    } catch (error) {
      console.error('[Fullchan X] Error adding audio hover listeners:', error);
    }
  }

  addKeyboardListeners() {
    try {
      console.log('[Fullchan X] Adding keyboard listeners...');
      [...this.videoLinks, ...this.audioLinks, ...this.imageLinks].forEach(link => {
        if (!link.tabIndex) {
          link.tabIndex = 0;
        }
      });
    } catch (error) {
      console.error('[Fullchan X] Error adding keyboard listeners:', error);
    }
  }

  addQuickReplyKeyboardHandlers() {
    try {
      console.log('[Fullchan X] Setting up quick reply keyboard handlers...');
      document.addEventListener('keydown', (event) => {
        try {
          if (event.key === 'Escape' && this.quickReply && getComputedStyle(this.quickReply).display !== 'none') {
            this.quickReply.style.display = 'none';
            console.log('[Fullchan X] Quick reply closed via Escape.');
          }
        } catch (error) {
          console.error('[Fullchan X] Keyboard handler error:', error);
        }
      });
      console.log('[Fullchan X] Escape key listener added.');

      const qrbody = this.quickReply?.querySelector('#qrbody') || this.quickReply?.querySelector('textarea');
      if (!qrbody) {
        console.warn('[Fullchan X] #qrbody or textarea not found, skipping spoiler keybind.');
        return;
      }
      console.log('[Fullchan X] #qrbody or textarea found, adding spoiler keybind.');

      qrbody.addEventListener('keydown', (event) => {
        try {
          if (event.ctrlKey && event.key === 's') {
            event.preventDefault();
            const start = qrbody.selectionStart;
            const end = qrbody.selectionEnd;
            const text = qrbody.value;
            const selectedText = text.slice(start, end);

            const spoilerText = selectedText ? `[spoiler]${selectedText}[/spoiler]` : '[spoiler][/spoiler]';
            qrbody.value = text.slice(0, start) + spoilerText + text.slice(end);

            const newCursorPos = selectedText ? start + 9 + selectedText.length : start + 9;
            qrbody.setSelectionRange(newCursorPos, newCursorPos);

            console.log(`[Fullchan X] Added spoiler tags, cursor at: ${newCursorPos}`);
          }
        } catch (error) {
          console.error('[Fullchan X] Spoiler keybind error:', error);
        }
      });
      console.log('[Fullchan X] Ctrl+S key listener added.');
    } catch (error) {
      console.error('[Fullchan X] Error adding quick reply handlers:', error);
    }
  }

  handleClick(event) {
    try {
      if (!event.target) return;
      const clicked = event.target;
      const post = clicked.closest('.innerPost') || clicked.closest('.innerOP');
      if (!post) return;

      const isNested = !!post.closest('.innerNested');
      const nestQuote = clicked.closest('a.quoteLink');
      const postMedia = clicked.closest('a[data-filemime]');
      const postId = clicked.closest('.linkQuote');

      if (nestQuote) {
        event.preventDefault();
        event.stopPropagation();
        this.nestQuote(nestQuote);
      } else if (postMedia && isNested) {
        this.handleMediaClick(event, postMedia);
      } else if (postId && isNested) {
        this.handleIdClick(postId);
      }
    } catch (error) {
      console.error('[Fullchan X] Click handler error:', error);
    }
  }

  handleMediaClick(event, postMedia) {
    try {
      if (!postMedia || !postMedia.dataset.filemime) return;
      if (postMedia.dataset.filemime.startsWith('video/') || postMedia.dataset.filemime.startsWith('audio/')) return;
      event.preventDefault();
      const imageSrc = postMedia.href;
      const imageEl = postMedia.querySelector('img');
      if (!imageEl) return;

      if (!postMedia.dataset.thumbSrc) postMedia.dataset.thumbSrc = imageEl.src;
      const isExpanding = imageEl.src !== imageSrc;

      imageEl.src = isExpanding ? imageSrc : postMedia.dataset.thumbSrc;
      imageEl.classList.toggle('imgExpanded', isExpanding);
    } catch (error) {
      console.error('[Fullchan X] Media click error:', error);
    }
  }

  handleIdClick(postId) {
    try {
      if (!postId || !this.quickReply) return;
      const idNumber = '>>' + postId.textContent;
      this.quickReply.style.display = 'block';
      const qrbody = this.quickReply.querySelector('#qrbody') || this.quickReply.querySelector('textarea');
      if (qrbody) qrbody.value += idNumber + '\n';
    } catch (error) {
      console.error('[Fullchan X] ID click error:', error);
    }
  }

  assignPostOrder() {
    try {
      console.log(`[Fullchan X] Assigning post order: ${this.postOrder}`);
      const postOrderReplies = (post) => {
        const replyCount = post.querySelectorAll('.panelBacklinks a').length;
        post.style.order = 100 - replyCount;
      };

      const postOrderCatbox = (post) => {
        const postContent = post.querySelector('.divMessage')?.textContent || '';
        const matches = postContent.match(/catbox\.moe/g);
        const catboxCount = matches ? matches.length : 0;
        post.style.order = 100 - catboxCount;
      };

      if (this.postOrder === 'default') {
        this.thread.style.display = 'block';
        return;
      }

      this.thread.style.display = 'flex';
      if (this.postOrder === 'replies') {
        this.posts.forEach(post => postOrderReplies(post));
      } else if (this.postOrder === 'catbox') {
        this.posts.forEach(post => postOrderCatbox(post));
      }
    } catch (error) {
      console.error('[Fullchan X] Post order error:', error);
    }
  }

  nestQuote(quoteLink) {
    try {
      console.log('[Fullchan X] Nesting quote...');
      if (!quoteLink) throw new Error('No quoteLink provided.');
      const parentPostMessage = quoteLink.closest('.divMessage');
      const quoteId = quoteLink.href.split('#')[1];
      console.log(`[Fullchan X] Quote ID: ${quoteId}`);
      if (!quoteId) throw new Error('Invalid quote ID.');
      const quotePost = document.getElementById(quoteId);
      if (!quotePost || !parentPostMessage) throw new Error(`Quote post (${quoteId}) or parent message not found.`);

      const quotePostContent = quotePost.querySelector('.innerPost, .innerOP') || quotePost.querySelector('.postCell, [class*="post"]');
      console.log(`[Fullchan X] Quote post content: ${quotePostContent ? 'found' : 'not found'}`);
      if (!quotePostContent) throw new Error(`Quote post content not found for ${quoteId}.`);

      const existing = parentPostMessage.querySelector(`.nestedPost[data-quote-id="${quoteId}"]`);
      if (existing) {
        existing.remove();
        console.log(`[Fullchan X] Removed existing nested quote: ${quoteId}`);
        return;
      }

      const wrapper = document.createElement('div');
      wrapper.classList.add('nestedPost');
      wrapper.setAttribute('data-quote-id', quoteId);

      const clone = quotePostContent.cloneNode(true);
      console.log('[Fullchan X] Cloned post content.');
      clone.querySelectorAll('.panelBacklinks, .postControls').forEach(el => el.remove());
      clone.style.whiteSpace = 'unset';
      clone.classList.add('innerNested');

      const htmlContent = DOMPurify.sanitize(clone.outerHTML, {
        ALLOWED_TAGS: ['div', 'span', 'p', 'a', 'img', 'br', 'strong', 'em', 'blockquote', 'pre', 'code'],
        ALLOWED_ATTR: ['href', 'src', 'class', 'style', 'data-filemime', 'data-thumb-src', 'alt', 'title']
      });
      console.log(`[Fullchan X] Sanitized content length: ${htmlContent.length}`);
      if (!htmlContent) throw new Error('Sanitized content is empty.');

      wrapper.innerHTML = htmlContent;
      parentPostMessage.appendChild(wrapper);
      console.log(`[Fullchan X] Nested quote added: ${quoteId}`);
    } catch (error) {
      console.error('[Fullchan X] Failed to create nested quote:', error.message);
    }
  }
}

try {
  console.log('[Fullchan X] Defining custom element: fullchan-x');
  window.customElements.define('fullchan-x', FullChanX);
  console.log('[Fullchan X] Custom element defined successfully.');
} catch (error) {
  console.error('[Fullchan X] Failed to define custom element:', error);
}

try {
  console.log('[Fullchan X] Creating custom element...');
  const fcx = document.createElement('fullchan-x');
  console.log(`[Fullchan X] Element created, instance of FullChanX: ${fcx instanceof FullChanX}`);
  fcx.innerHTML = `
    <div class="fcx__controls">
      <label for="toggle-controls" style="margin-bottom: 5px;">
        <input type="checkbox" id="toggle-controls" ${JSON.parse(localStorage.getItem('fullchanx-controls-visible') || 'true') ? 'checked' : ''}>
        Show Controls
      </label>
      <div class="fcx__controls__inner" style="display: ${JSON.parse(localStorage.getItem('fullchanx-controls-visible') || 'true') ? 'flex' : 'none'}; flex-direction: column; gap: 5px;">
        <select id="thread-sort" aria-label="Sort thread posts">
          <option value="default">Default</option>
          <option value="replies">Replies</option>
          <option value="catbox">Catbox</option>
        </select>
        <label for="low-res-previews" style="margin-top: 5px;">
          <input type="checkbox" id="low-res-previews" ${JSON.parse(localStorage.getItem('fullchanx-low-res-previews') || 'false') ? 'checked' : ''}>
          Low-Res Video Previews
        </label>
        <div class="fcx__my-yous" role="region" aria-label="Posts mentioning you">
          <p class="my-yous__label">My (You)s</p>
          <div class="my-yous__yous" id="my-yous"></div>
        </div>
      </div>
    </div>
  `;
  document.body.appendChild(fcx);
  console.log('[Fullchan X] Custom element appended to body.');
  if (fcx instanceof FullChanX) {
    fcx.init();
    console.log('[Fullchan X] Custom element initialized.');
  } else {
    console.error('[Fullchan X] Element is not a FullChanX instance, skipping init.');
  }
} catch (error) {
  console.error('[Fullchan X] Failed to create or initialize custom element:', error);
}

const style = document.createElement('style');
style.innerHTML = `
  fullchan-x {
    display: block;
    position: fixed;
    top: 2.5rem;
    right: 2rem;
    padding: 10px;
    background: var(--contrast-color);
    border: 1px solid var(--navbar-text-color);
    color: var(--link-color);
    font-size: 14px;
    opacity: 0.5;
    z-index: 1000;
  }
  fullchan-x:hover { opacity: 1; }
  .divPosts { flex-direction: column; }
  .fcx__controls { display: flex; flex-direction: column; gap: 5px; }
  #thread-sort {
    padding: 0.4rem 0.6rem;
    background: white;
    border: none;
    border-radius: 0.2rem;
    transition: all ease 150ms;
    cursor: pointer;
  }
  #low-res-previews, #toggle-controls {
    margin-right: 5px;
  }
  .my-yous__yous { display: none; flex-direction: column; }
  .my-yous__label {
    padding: 0.4rem 0.6rem;
    background: white;
    border: none;
    border-radius: 0.2rem;
    transition: all ease 150ms;
    cursor: pointer;
  }
  .fcx__my-yous:hover .my-yous__yous { display: flex; }
  .innerPost:has(.quoteLink.you) { border-left: solid #dd003e 6px; }
  .innerPost:has(.youName) { border-left: solid #68b723 6px; }
  .nestedPost {
    max-width: 100%;
    box-sizing: border-box;
    background: var(--contrast-color);
    border-radius: 3px;
    display: block;
    visibility: visible;
  }
  .divMessage .nestedPost {
    display: block;
    white-space: normal;
    overflow-wrap: anywhere;
    margin-top: 0.5em;
    margin-bottom: 0.5em;
    border: 1px solid var(--navbar-text-color);
    padding: 8px;
  }
  .nestedPost .innerNested {
    width: 100%;
    max-width: 100%;
    display: block;
    font-size: 0.95em;
  }
  .nestedPost .divMessage {
    margin: 0;
    padding: 0;
    white-space: normal;
    display: block;
  }
  .nestedPost .postInfo {
    margin-bottom: 5px;
    font-size: 0.9em;
    display: block;
  }
  .nestedPost img, .nestedPost .imgLink img {
    max-width: 100%;
    max-height: 200px;
    height: auto;
    display: block;
  }
  .nestedPost .imgLink .imgExpanded {
    max-width: 100%;
    max-height: 300px;
    width: auto;
    height: auto;
  }
  .nestedPost a[data-filemime] {
    pointer-events: auto;
    display: inline-block;
  }
  .my-yous__label.unseen {
    background: var(--link-hover-color);
    color: white;
  }
  .my-yous__yous .unseen {
    font-weight: 900;
    color: var(--link-hover-color);
  }
  a[data-filemime^="video/"]:hover, a[data-filemime^="image/"]:hover, a[data-filemime^="audio/"]:hover {
    position: relative;
  }
  a[data-filemime]:focus {
    outline: 2px solid var(--link-hover-color);
  }
  .audio-preview-indicator {
    position: absolute;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 5px;
    font-size: 12px;
    border-radius: 3px;
    z-index: 1000;
  }
`;
try {
  document.head.appendChild(style);
  console.log('[Fullchan X] Styles appended to head.');
} catch (error) {
  console.error('[Fullchan X] Failed to append styles:', error);
}
Edit Report
Pub: 18 Apr 2025 14:58 UTC
Views: 14