// -------------- START OF CODE --------------
// UserScript
// @name DVDoom
// @namespace http://tampermonkey.net/
// @version 5.0.3
// @description Changes in 5.0.3: Radio and fixes.
// @author Seianon and Mimorianon
// @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @namespace rccom
// @match ://boards.4chan.org//thread/*
// @grant GM_xmlhttpRequest
// @connect 4chan.org
// @connect 4channel.org
// @connect static.wikitide.net
// @connect bluearchive.wiki
// @updateURL https://rentry.org/DVDoomSCRIPT/raw
// @downloadURL https://rentry.org/DVDoomSCRIPT/raw
// @require https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
// @require https://rentry.org/DVDoom_radio/raw
// @require https://rentry.org/dvdoom_hole/raw
// /UserScript
(async function() {

// Check for a thread.
if (!/^bag\/|\/bag\/|Blue Archive|BIue Archive/.test(document?.querySelector('.postInfo.desktop .subject')?.textContent?.trim() ?? '')) return;

//////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////// BIRTHDAY SECTION ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
await (async function() {
    const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    let fullStringTop = "";
    let fullStringBottom = "";

    // Check if DVDoomParent exists, if not, create it
    let dvDoomParent = document.getElementById("DVDoomParent");
    if (!dvDoomParent) {
        dvDoomParent = document.createElement('div');
        dvDoomParent.id = "DVDoomParent";
        dvDoomParent.style.display = 'flex';
        dvDoomParent.style.marginLeft = '3.5px';
        dvDoomParent.style.marginRight = '12.5px';
        dvDoomParent.style.justifyContent = 'space-between';

        // Find an appropriate place to insert DVDoomParent
        let targetElement = document.querySelector('.navLinks.desktop');
        if (targetElement) {
            targetElement.parentNode.insertBefore(dvDoomParent, targetElement);
        } else {
            document.body.appendChild(dvDoomParent);
        }
    }

    // Create and append the birthday and clock container
    let birthdayContainer = document.createElement('div');
    birthdayContainer.style.flexGrow = '5';
    birthdayContainer.style.flexBasis = '0';
    birthdayContainer.style.display = 'flex';
    birthdayContainer.style.flexDirection = 'column';
    birthdayContainer.style.alignItems = 'flex-start';
    birthdayContainer.style.justifyContent = 'center';
    dvDoomParent.appendChild(birthdayContainer);

    // Add updated styles for birthday table with vertical header
    const birthdayStyles = `
.birthday-table-container {
    width: fit-content;
    display: flex;
    align-items: stretch;
    gap: 0;
    margin: 0;
    height: fit-content;
}
.vertical-header {
    writing-mode: vertical-lr;
    transform: rotate(180deg);
    padding: 0 5px;
    border: 1px solid #ccc;
    border-radius: 0 5px 5px 0;
    border-left: none;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
}
.birthday-table {
    border-collapse: separate;
    border-spacing: 0;
    border: 1px solid #ccc;
    border-radius: 0 5px 5px 0;
    overflow: hidden;
    margin: 0;
    width: auto;
    height: auto;
}
.birthday-table th, .birthday-table td {
    border-right: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
    white-space: nowrap;
    padding: 8px;
}
.birthday-table th:last-child, .birthday-table td:last-child {
    border-right: none;
}
.birthday-table tr:last-child td {
    border-bottom: none;  /* Ensure last row has no bottom border */
}
.birthday-table tr {
    height: auto;
}
.image-container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60px;
    margin: auto;
}
.image-container img {
    max-width: 100%;
    max-height: 100%;
    display: block;
}

`;
// Add the styles to the document
const styleElement = document.createElement('style');
styleElement.textContent = birthdayStyles;
document.head.appendChild(styleElement);

    // Function to add days to a date
    function addDays(date, days) {
        const copy = new Date(Number(date));
        copy.setDate(date.getDate() + days);
        return copy;
    }

    // Fetch birthdays data from the API
    async function fetchBirthdays() {
        const response = await fetch('https://schaledb.com/data/en/students.json');
        const data = await response.json();

        const responseCustom = await fetch('https://rentry.org/dvdoombday/raw');
        const dataCustom = await responseCustom.json();

        // Iterate through each custom birthday list.
        for (let i = 0; i < dataCustom.length; i++) {
            // The current student.
            const customStudent = dataCustom[i];
            let actualStudent = {};
            // Check if it should replace.
            if (customStudent.Id) {
                // Obtain the existing student.
                actualStudent = data[customStudent.Id];
            } else {
                data[`DVDOOM_${i}`] = actualStudent;
            }
            // Override the values.
            actualStudent.FamilyName = customStudent.FamilyName;
            actualStudent.PersonalName = customStudent.PersonalName;
            actualStudent.BirthDay = customStudent.BirthDay;
            actualStudent.DirectImage = customStudent.DirectImage;
        }

        return Object.values(data).reduce((acc, student) => {
            const birthdayMatch = student.BirthDay.match(/(\d+)\/(\d+)/);
            if (!birthdayMatch) return acc;

            const monthNumber = parseInt(birthdayMatch[1], 10);
            const day = parseInt(birthdayMatch[2], 10);

            if (!acc[monthNumber]) {
                acc[monthNumber] = {};
            }
            if (!acc[monthNumber][day]) {
                acc[monthNumber][day] = [];
            }

            const studentFullName = `${student.FamilyName} ${student.PersonalName}`;
            let studentEntry = acc[monthNumber][day].find(char => char.name === studentFullName);

            const studentImage = (student.DirectImage) ? student.DirectImage : `https://schaledb.com/images/student/collection/${student.Id}.webp`;

            if (studentEntry) {
                if (!studentEntry.images.includes(studentImage)) {
                    studentEntry.images.push(studentImage);
                }
            } else {
                acc[monthNumber][day].push({
                    name: studentFullName,
                    images: [studentImage]
                });
            }
            return acc;
        }, {});
    }

    async function initBirthdayAndClock() {
        const birthdays = await fetchBirthdays();
        const baseDate = new Date();
        // This loop checks for birthdays today and up to the next 7 days
        for (let i = 0; i <= 6; i++) {
            const currentDate = addDays(baseDate, i);
            const month = currentDate.getMonth() + 1;
            const day = currentDate.getDate();

            const studentsByBirthday = birthdays[month]?.[day];
            if (studentsByBirthday) {
                fullStringTop += `<td style="font-weight: bold; padding: 8px; text-align: center;">${months[currentDate.getMonth()]} ${day}</td>`;
                fullStringBottom += `<td style="font-weight: bold; text-align: center;">`;

                for (const student of studentsByBirthday) {
                    fullStringBottom += `<div style="display: inline-block; padding: 8px;">
                    <div style="position: relative; text-align: justify;">
                        <center style="white-space: pre;">${student.name.replace(' ', '\n')}</center>
                        <center class="image-container" data-images="${student.images.join(',')}" style="width:60px;height:60px;">
                            <img src="${student.images[0]}" alt="${student.name}" style="width:60px;height:60px;">
                        </center>
                    </div>
                </div>`;
                }

                fullStringBottom += `</td>`;
            }
        }

        if (fullStringTop === '') {
            fullStringBottom = `
            <td style="font-weight: bold; text-align: center;">
                <div style="display: inline-block; padding: 8px;">
                    <div style="position: relative; text-align: justify;">
                        <center style="white-space: pre;">No upcoming student birthdays in the next 7 days</center>
                    </div>
                </div>
            </td>
        `;
        }

        // Updated HTML structure with vertical header
        let finalString = `
        <div class="birthday-table-container">
            <div class="vertical-header">Student Birthdays</div>
            <table class="birthday-table">
                <tr>${fullStringTop}</tr>
                <tr>${fullStringBottom}</tr>
            </table>
        </div>`;

        birthdayContainer.innerHTML = finalString;

        // Image cycling logic for multiple character images
        document.querySelectorAll('.image-container').forEach(container => {
            let images = container.dataset.images.split(',');
            let currentImageIndex = 0;

            images = [...new Set(images)];

            if (images.length > 1) {
                setInterval(() => {
                    currentImageIndex = (currentImageIndex + 1) % images.length;
                    container.querySelector('img').src = images[currentImageIndex];
                }, 5000);
            }
        });
    }

    // Initialize the birthday and clock functionality
    initBirthdayAndClock();
})();

//////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////// CLOCKS SECTION ///////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

await (async function() {

    // Check if DVDoomParent exists, if not, create it
    let dvDoomParent = document.getElementById("DVDoomParent");
    if (!dvDoomParent) {
        dvDoomParent = document.createElement('div');
        dvDoomParent.id = "DVDoomParent";
        dvDoomParent.style.display = 'flex';
        dvDoomParent.style.marginLeft = '3.5px';
        dvDoomParent.style.marginRight = '12.5px';
        dvDoomParent.style.justifyContent = 'space-between';

        // Find an appropriate place to insert DVDoomParent
        let targetElement = document.querySelector('.navLinks.desktop');
        if (targetElement) {
            targetElement.parentNode.insertBefore(dvDoomParent, targetElement);
        } else {
            document.body.appendChild(dvDoomParent);
        }
    }

    // Modify the table creation part
    document.getElementById("DVDoomParent").insertAdjacentHTML(
        'beforeend',
        `<div style="flex-grow: 2; flex-basis: 0; align-items: center; justify-content: center; display: flex;">
            <table id="seia-table" class="dvdoom-table" style="border: 1px solid #ccc; border-radius: 5px; flex: 1;">
                <tr><th id="clockJST" colspan="100%" style="width: 100%; font-size: 18px; font-weight: bold; padding: 12px; text-align: center; border-bottom-width: 0px;">JST TIME</th></tr>
                <tr><th id="clockUTC" colspan="100%" style="width: 100%; font-size: 18px; font-weight: bold; padding: 12px; text-align: center; border-top: 1px solid #ccc; border-bottom-width: 0px;">UTC TIME</th></tr>
            </table>
        </div>
    `);

    // Clock logic
    const clockCallbacks = {};
    const clockJST = document.getElementById("clockJST");
    const clockUTC = document.getElementById("clockUTC");
    const clockStyle = {
        hour: "numeric",
        minute: "numeric",
        second: "numeric",
        weekday: "short",
        month: "long",
        day: "numeric",
        hourCycle: 'h23'
    }
    setInterval(() => {
        const dateToUpdate = new Date();
        clockJST.textContent = dateToUpdate.toLocaleString('en-US', {
            ...clockStyle,
            ...{
                timeZone: 'Japan'
            }
        }).replace(' at', ',') + ' JST';
        clockUTC.textContent = dateToUpdate.toLocaleString('en-US', {
            ...clockStyle,
            ...{
                timeZone: 'UTC'
            }
        }).replace(' at', ',') + ' UTC';
        for (const [_, callbackFunction] of Object.entries(clockCallbacks)) {
            callbackFunction(dateToUpdate);
        }
    }, 1000);


})();

//////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////// DVDOOM SECTION ///////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
await (async function() {
    // Inject styles
    const styleElement = document.createElement('style');
    styleElement.textContent = `
    .image-container { display: flex; align-items: center; justify-content: center; height: 60px; margin: auto; }
    .image-container img { max-width: 100%; max-height: 100%; display: block; }
    .centered-text { text-align: center; margin: 0; font-size: 14px; line-height: 20px; height: 20px; overflow: hidden; }
    .student-name { display: block; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
    .seia-heart { display: inline-block; width: 200px; aspect-ratio: 1; border-image: radial-gradient(red 69%, #0000 70%) 84.5%/50%; clip-path: polygon(-41% 0, 50% 91%, 141% 0); }
    @keyframes seia-heart-animation { from { transform: translate3d(0, 0, 0); opacity: 0.65; } }
    .seia-text { font: 800 20px Arial; -webkit-text-fill-color: black; -webkit-text-stroke: 1px; -webkit-text-stroke-color: white}

    .quantity {   display: flex;   align-items: center;   justify-content: center;   padding: 0; }
    .quantity__minus, .quantity__plus {   display: block;   flex-grow: 1;  width: 0; height: 23px;   margin: 0;   background: #dee0ee;   text-decoration: none;   text-align: center;   line-height: 23px; }
    .seia-button {  display: block;   margin: 0;   background: #dee0ee;   text-decoration: none;   text-align: center;   line-height: 23px; }
    .seia-button:hover {  cursor: pointer; background: #575b71; color: currentColor !important; }
    .quantity__minus:hover, .quantity__plus:hover {  cursor: pointer; background: #575b71; color: #fff !important; }
    .quantity__minus {   border-radius: 3px 0 0 3px; -webkit-user-select: none; -moz-user-select: none; -khtml-user-select: none; -ms-user-select: none; }
    .quantity__plus {   border-radius: 0 3px 3px 0; -webkit-user-select: none; -moz-user-select: none; -khtml-user-select: none; -ms-user-select: none; }
    .quantity__input {   width: 40px;   height: 19px;   margin: 0;   padding: 0;   text-align: center;   border-top: 2px solid #dee0ee;   border-bottom: 2px solid #dee0ee;   border-left: 1px solid #dee0ee;   border-right: 2px solid #dee0ee;   background: #fff;   color: #8184a1; }
    input.quantity__input[type=number] { -moz-appearance: textfield; }
    input.quantity__input::-webkit-outer-spin-button, input.quantity__input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
    .quantity__minus:link, .quantity__plus:link {   color: #8184a1; }
    .quantity__minus:visited, .quantity__plus:visited {   color: #fff; }
`;
    // Add these styles to your existing styles
    const dvdoomStyles = `

.drawer {
position: fixed;
right: -200px;
top: 0;
width: 200px;
height: 100vh;
box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
transition: right 0.3s ease;
z-index: 9999;
display: flex;
flex-direction: column;
}

.drawer::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: inherit;
background-attachment: fixed;
z-index: -1;
}

.drawer.open {
right: 0;
}

.drawer-header {
padding: 20px;
border-bottom: 1px solid #ccc;
font-weight: bold;
text-align: center;
flex-shrink: 0;
position: relative;
background-color: rgba(222, 224, 238, 0.05);
backdrop-filter: blur(5px);
}

.drawer-content {
flex-grow: 1;
overflow-y: auto;
padding: 20px 20px 20px 10px;
height: 0;
scrollbar-width: thin;
scrollbar-color: rgba(0, 0, 0, 0.2) transparent;
margin-right: -10px;
}

.drawer-content::-webkit-scrollbar {
width: 6px;
}

.drawer-content::-webkit-scrollbar-track {
background: transparent;
}

.drawer-content::-webkit-scrollbar-thumb {
background-color: rgba(0, 0, 0, 0.2);
border-radius: 3px;
}

.drawer-footer {
padding: 20px;
border-top: 1px solid #ccc;
flex-shrink: 0;
position: relative;
background-color: rgba(222, 224, 238, 0.05);
backdrop-filter: blur(5px);
}

.menu-item {
margin-bottom: 20px;
padding: 15px;
border: 1px solid #ccc;
border-radius: 5px;
transition: background-color 0.3s ease;
background: rgba(255, 255, 255, 0.7);
backdrop-filter: blur(5px);
position: relative;
}

.menu-item-header {
font-weight: bold;
margin-bottom: 10px;
}

.menu-item-content {
display: flex;
flex-direction: column;
gap: 10px;
}

.quantity {
margin-bottom: 10px;
}

.eos-button {
width: 100%;
padding: 10px;
background: #dee0ee;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background 0.3s ease;
}

.eos-button:hover {
background: #575b71;
color: white;
}

.shortcut.brackets-wrap .seia-drawer-button {
display: inline-block;
width: 14px;
height: 14px;
-webkit-mask-image: url('https://files.catbox.moe/h16d09.png');
-webkit-mask-size: contain;
-webkit-mask-repeat: no-repeat;
mask-image: url('https://files.catbox.moe/h16d09.png');
mask-size: contain;
mask-repeat: no-repeat;
background-color: currentColor;
vertical-align: middle;
}

seiaHoleLink {

display: inline-flex;
align-items: center;

}
`;

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
    styleElement.textContent += dvdoomStyles;
    document.head.appendChild(styleElement);


    // Modified button creation function for 4chan X
    function create4chanXStyleButton() {
        const shortcutSpan = document.createElement('span');
        shortcutSpan.id = 'shortcut-seia';
        shortcutSpan.className = 'shortcut brackets-wrap';
        shortcutSpan.innerHTML = `<a href="javascript:;" title="Seia Menu"><span class="seia-drawer-button"></span></a>`;
        return shortcutSpan;
    }

    // Function to create classic 4chan style button
    function createClassicStyleButton() {
        return ` [<a href="javascript:void(0);" id="seiaMenuLink">Seia</a>] `;
    }

    // Modify the drawer creation to remove close button
    const drawer = document.createElement('div');
    drawer.className = 'drawer';
    drawer.innerHTML = `
        <div class="drawer-header">
            \< Seia DVD Menu \>
        </div>
        <div class="drawer-content">
            <!-- Menu items will be inserted here -->
        </div>
        <div class="drawer-footer">
            <button class="eos-button" onclick="forceEoS()">EoS</button>
        </div>
    `;

    document.body.appendChild(drawer);

    if (document.getElementById('shortcuts')) {
        const shortcuts = document.getElementById('shortcuts');
        const shortcutChildren = shortcuts.children;
        const lastElement = shortcutChildren[shortcutChildren.length - 1];

        const openDrawerButtonElement = create4chanXStyleButton();
        shortcuts.insertBefore(openDrawerButtonElement, lastElement);

        openDrawerButtonElement.querySelector('a').addEventListener('click', (e) => {
            e.preventDefault();
            drawer.classList.toggle('open');
        });
    } else {
        // Classic 4chan
        const navTopRight = document.getElementById('navtopright');
        if (navTopRight) {
            // Insert before the last bracket
            navTopRight.insertAdjacentHTML('afterbegin', createClassicStyleButton());
            const openDrawerButtonElement = document.getElementById('seiaMenuLink');
            if (openDrawerButtonElement) {
                openDrawerButtonElement.addEventListener('click', (e) => {
                    e.preventDefault();
                    drawer.classList.toggle('open');
                });
            }
        }
    }

    // Keep the click-outside handler
    document.addEventListener('click', (e) => {
        const isButton = e.target.matches('#seiaMenuLink, .seia-drawer-button, #shortcut-seia a');
        if (!drawer.contains(e.target) && !isButton) {
            drawer.classList.remove('open');
        }
    });

    // Function to copy background to drawer
    function copyBodyBackground(drawer) {
        // Get computed styles from both html and body elements
        const htmlStyle = window.getComputedStyle(document.documentElement);
        const bodyStyle = window.getComputedStyle(document.body);

        // Combine background properties, prioritizing html background-color if it exists
        const backgroundColor = htmlStyle.backgroundColor !== 'rgba(0, 0, 0, 0)' ? htmlStyle.backgroundColor : bodyStyle.backgroundColor;

        drawer.style.background = bodyStyle.background;
        drawer.style.backgroundColor = backgroundColor;
        drawer.style.backgroundImage = bodyStyle.backgroundImage;
        drawer.style.backgroundSize = bodyStyle.backgroundSize;
        drawer.style.backgroundPosition = bodyStyle.backgroundPosition;
        drawer.style.backgroundRepeat = bodyStyle.backgroundRepeat;
        drawer.style.backgroundAttachment = 'fixed';
    }


    // Helper function to convert color to rgba with opacity
    function colorToRGBA(color, opacity = 0.05) {
        // Create a temporary element to compute the color
        const temp = document.createElement('div');
        temp.style.color = color;
        document.body.appendChild(temp);

        // Get computed color
        const computedColor = window.getComputedStyle(temp).color;
        document.body.removeChild(temp);

        // Parse RGB values
        const match = computedColor.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        if (match) {
            return `rgba(${match[1]}, ${match[2]}, ${match[3]}, ${opacity})`;
        }

        // If color parsing fails, return a default transparent background
        return `rgba(0, 0, 0, ${opacity})`;
    }

    // Check if DVDoomParent exists, if not, create it
    let dvDoomParent = document.getElementById("DVDoomParent");
    if (!dvDoomParent) {
        dvDoomParent = document.createElement('div');
        dvDoomParent.id = "DVDoomParent";
        dvDoomParent.style.display = 'flex';
        dvDoomParent.style.marginLeft = '3.5px';
        dvDoomParent.style.marginRight = '12.5px';
        dvDoomParent.style.justifyContent = 'space-between';

        // Find an appropriate place to insert DVDoomParent
        let targetElement = document.querySelector('.navLinks.desktop');
        if (targetElement) {
            targetElement.parentNode.insertBefore(dvDoomParent, targetElement);
        } else {
            document.body.appendChild(dvDoomParent);
        }
        // Adding a horizontal rule below the parent div if needed
        dvDoomParent.insertAdjacentHTML('afterend', '<hr/>');
    }

    // Set up DOM elements
    const fragment = document.createDocumentFragment();
    const seiaEnclosure = document.createElement('div');
    seiaEnclosure.id = 'seiaEnclosure';
    fragment.appendChild(seiaEnclosure);
    const threadElement = document.getElementsByClassName("navLinks desktop")[0];
    threadElement.parentNode.insertBefore(fragment, threadElement);

    // Set up observers for both html and body elements
    const observers = [];

    function setupBackgroundObservers(drawer) {
        // Observer for html element
        const htmlObserver = new MutationObserver(() => {
            copyBodyBackground(drawer);
        });

        htmlObserver.observe(document.documentElement, {
            attributes: true,
            attributeFilter: ['style', 'class']
        });

        // Observer for body element
        const bodyObserver = new MutationObserver(() => {
            copyBodyBackground(drawer);
        });

        bodyObserver.observe(document.body, {
            attributes: true,
            attributeFilter: ['style', 'class']
        });

        observers.push(htmlObserver, bodyObserver);

        // Also update on system color scheme changes
        const colorSchemeObserver = window.matchMedia('(prefers-color-scheme: dark)');
        colorSchemeObserver.addListener(() => {
            copyBodyBackground(drawer);
        });
    }

    // Initial setup
    copyBodyBackground(drawer);
    setupBackgroundObservers(drawer);


    // Constants
    const DEFAULT_SIZE = 75;
    const DEFAULT_SPEED = 2;
    const MAX_TRAIL_LENGTH = 25;

    // Dynamic window size handling
    let screenWidth = window.innerWidth;
    let screenHeight = window.innerHeight;
    window.addEventListener('resize', () => {
        screenWidth = window.innerWidth;
        screenHeight = window.innerHeight;
    });

    // End of Service flag
    let EOS = false;

    // Seia management
    const SEIA_TYPE_MAP = new Map();
    const SEIA_STRING_ENUM = {};

    // Function used for integer randomization.
    function randomInt(min, max) {
        return Math.floor(Math.random() * max) + min;
    }

    // Used for image caching.
    const imageURLMap = {
        default: 'https://files.catbox.moe/ph1rgd.gif',
        defaultHearts: 'https://files.catbox.moe/0nujy7.gif',
        blush: 'https://files.catbox.moe/oz1irf.gif',
        blushHearts: 'https://files.catbox.moe/h6qcnz.gif',
        shiny: 'https://files.catbox.moe/p23xa2.gif',
        hole: 'https://files.catbox.moe/ri3pe7.png'
    };

    // Preloaded images will be stored here
    // Maybe we don't even need to use base 64?
    const imageCache = {};

    //////////////
    /// Seia collision logic
    const COORDINATE_LENGTH = 500;
    const SEIA_COORDINATE_MAP = [];
    const CoordinatesListItem = (superclass) => class CoordinatesListItem extends superclass {
        constructor(...args) {
            super(...args);
            this.currentCoordinate = Math.floor(this.positionY / COORDINATE_LENGTH);
            const currentHead = SEIA_COORDINATE_MAP[this.currentCoordinate];
            if (currentHead) {
                currentHead.prev = this;
                this.next = currentHead;
            }
            SEIA_COORDINATE_MAP[this.currentCoordinate] = this;
            this.prev = null;
        }

        get mass() {
            var density = 1;
            return density * this.elementSize * this.elementSize;
        }

        get v() {
            return [this.directionX, this.directionY];
        }

        dettach() {
            const currentHead = SEIA_COORDINATE_MAP[this.currentCoordinate];
            const nextNode = this.next;
            const prevNode = this.prev;
            this.next = null;
            this.prev = null;
            if (currentHead === this) SEIA_COORDINATE_MAP[this.currentCoordinate] = nextNode;
            if (nextNode) nextNode.prev = prevNode;
            if (prevNode) prevNode.next = nextNode;
        }

        attach() {
            const currentHead = SEIA_COORDINATE_MAP[this.currentCoordinate];
            if (currentHead) {
                currentHead.prev = this;
                this.next = currentHead;
            }
            SEIA_COORDINATE_MAP[this.currentCoordinate] = this;
            this.prev = null;
        }

        updateCoordinatePosition() {
            // Obtain the next coordinate.
            const nextCoordinate = Math.floor(this.positionY / COORDINATE_LENGTH);
            // Check if it has changed.
            if ((nextCoordinate != this.currentCoordinate) && (nextCoordinate >= 0)) {
                // console.log("Changing " + this.id);
                this.dettach();
                this.currentCoordinate = nextCoordinate;
                this.attach();
            }
        }

        collision(seiaStart) {
            let other = seiaStart;
            while (other) {
                var dx = this.positionX - other.positionX;
                var dy = this.positionY - other.positionY;
                if (Math.sqrt(dx * dx + dy * dy) < ((this.elementSize / 2) + (other.elementSize / 2))) {
                    var res = [this.directionX - other.directionX, this.directionY - other.directionY];
                    if (res[0] * (other.positionX - this.positionX) + res[1] * (other.positionY - this.positionY) >= 0) {
                        var m1 = this.mass
                        var m2 = other.mass
                        var theta = -Math.atan2(other.positionY - this.positionY, other.positionX - this.positionX);
                        var v1 = rotate(this.v, theta);
                        var v2 = rotate(other.v, theta);
                        var u1 = rotate([v1[0] * (m1 - m2) / (m1 + m2) + v2[0] * 2 * m2 / (m1 + m2), v1[1]], -theta);
                        var u2 = rotate([v2[0] * (m2 - m1) / (m1 + m2) + v1[0] * 2 * m1 / (m1 + m2), v2[1]], -theta);


                        this.directionX = u1[0];
                        this.directionY = u1[1];
                        this.facing = (this.directionX > 0 ? 1 : -1);
                        other.directionX = u2[0];
                        other.directionY = u2[1];
                        other.facing = (other.directionX > 0 ? 1 : -1);

                        if (this.hue !== null) {
                            if (other.hue === null) {
                                other.hue = this.hue;
                            } else if (this.hue !== other.hue) {
                                other.hue = this.hue = null;
                            }
                        } else {
                            if (other.hue !== null) {
                                this.hue = other.hue;
                            }
                        }

                        this.syncUI();
                        other.syncUI();
                    }
                }
                other = other.next;
            }
        }

        // Method to destroy a DVDoom instance.
        destroy() {
            // Remove the element.
            this.dettach();
            // Continue the removal.
            super.destroy();
        }
    }

    async function preloadImages() {
        const loadImageAsBase64 = async (url) => {
            const response = await fetch(url);
            const blob = await response.blob();
            return new Promise((resolve) => {
                resolve(window.URL.createObjectURL(blob));
            });
        };

        for (const [key, url] of Object.entries(imageURLMap)) {
            imageCache[key] = await loadImageAsBase64(url);
        }
    }
    // Ensure images are preloaded before continuing
    await preloadImages();

    // Mouse position tracking
    function debounce(func, wait) {
        let timeout;
        return function() {
            const context = this,
                args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(context, args), wait);
        };
    }

    const mousePos = {
        x: 0,
        y: 0
    };
    document.addEventListener('mousemove', (event) => {
        mousePos.x = event.clientX;
        mousePos.y = event.clientY;
    });

    function checkCollisions(seiaArray) {
        for (let i = 0; i < seiaArray.length; i++) {
            for (let j = i + 1; j < seiaArray.length; j++) {
                const seia1 = seiaArray[i];
                const seia2 = seiaArray[j];

                if (seia1.isHeld || seia2.isHeld || seia1.type === 'game' || seia2.type === 'game') {
                    continue;
                }

                const dx = seia2.positionX - seia1.positionX;
                const dy = seia2.positionY - seia1.positionY;
                const distanceSquared = dx * dx + dy * dy;
                const minDist = seia1.elementSize / 2 + seia2.elementSize / 2;
                const minDistSquared = minDist * minDist;

                if (distanceSquared < minDistSquared) {
                    const distance = Math.sqrt(distanceSquared); // Calculate sqrt only if there's a collision
                    const overlap = minDist - distance;
                    const nx = dx / distance;
                    const ny = dy / distance;

                    const separation = overlap / 10;
                    const sx = nx * separation;
                    const sy = ny * separation;

                    seia1.positionX -= sx / 2;
                    seia1.positionY -= sy / 2;
                    seia2.positionX += sx / 2;
                    seia2.positionY += sy / 2;

                    const v1 = {
                        x: seia1.directionX,
                        y: seia1.directionY
                    };
                    const v2 = {
                        x: seia2.directionX,
                        y: seia2.directionY
                    };

                    seia1.directionX = v2.x;
                    seia1.directionY = v2.y;
                    seia2.directionX = v1.x;
                    seia2.directionY = v1.y;

                    seia1.syncUI();
                    seia2.syncUI();
                }
            }
        }
    }

    /**
     * Rotates a point or velocity vector around the origin.
     * @param {number} x The x-coordinate of the point/vector to rotate.
     * @param {number} y The y-coordinate of the point/vector to rotate.
     * @param {number} sin The precomputed sine of the angle to rotate.
     * @param {number} cos The precomputed cosine of the angle to rotate.
     * @param {boolean} reverse If true, rotates counterclockwise; otherwise, clockwise.
     * @returns {{x: number, y: number}} The rotated point/vector.
     */

    // So, the funny thing is I declared this but never read it anywhere.
    // I'll leave it here in case you have another Seia idea that involes rotation!
    function rotation(x, y, sin, cos, reverse) {
        return {
            x: (reverse) ? (x * cos + y * sin) : (x * cos - y * sin),
            y: (reverse) ? (y * cos - x * sin) : (y * cos + x * sin)
        };
    }


    function rotate(v, theta) {
        return [v[0] * Math.cos(theta) - v[1] * Math.sin(theta), v[0] * Math.sin(theta) + v[1] * Math.cos(theta)];
    }


    // Use a function to set multiple styles at once to reduce layout thrashing
    const setStyles = (elem, styles) => {
        Object.assign(elem.style, styles);
    };


    ////////////////////////////////////////////////////
    /////////////////// SEIA CLASSES ///////////////////
    ////////////////////////////////////////////////////

    //////////////////// Base

    // Base class to be extended by every type of Seia.
    class DVDoom {
        constructor(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing, type) {
            // Base UI fields.
            this.elementSize = elementSize;
            this.positionX = positionX;
            this.positionY = positionY;
            this.hue = hue;
            this.background = background;
            this.facing = facing;
            // Movement fields.
            this.directionX = directionX;
            this.directionY = directionY;
            this.maxSpeed = speed;
            this.speed = speed;
            // Other fields.
            this.eos = false;

            this.type = type;
            this.collisionCooldown = 0;

            // Setup of the DVDoom's UI view.
            this.htmlElement = document.createElement('div');
            this.htmlElement.className = 'doomvdoom';
            let filterType = (hue === null) ? `grayscale(1)` : `hue-rotate(${hue}deg)`;
            setStyles(this.htmlElement, {
                transform: `scaleX(${facing})`,
                position: 'absolute',
                left: `${positionX}px`,
                top: `${positionY}px`,
                height: `${elementSize}px`,
                width: `${elementSize}px`,
                filter: filterType,
                background: `url("${background}")`,
                pointerEvents: 'none',
                backgroundSize: 'cover',
                maskMode: 'luminance'
            });
        }

        triggerCollisionCooldown(frames) {
            this.collisionCooldown = frames;
        }

        // Reflect changes in the DVDoom instance to the UI.
        syncUI() {
            if (this.collisionCooldown > 0) {
                this.collisionCooldown--; // Decrement cooldown timer
                return; // Skip movement if cooling down
            }
            this.htmlElement.style.left = `${this.positionX}px`;
            this.htmlElement.style.top = `${this.positionY}px`;
        }

        // Method to adjust a DVDoom instance per tick.
        adjust() {
            // Return true.
            return true;
        }

        // Method to destroy a DVDoom instance.
        destroy() {
            // Remove the element.
            this.htmlElement.remove();
            // Ensure the element was marked for deletion.
            this.eos = true;
        }

        // Factory method to create a DVDoom instance, implementation should be provided based on specific use case.
        static create() {
            return null;
        }

        // Method to handle same class collisions.
        static handleCollisions() {}
    }

    //////////////////// Mixins

    // Class containing all cursor reaction logic, by extending this class a Seia is able to interact with the cursor.
    class DVDoomCursorMixin extends DVDoom {

        constructor(...args) {
            // Ensure the upper class is properly set up.
            super(...args);

            // Mouse related variables.
            this.launchCooldown = 0;
            this.mouseCollisionCooldown = 0;
            this.isDragging = false;
            this.velocityX = 0;
            this.velocityY = 0;
            this.isHeld = false;

            // Create the listeners functions.
            this.boundMouseDown = this.handleMouseDown.bind(this);
            this.boundMouseMove = this.handleMouseMove.bind(this);
            this.boundMouseUp = this.handleMouseUp.bind(this);
            // Add all necessary listeners.
            this.htmlElement.addEventListener('mousedown', this.boundMouseDown);

            // Set the element style.
            setStyles(this.htmlElement, {
                pointerEvents: 'auto',
            });
        }

        handleMouseDown(event) {
            if (event.target === this.htmlElement) {
                this.isDragging = true;
                this.isHeld = true;
                this.directionX = 0;
                this.directionY = 0;
                this.dragStartX = event.clientX;
                this.dragStartY = event.clientY;
                document.addEventListener('mousemove', this.boundMouseMove);
                document.addEventListener('mouseup', this.boundMouseUp);
            }
        }

        handleMouseMove(event) {
            if (this.isDragging) {
                let deltaX = event.clientX - this.dragStartX;
                let deltaY = event.clientY - this.dragStartY;

                // Update position and velocities
                this.positionX += deltaX;
                this.positionY += deltaY;
                this.velocityX = deltaX;
                this.velocityY = deltaY;
                this.syncUI();

                // Reset drag start positions for next calculation
                this.dragStartX = event.clientX;
                this.dragStartY = event.clientY;
            }
        }

        handleMouseUp() {
            this.isDragging = false;
            this.isHeld = false;
            this.launchSeia(this.velocityX, this.velocityY);
            // Remove mouse event listeners when not dragging
            document.removeEventListener('mousemove', this.boundMouseMove);
            document.removeEventListener('mouseup', this.boundMouseUp);
        }

        // Might way to have it gradually lose speed at some point
        // But for now let's have fun with it
        launchSeia(deltaX, deltaY) {
            // Use a constant threshold for 'significant' drag
            const significantDragThreshold = 10;
            const dragNumber = Math.hypot(deltaX, deltaY);
            if (dragNumber < significantDragThreshold) {
                return; // Ignore insignificant drags
            }
            // Launch the seia by updating its direction
            this.directionX = deltaX / dragNumber;
            this.directionY = deltaY / dragNumber;
            this.speed = dragNumber / significantDragThreshold;
            // Set cooldowns to avoid immediate re-collision
            this.launchCooldown = 30;
            this.mouseCollisionCooldown = 60;
        }

        adjust() {
            // Call the superclass method, if it returns false, consider the adjustment concluded and return immediatly.
            if (!super.adjust()) return false;

            // Skip adjustments if the seia is held or cooldowns are active
            if (this.isHeld) return false;
            if (this.launchCooldown > 0 || this.mouseCollisionCooldown > 0) {
                this.launchCooldown--;
                this.mouseCollisionCooldown--;
            }

            if (this.mouseCollisionCooldown == 0 && this.type !== 'game') {
                const dx = mousePos.x - (this.positionX + this.elementSize / 2);
                const dy = (mousePos.y + window.scrollY) - (this.positionY + this.elementSize / 2);
                const distanceSquared = dx * dx + dy * dy;
                const collisionRadiusSquared = Math.max(100, (this.elementSize / 2) * (this.elementSize / 2)); // Compare with the square of the collision radius

                if (distanceSquared < collisionRadiusSquared) {
                    const collisionRadius = Math.sqrt(collisionRadiusSquared); // Calculate sqrt only if needed
                    this.directionX = -dx / collisionRadius;
                    this.directionY = -dy / collisionRadius;
                    this.mouseCollisionCooldown = 60; // Reset cooldown to prevent immediate re-collision
                    return false;
                }
            }

            if (this.speed > this.maxSpeed) {
                this.speed *= 0.99;
            }
            return true;
        }

        destroy() {
            // Remove all listeners.
            document.removeEventListener('mousedown', this.boundMouseDown);
            // Continue its deconstruction.
            super.destroy()
        }
    }

    // Class containing all cursor reaction logic, by extending this class a Seia is able to interact with the cursor.
    class DVDoomCursorDragMixin extends DVDoom {

        constructor(...args) {
            // Ensure the upper class is properly set up.
            super(...args);

            // Mouse related variables.
            this.isDragging = false;
            this.velocityX = 0;
            this.velocityY = 0;
            this.isHeld = false;

            // Create the listeners functions.
            this.boundMouseDown = this.handleMouseDown.bind(this);
            this.boundMouseMove = this.handleMouseMove.bind(this);
            this.boundMouseUp = this.handleMouseUp.bind(this);
            // Add all necessary listeners.
            this.htmlElement.addEventListener('mousedown', this.boundMouseDown);

            // Set the element style.
            setStyles(this.htmlElement, {
                pointerEvents: 'auto',
            });
        }

        handleMouseDown(event) {
            if (event.target === this.htmlElement) {
                this.isDragging = true;
                this.isHeld = true;
                this.directionX = 0;
                this.directionY = 0;
                this.dragStartX = event.clientX;
                this.dragStartY = event.clientY;
                event.preventDefault();
                document.addEventListener('mousemove', this.boundMouseMove);
                document.addEventListener('mouseup', this.boundMouseUp);
            }
        }

        handleMouseMove(event) {
            if (this.isDragging) {
                let deltaX = (
                    Math.min(Math.max(this.elementSize, event.clientX), (screenWidth - (this.elementSize))) -
                    Math.min(Math.max(this.elementSize, this.dragStartX), (screenWidth - (this.elementSize)))
                );
                let deltaY = (
                    Math.min(Math.max(this.elementSize, event.clientY + scrollY), (screenHeight - this.elementSize)) -
                    Math.min(Math.max(this.elementSize, this.dragStartY + scrollY), (screenHeight - this.elementSize))
                );

                // Update position and velocities
                this.positionX += deltaX;
                this.positionY += deltaY;
                this.velocityX = deltaX;
                this.velocityY = deltaY;
                this.speed += Math.hypot(deltaX, deltaY);
                this.speed *= 0.9;
                this.syncUI();

                // Reset drag start positions for next calculation
                this.dragStartX = event.clientX;
                this.dragStartY = event.clientY;
            }
        }

        handleMouseUp() {
            // Remove mouse event listeners when not dragging
            document.removeEventListener('mousemove', this.boundMouseMove);
            document.removeEventListener('mouseup', this.boundMouseUp);
            this.isDragging = false;
            this.isHeld = false;
            this.launchSeia(this.velocityX, this.velocityY);
            this.velocityX = 0;
            this.velocityY = 0;
        }

        // Might way to have it gradually lose speed at some point
        // But for now let's have fun with it
        launchSeia(deltaX, deltaY) {
            // Use a constant threshold for 'significant' drag
            const significantDragThreshold = 10;
            const dragNumber = Math.hypot(deltaX, deltaY);
            if (dragNumber < significantDragThreshold) {
                this.speed = 0;
                return; // Ignore insignificant drags
            }
            // Launch the seia by updating its direction
            this.directionX = deltaX / dragNumber;
            this.directionY = deltaY / dragNumber;
            this.facing = this.directionX > 0 ? 1 : -1;
            this.speed /= significantDragThreshold;
        }

        adjust() {
            // Call the superclass method, if it returns false, consider the adjustment concluded and return immediatly.
            if (!super.adjust()) return false;

            // Skip adjustments if the seia is held or cooldowns are active
            if (this.isHeld) return false;

            if (this.speed > this.maxSpeed) {
                this.speed *= 0.99;
            }
            return true;
        }

        destroy() {
            // Remove all listeners.
            document.removeEventListener('mousedown', this.boundMouseDown);
            // Continue its deconstruction.
            super.destroy()
        }
    }


    //////////////////// Seias

    // Seia => a more erratic version of the classic Seia that can bounce unpredictably with various sizes and speeds.
    class DVDoomRE extends DVDoom {

        adjust() {
            // Call the superclass method, if it returns false, consider the adjustment concluded and return immediatly.
            if (!super.adjust()) return false;

            // Use a helper function to handle the bounce logic
            this.handleBounce();

            // Directly update styles using the setStyles function
            setStyles(this.htmlElement, {
                left: `${this.positionX}px`,
                top: `${this.positionY}px`,
                filter: `hue-rotate(${this.hue}deg)`,
                transform: `scaleX(${this.facing})`
            });

            return true;
        }

        syncUI() {
            // Call the superclass method is called to update the UI.
            super.syncUI();
            // Update the direction.
            this.htmlElement.style["transform"] = `scaleX(${this.facing})`;
        }

        handleBounce() {
            if (((this.positionY + (this.elementSize * 1.3)) >= screenHeight) && this.directionY > 0) {
                this.directionY = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * -1;
                this.directionX = (2 - Math.abs(this.directionY)) * (this.directionX > 0 ? 1 : -1);
                this.hue = Math.floor(Math.random() * 360); // Randomly adjust the hue
            } else if ((this.positionY < 0) && this.directionY < 0) {
                this.directionY = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * 1;
                this.directionX = (2 - Math.abs(this.directionY)) * (this.directionX > 0 ? 1 : -1);
                this.hue = Math.floor(Math.random() * 360); // Randomly adjust the hue
            }

            if (((this.positionX + (this.elementSize * 1.3)) >= screenWidth) && this.directionX > 0) {
                this.directionX = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * -1;
                this.directionY = (2 - Math.abs(this.directionX)) * (this.directionY > 0 ? 1 : -1);
                this.hue = Math.floor(Math.random() * 360); // Randomly adjust the hue
                this.facing = -1; // Flip the scaleX value
            } else if ((this.positionX < 0) && this.directionX < 0) {
                this.directionX = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * 1;
                this.directionY = (2 - Math.abs(this.directionX)) * (this.directionY > 0 ? 1 : -1);
                this.hue = Math.floor(Math.random() * 360); // Randomly adjust the hue
                this.facing = 1; // Flip the scaleX value
            }

            this.positionX += this.directionX * this.speed;
            this.positionY += this.directionY * this.speed;
        }

        static create() {
            // Existing make method implementation
            // As in, I left it untouched because I was starting to spend a significant time trying to "make it better"
            let sizeMultiplier = ((Math.random() * 0.75) + 0.5);
            let elementSize = DEFAULT_SIZE * sizeMultiplier;
            let positionX = Math.floor(Math.random() * ((screenWidth * 0.99) - elementSize));
            let positionY = Math.floor(Math.random() * ((screenHeight * 0.99) - elementSize));
            let directionX = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * ((Math.random() >= 0.5) ? 1 : -1);
            let directionY = (2 - Math.abs(directionX)) * ((Math.random() >= 0.5) ? 1 : -1);
            let speed = DEFAULT_SPEED * (Math.random() + 0.5);
            let hue = Math.floor(Math.random() * 360);
            let facing = (directionX > 0 ? 1 : -1);
            if (Math.random() < 0.001) {
                let background = imageCache.shiny;
                return new DVDoomREShiny(elementSize, positionX, positionY, directionX, directionY, speed, 0, background, facing, sizeMultiplier);
            } else {
                let background = imageCache.default;
                return new DVDoomRE(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing);
            }
        }
    }

    // Shiny Seia => a very rare golden version of the normal Seia which emits a golden glow.
    class DVDoomREShiny extends DVDoom {
        constructor(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing, sizeMultiplier) {
            super(elementSize, positionX, positionY, directionX, directionY, speed, 60, background, facing);
            // Set styles using setStyles function for better performance (I hope)
            setStyles(this.htmlElement, {
                filter: `drop-shadow(0px 0px ${15 * sizeMultiplier}px #ffd000) contrast(130%) brightness(150%)`,
                backgroundImage: `url("${background}")`,
            });
        }

        adjust() {
            // Call the superclass method, if it returns false, consider the adjustment concluded and return immediatly.
            if (!super.adjust()) return false;
            // Any specific behavior for DVDoomREShiny can go here, if needed
            // Since super.adjust() already handles position updates and bounce logic,
            // we may not need to repeat that logic here unless there's something different
            // for shiny ones. I've left it untouched for this reason.
            if (((this.positionY + (this.elementSize * 1.3)) >= screenHeight) && this.directionY > 0) {
                this.directionY = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * -1;
                this.directionX = (2 - Math.abs(this.directionY)) * (this.directionX > 0 ? 1 : -1);
            } else if ((this.positionY < 0) && this.directionY < 0) {
                this.directionY = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * 1;
                this.directionX = (2 - Math.abs(this.directionY)) * (this.directionX > 0 ? 1 : -1);
            }

            if (((this.positionX + (this.elementSize * 1.3)) >= screenWidth) && this.directionX > 0) {
                this.directionX = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * -1;
                this.directionY = (2 - Math.abs(this.directionX)) * (this.directionY > 0 ? 1 : -1);
            } else if ((this.positionX < 0) && this.directionX < 0) {
                this.directionX = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * 1;
                this.directionY = (2 - Math.abs(this.directionX)) * (this.directionY > 0 ? 1 : -1);
            }
            this.positionX += this.directionX * this.speed;
            this.positionY += this.directionY * this.speed;
            return true;
        }

        syncUI() {
            // Call the superclass method is called to update the UI.
            super.syncUI();
            // Update the direction.
            this.htmlElement.style["transform"] = `scaleX(${this.facing})`;
        }
    }

    // Classic Seia => dvd like behavior of the initial version of the script.
    class DVDoomClassic extends DVDoom {
        adjust() {
            // Call the superclass method, if it returns false, consider the adjustment concluded and return immediatly.
            if (!super.adjust()) return false;

            if (
                (this.positionY + this.elementSize * 1.3 >= screenHeight && this.directionY > 0) ||
                (this.positionY <= 0 && this.directionY < 0)
            ) {
                this.directionY *= -1;
                this.hue = Math.floor(Math.random() * 360);
            }

            if (
                (this.positionX + this.elementSize * 1.3 >= screenWidth && this.directionX > 0) ||
                (this.positionX <= 0 && this.directionX < 0)
            ) {
                this.directionX *= -1;
                this.hue = Math.floor(Math.random() * 360);
            }
            // Move the element
            this.positionX += this.directionX * this.speed;
            this.positionY += this.directionY * this.speed;
            return true; // Continue animation
        }

        static create() {
            // This method has a logic error; it should instantiate DVDoomClassic, not DVDoomRE
            // I think. I think? Change it back to RE if that's intentional
            let elementSize = DEFAULT_SIZE;
            let positionX = Math.floor(Math.random() * (screenWidth - elementSize));
            let positionY = Math.floor(Math.random() * (screenHeight - elementSize));
            let directionX = (Math.random() >= 0.5) ? 1 : -1;
            let directionY = (Math.random() >= 0.5) ? 1 : -1;
            let speed = DEFAULT_SPEED;
            let hue = Math.floor(Math.random() * 360);
            let facing = 1;
            let background = imageCache.default;
            // Create a new instance of DVDoomClassic instead of DVDoomRE
            return new DVDoomClassic(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing);
        }
    }

    // Trailling Seia => a hue shifting seia that leaves behind a trail.
    class DVDoomTrailing extends DVDoomCursorDragMixin {
        constructor(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing) {
            super(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing);
            this.trail = [];
            this.maxTrailLength = 10;
            this.lastSpawn = 0;
        }

        syncUI() {
            // Call the superclass method is called to update the UI.
            super.syncUI();
            // Update the direction.
            this.htmlElement.style["transform"] = `scaleX(${this.facing})`;
            this.htmlElement.style["filter"] = `hue-rotate(${this.hue}deg)`;
        }

        adjust() {
            // Manage trail spawning
            if (this.lastSpawn > (10 / (this.speed / this.maxSpeed))) {
                this.spawnTrail();
                this.lastSpawn = 0;
            } else {
                this.lastSpawn++;
            }

            // Fade out trail elements over time
            this.fadeTrailElements();

            // Call the superclass method, if it returns false, consider the adjustment concluded and return immediatly.
            if (!super.adjust()) return false;

            // Bounce logic for edges
            this.bounceOnEdges();

            // Update position and visual appearance
            this.positionX += this.directionX * this.speed;
            this.positionY += this.directionY * this.speed;
            this.hue = ((this.hue + 1) % 360);
            return true;
        }

        spawnTrail() {
            let newTrailSeia = new DvDoomAuxStationary(
                this.elementSize,
                this.positionX,
                this.positionY,
                this.directionX,
                this.directionY,
                this.speed,
                this.hue,
                this.background,
                (this.directionX > 0 ? 1 : -1)
            );
            this.trail.push(newTrailSeia);
            seiaEnclosure.insertBefore(newTrailSeia.htmlElement, this.htmlElement);
        }

        fadeTrailElements() {
            for (let index = 0; index < this.trail.length; index++) {
                let currentTrailElement = this.trail[index].htmlElement;
                currentTrailElement.style.opacity = (index) / MAX_TRAIL_LENGTH;
            }
            if (this.trail.length > MAX_TRAIL_LENGTH) {
                this.trail[0].destroy();
                this.trail.splice(0, 1);
            }
        }

        bounceOnEdges() {
            if (((this.positionY + (this.elementSize * 1.3)) >= screenHeight) && this.directionY > 0) {
                this.bounce('y', -1);
            } else if ((this.positionY < 0) && this.directionY < 0) {
                this.bounce('y', 1);
            }

            if (((this.positionX + (this.elementSize * 1.3)) >= screenWidth) && this.directionX > 0) {
                this.bounce('x', -1);
            } else if ((this.positionX < 0) && this.directionX < 0) {
                this.bounce('x', 1);
            }
        }

        bounce(axis, direction) {
            if (axis === 'y') {
                this.directionY = ((Math.random() * 0.8) + 0.2) * direction;
                this.directionX = (1 - Math.abs(this.directionY)) * (this.directionX > 0 ? 1 : -1);
            } else {
                this.directionX = ((Math.random() * 0.8) + 0.2) * direction;
                this.directionY = (1 - Math.abs(this.directionX)) * (this.directionY > 0 ? 1 : -1);
                this.facing = (this.directionX > 0) ? 1 : -1;
            }
        }

        destroy() {
            // Empty out the trail.
            this.trail.forEach((seiaTrailElement) => seiaTrailElement.destroy());
            this.trail = [];
            // Continue its deconstruction.
            super.destroy();
        }

        static create() {
            let elementSize = DEFAULT_SIZE;
            let positionX = Math.floor(Math.random() * ((screenWidth * 0.99) - elementSize));
            let positionY = Math.floor(Math.random() * ((screenHeight * 0.99) - elementSize));
            let directionX = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * ((Math.random() >= 0.5) ? 1 : -1);
            let directionY = (2 - Math.abs(directionX)) * ((Math.random() >= 0.5) ? 1 : -1);
            let speed = DEFAULT_SPEED;
            let hue = Math.floor(Math.random() * 360);
            let facing = (directionX > 0 ? 1 : -1);
            let background = imageCache.default;
            return new DVDoomTrailing(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing);
        }
    }

    // Fractal Seia => a Seia that splits into two smaller Seias upon impact.
    class DVDoomFractal extends DVDoom {

        splitSeia(wallHit) {
            this.eos = true;
            let elementSize = Math.floor(this.elementSize * 0.75);

            if (elementSize < 12) {
                return;
            }

            const documentfragment = document.createDocumentFragment();
            let directionY1;
            let directionX1;
            let directionY2;
            let directionX2;

            if (wallHit) {
                directionX1 = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * (this.directionX > 0 ? -1 : 1);
                directionY1 = (2 - Math.abs(directionX1)) * ((Math.random() >= 0.5) ? 1 : -1);
                directionX2 = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * (this.directionX > 0 ? -1 : 1);
                directionY2 = (2 - Math.abs(directionX2)) * ((Math.random() >= 0.5) ? 1 : -1);
            } else {
                directionY1 = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * (this.directionY > 0 ? -1 : 1);
                directionX1 = (2 - Math.abs(directionY1)) * ((Math.random() >= 0.5) ? 1 : -1);
                directionY2 = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * (this.directionY > 0 ? -1 : 1);
                directionX2 = (2 - Math.abs(directionY2)) * ((Math.random() >= 0.5) ? 1 : -1);
            }

            let positionX1 = this.positionX + (directionX1 * this.speed);
            let positionY1 = this.positionY + (directionY1 * this.speed);
            let positionX2 = this.positionX + (directionX2 * this.speed);
            let positionY2 = this.positionY + (directionY2 * this.speed);

            let childSeia1 = new DVDoomFractal(
                elementSize,
                positionX1,
                positionY1,
                directionX1,
                directionY1,
                this.speed,
                Math.floor(Math.random() * 360),
                this.background,
                (directionX1 > 0 ? 1 : -1)
            );
            SEIA_TYPE_MAP.get(DVDoomFractal).push(childSeia1);
            documentfragment.appendChild(childSeia1.htmlElement);

            let childSeia2 = new DVDoomFractal(
                elementSize,
                positionX2,
                positionY2,
                directionX2,
                directionY2,
                this.speed,
                Math.floor(Math.random() * 360),
                this.background,
                (directionX2 > 0 ? 1 : -1)
            );
            SEIA_TYPE_MAP.get(DVDoomFractal).push(childSeia2);
            documentfragment.appendChild(childSeia2.htmlElement);

            seiaEnclosure.appendChild(documentfragment);
        }

        adjust() {
            if (((this.positionY + (this.elementSize * 1.3)) >= screenHeight) && this.directionY > 0) {
                this.splitSeia(false);
                return false;
            } else if ((this.positionY < 0) && this.directionY < 0) {
                this.splitSeia(false);
                return false;
            }

            if (((this.positionX + (this.elementSize * 1.3)) >= screenWidth) && this.directionX > 0) {
                this.splitSeia(true);
                return false;
            } else if ((this.positionX < 0) && this.directionX < 0) {
                this.splitSeia(true);
                return false;
            }
            this.positionX += this.directionX * this.speed;
            this.positionY += this.directionY * this.speed;
            return true;
        }

        static create() {
            let elementSize = DEFAULT_SIZE * 2.5;
            let positionX = Math.floor(Math.random() * ((screenWidth * 0.99) - elementSize));
            let positionY = Math.floor(Math.random() * ((screenHeight * 0.99) - elementSize));
            let directionX = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * ((Math.random() >= 0.5) ? 1 : -1);
            let directionY = (2 - Math.abs(directionX)) * ((Math.random() >= 0.5) ? 1 : -1);
            let speed = DEFAULT_SPEED;
            let hue = Math.floor(Math.random() * 360);
            let facing = (directionX > 0 ? 1 : -1);
            let background = imageCache.default;
            return new DVDoomFractal(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing, background);
        }
    }

    // Snake (Player) Seia => a Seia that can be controlled through the WASD keys, eats food-type point Seias to grow its tail. Dies on impact with walls or death-type point Seias.
    class DVDoomPlayer extends DVDoom {

        constructor(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing) {
            super(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing);
            this.trail = [];
            this.maxTrailSize = 0;
            this.lastSpawn = 0;
            this.type = 'game';
            this.customEventListener = (event) => {
                switch (event.key) {
                    case 'a':
                        if (this.directionX == 0) {
                            this.directionY = 0;
                            this.directionX = -1;
                            this.facing = -1;
                        }
                        break;
                    case 'd':
                        if (this.directionX == 0) {
                            this.directionY = 0;
                            this.directionX = 1;
                            this.facing = 1;
                        }
                        break;
                    case 'w':
                        if (this.directionY == 0) {
                            this.directionX = 0;
                            this.directionY = -1;
                        }
                        break;
                    case 's':
                        if (this.directionY == 0) {
                            this.directionX = 0;
                            this.directionY = 1;
                        }
                        break;
                    default:
                        break;
                }
            }
            window.addEventListener(
                "keydown",
                this.customEventListener,
                true,
            );
        }

        syncUI() {
            // Call the superclass method is called to update the UI.
            super.syncUI();
            // Update the direction.
            this.htmlElement.style["transform"] = `scaleX(${this.facing})`;
            this.htmlElement.style["-webkit-filter"] = `hue-rotate(${this.hue}deg)`;
        }

        adjust() {
            // Call the superclass method, if it returns false, consider the adjustment concluded and return immediatly.
            if (!super.adjust()) return false;

            for (let index = this.trail.length - 4; index > 0; index--) {
                let currentSeiaHunter = this.trail[index];
                if (
                    ((this.positionX + (this.elementSize * 0.15)) < (currentSeiaHunter.positionX + currentSeiaHunter.elementSize)) &&
                    ((this.positionX + (this.elementSize * 0.85)) > currentSeiaHunter.positionX) &&
                    ((this.positionY + (this.elementSize * 0.15)) < (currentSeiaHunter.positionY + currentSeiaHunter.elementSize)) &&
                    ((this.positionY + (this.elementSize * 0.85)) > (currentSeiaHunter.positionY))
                ) {
                    for (let index = this.trail.length - 1; index >= 0; index--) {
                        this.trail[index].destroy();
                        this.trail.splice(index, 1);
                    }
                    this.eos = true;
                    return false;
                }
            }
            if (
                (this.positionY + (this.elementSize * 1.3) >= screenHeight) ||
                (this.positionY < 0) ||
                (this.positionX + (this.elementSize * 1.3) >= screenWidth) ||
                (this.positionX < 0)
            ) {
                for (let index = this.trail.length - 1; index >= 0; index--) {
                    this.trail[index].destroy();
                    this.trail.splice(index, 1);
                }
                this.eos = true;
                return false;
            }
            if (this.lastSpawn > 18 && this.maxTrailSize > 0) {
                if (this.trail.length === this.maxTrailSize) {
                    this.trail[0].destroy();
                    this.trail.splice(0, 1);
                }
                let newTrailSeia = new DvDoomAuxStationary(
                    this.elementSize,
                    this.positionX,
                    this.positionY,
                    this.directionX,
                    this.directionY,
                    this.speed,
                    this.hue,
                    this.background,
                    (this.directionX > 0 ? 1 : -1)
                );
                this.trail.push(newTrailSeia);
                seiaEnclosure.insertBefore(newTrailSeia.htmlElement, this.htmlElement);
                this.lastSpawn = 0;
            }
            this.hue = ((this.hue + 1) % 360);
            this.lastSpawn += 1;
            this.positionX += this.directionX * this.speed;
            this.positionY += this.directionY * this.speed;
            this.htmlElement.style.left = this.positionX + "px";
            this.htmlElement.style.top = this.positionY + "px";
            return true;
        }


        destroy() {
            for (let index = this.trail.length - 1; index >= 0; index--) {
                let currentTrailElement = this.trail[index];
                currentTrailElement.destroy();
                this.trail.splice(index, 1);
            }
            window.removeEventListener('keydown', this.customEventListener);
            super.destroy();
        }

        static create() {
            let elementSize = DEFAULT_SIZE * 0.8;
            let positionX = Math.floor(((screenWidth * 0.5) - elementSize));
            let positionY = Math.floor(elementSize * 2);
            let directionX = 0;
            let directionY = 1;
            let speed = DEFAULT_SPEED * 1.5;
            let hue = Math.floor(Math.random() * 360);
            let facing = 1;
            let background = imageCache.shiny;
            return new DVDoomPlayer(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing, background);
        }
    }

    // Snake (Point) Seia => a Seia that can be of three types (none: changes to another type on impact; food: can be eaten by the player; death: will kill the player).
    class DVDoomPlayerPoint extends DVDoom {

        constructor(elementSize, positionX, positionY, directionX, directionY, speed, background, facing) {
            super(elementSize, positionX, positionY, directionX, directionY, speed, null, background, facing);
            this.pointMode = null;
            this.type = 'game';
        }

        syncUI() {
            // Call the superclass method is called to update the UI.
            super.syncUI();
            // Update the direction.
            this.htmlElement.style["transform"] = `scaleX(${this.facing})`;
            this.htmlElement.style["-webkit-filter"] = `hue-rotate(${this.hue}deg)`;
        }

        changeMode() {
            switch ((Math.random() * 3) << 0) {
                case 2:
                case 1:
                    this.hue = 60;
                    this.pointMode = true;
                    break;
                case 0:
                    this.hue = 300;
                    this.pointMode = false;
                    break;
                default:
                    this.hue = 0;
                    this.pointMode = null;
                    break;
            }
        }

        adjust() {
            // Call the superclass method, if it returns false, consider the adjustment concluded and return immediatly.
            if (!super.adjust()) return false;

            let seiaPlayers = SEIA_TYPE_MAP.get(DVDoomPlayer);

            if (this.pointMode != null) {
                for (let index = seiaPlayers.length - 1; index >= 0; index--) {
                    let currentSeiaHunter = seiaPlayers[index];
                    if (
                        ((this.positionX) < (currentSeiaHunter.positionX + currentSeiaHunter.elementSize)) &&
                        ((this.positionX + (this.elementSize)) > currentSeiaHunter.positionX) &&
                        ((this.positionY) < (currentSeiaHunter.positionY + currentSeiaHunter.elementSize)) &&
                        ((this.positionY + (this.elementSize)) > (currentSeiaHunter.positionY))
                    ) {

                        if (this.pointMode) {
                            currentSeiaHunter.maxTrailSize += 1;
                        } else {
                            currentSeiaHunter.eos = true;
                        }
                        this.eos = true;
                        return false;
                    }
                }
            }

            if (((this.positionY + (this.elementSize * 1.3)) >= screenHeight) && this.directionY > 0) {
                this.directionY = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * -1;
                this.directionX = (2 - Math.abs(this.directionY)) * (this.directionX > 0 ? 1 : -1);
                this.changeMode();
            } else if ((this.positionY < 0) && this.directionY < 0) {
                this.directionY = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * 1;
                this.directionX = (2 - Math.abs(this.directionY)) * (this.directionX > 0 ? 1 : -1);
                this.changeMode();
            }

            if (((this.positionX + (this.elementSize * 1.3)) >= screenWidth) && this.directionX > 0) {
                this.directionX = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * -1;
                this.directionY = (2 - Math.abs(this.directionX)) * (this.directionY > 0 ? 1 : -1);
                this.facing = -1;
                this.changeMode();
            } else if ((this.positionX < 0) && this.directionX < 0) {
                this.directionX = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * 1;
                this.directionY = (2 - Math.abs(this.directionX)) * (this.directionY > 0 ? 1 : -1);
                this.facing = 1;
                this.changeMode();
            }
            this.positionX += this.directionX * this.speed;
            this.positionY += this.directionY * this.speed;
            return true;
        }

        static create() {
            let sizeMultiplier = 0.5;
            let elementSize = DEFAULT_SIZE * sizeMultiplier;
            let positionX = Math.floor(Math.random() * ((screenWidth * 0.99) - elementSize));
            let positionY = Math.floor(Math.random() * ((screenHeight * 0.99) - elementSize));
            let directionX = ((Math.random() * 2 * 0.8) + (2 * 0.2)) * ((Math.random() >= 0.5) ? 1 : -1);
            let directionY = (2 - Math.abs(directionX)) * ((Math.random() >= 0.5) ? 1 : -1);
            let speed = DEFAULT_SPEED * (Math.random() * 0.5) + 0.5;
            let facing = (directionX > 0 ? 1 : -1);
            let background = imageCache.shiny;
            return new DVDoomPlayerPoint(elementSize, positionX, positionY, directionX, directionY, speed, background, facing, background);
        }
    }

    // Rain Seia => a Seia that falls from top to bottom, upon impact teleports back to the top.
    class DVDoomRain extends DVDoom {
        constructor(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing, opacity) {
            super(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing);
            this.opacity = opacity;
            setStyles(this.htmlElement, {
                width: `${(elementSize * 0.35)}px`,
                backgroundSize: '100% 100%',
                backgroundRepeat: 'no-repeat',
                maskMode: 'luminance',
                opacity: this.opacity
            });
        }

        adjust() {
            // Call the superclass method, if it returns false, consider the adjustment concluded and return immediatly.
            if (!super.adjust()) return false;
            // Check if it has reached the bottom.
            if (this.positionY + (this.elementSize * 1.3) >= screenHeight && this.directionY > 0) {
                this.directionY = Math.random() + 1;
                this.positionY = this.elementSize;
                this.htmlElement.style["-webkit-filter"] = 'hue-rotate(' + Math.floor(Math.random() * 360) + 'deg)';
                this.htmlElement.style.transform = 'scaleX(' + (Math.random() > 0.5 ? 1 : -1) + ')';
                this.speed = DEFAULT_SPEED * (Math.random() + 1);
            }
            this.positionY += this.directionY * this.speed;
            return true;
        }

        static create() {
            const sizeMultiplier = Math.random() * 0.5 + 0.5;
            const elementSize = DEFAULT_SIZE * sizeMultiplier;
            const positionX = Math.floor(Math.random() * (screenWidth - elementSize));
            const positionY = Math.floor(Math.random() * (screenHeight - elementSize));
            const directionY = Math.random() + 1;
            const speed = DEFAULT_SPEED * (Math.random() + 1);
            const hue = Math.floor(Math.random() * 360);
            const facing = Math.random() > 0.5 ? 1 : -1;
            const background = imageCache.shiny;
            const opacity = Math.random() * 0.4 + 0.3;
            return new DVDoomRain(elementSize, positionX, positionY, 0, directionY, speed, hue, background, facing, opacity);
        }
    }

    // Wife Seia => a Seia that moves towards the cursor.
    class DVDoomWife extends DVDoomCursorDragMixin {
        constructor(...args) {
            super(...args);
            this.chaseSpeed = this.speed;
            this.speed = 0;
            this.directionChaseX = this.directionX;
            this.directionChaseY = this.directionY;
            this.heightModifier = 100;
            this.currentCursorX = mousePos.x;
            this.currentCursorY = mousePos.y;
            this.currentClicks = 0;
            this.doomChildren = [];
            setStyles(this.htmlElement, {
                // filter: `drop-shadow(0px 0px ${5}px rgba(235, 52, 210, 0.4))`,
                backgroundSize: `100% ${this.heightModifier}%`,
                backgroundRepeat: 'no-repeat',
                backgroundPosition: 'bottom',
            });


            // Uselful for the "return" reaction.
            this.windowVisibilityChange = this.onVisibilityChanged.bind(this);
            this.leftPageDate = -1;
            var eventName;
            this.isVisible = true;
            if ((this.propName = "hidden") in document) eventName = "visibilitychange";
            else if ((this.propName = "msHidden") in document) eventName = "msvisibilitychange";
            else if ((this.propName = "mozHidden") in document) eventName = "mozvisibilitychange";
            else if ((this.propName = "webkitHidden") in document) eventName = "webkitvisibilitychange";
            if (eventName) document.addEventListener(eventName, this.windowVisibilityChange);
            if ("onfocusin" in document) document.onfocusin = document.onfocusout = this.windowVisibilityChange; //IE 9
            window.onpageshow = window.onpagehide = window.onfocus = window.onblur = this.windowVisibilityChange; // Changing tab with alt+tab
            if (document[this.propName] !== undefined) this.windowVisibilityChange({
                type: document[this.propName] ? "blur" : "focus"
            });

            // Setup of the Seia's text box.
            this.seiaText = '';
            this.textLifetime = 0;
            this.htmlElementText = document.createElement('a');
            this.htmlElementText.className = 'seia-text';
            this.htmlElementText.textContent = this.seiaText;
            setStyles(this.htmlElementText, {
                display: 'block',
                whiteSpace: 'pre-line',
                width: `${this.elementSize * 3}px`,
                height: `${this.elementSize * 0.5}px`,
                textAlign: "center",
                marginLeft: `${this.elementSize * -1}px`,
                marginTop: `${this.elementSize * -0.25}px`,
                pointerEvents: 'none'
            });
            this.htmlElement.append(this.htmlElementText);
        }

        onVisibilityChanged(event) {
            event = event || window.event;
            if (this.isVisible && (["blur", "focusout", "pagehide"].includes(event.type) || (document && document[this.propName]))) {
                this.isVisible = false;
                this.leftPageDate = performance.now();
            } else if (!this.isVisible && (["focus", "focusin", "pageshow"].includes(event.type) || (document && !document[this.propName]))) {
                this.isVisible = true;
                // Check if enough time has passed.
                if (this.leftPageDate >= 0 && (performance.now() > (this.leftPageDate + (5 * 60 * 1000)))) {
                    this.seiaText = 'you came back';
                    this.textLifetime = 200;
                }
                this.leftPageDate = -1;
            }
        }

        syncUI() {
            super.syncUI();
            setStyles(this.htmlElement, {
                transform: `scaleX(${this.facing})`,
                background: `url("${this.background}")`,
                backgroundSize: `100% ${this.heightModifier}%`,
                backgroundRepeat: 'no-repeat',
                backgroundPosition: 'bottom',
            });
            this.htmlElementText.textContent = this.seiaText;
            setStyles(this.htmlElementText, {
                transform: `scaleX(${this.facing})`,
                display: ((this.textLifetime > 0) ? 'block' : 'none')
            });
            this.doomChildren.forEach((doomChild) => doomChild.syncUI());
        }

        handleMouseDown(event) {
            super.handleMouseDown(event);
            this.heightModifier = 85;
            this.heartPat();
        }

        adjust() {

            if (this.heightModifier < 100) {
                this.heightModifier += 1;
            } else {
                this.currentClicks = 0;
                this.background = imageCache.defaultHearts;
            }

            if (this.textLifetime === 0) {
                this.seiaText = '';
            } else {
                this.textLifetime -= 1;
            }

            // Get the current date.
            const currentUTCDate = new Date();
            if (currentUTCDate.getUTCHours() == 19 && 0 == currentUTCDate.getUTCMinutes() == currentUTCDate.getUTCSeconds()) {
                this.seiaText = 'reset seia'
                this.textLifetime = 200;
            }

            // Adjust the child seias.
            for (let i = 0; i < this.doomChildren.length; i++) {
                const seia1 = this.doomChildren[i];
                for (let j = i + 1; j < this.doomChildren.length; j++) {
                    const seia2 = this.doomChildren[j];

                    if (seia1.isHeld || seia2.isHeld) {
                        continue;
                    }

                    const dx = (seia2.positionX + (seia2.elementSize / 2)) - (seia1.positionX + (seia1.elementSize / 2));
                    const dy = (seia2.positionY + (seia2.elementSize / 2)) - (seia1.positionY + (seia1.elementSize / 2));
                    const distanceSquared = dx * dx + dy * dy;
                    const minDist = (seia1.elementSize / 2 + seia2.elementSize / 2) * 1.5;
                    const minDistSquared = minDist * minDist;

                    if (distanceSquared < minDistSquared) {
                        const distance = Math.sqrt(distanceSquared); // Calculate sqrt only if there's a collision
                        const overlap = minDist - distance;
                        const nx = dx / distance;
                        const ny = dy / distance;

                        const separation = overlap / 10;
                        const sx = nx * separation;
                        const sy = ny * separation;

                        seia1.positionX -= sx / 2;
                        seia1.positionY -= sy / 2;
                        seia2.positionX += sx / 2;
                        seia2.positionY += sy / 2;

                        const v1 = {
                            x: seia1.directionX,
                            y: seia1.directionY
                        };
                        const v2 = {
                            x: seia2.directionX,
                            y: seia2.directionY
                        };

                        seia1.directionX = v2.x;
                        seia1.directionY = v2.y;
                        seia2.directionX = v1.x;
                        seia2.directionY = v1.y;
                    }
                }
                seia1.adjust();
            }

            // Call the superclass method, if it returns false, consider the adjustment concluded and return immediatly.
            if (!super.adjust()) return false;

            // Use a helper function to handle the bounce logic
            this.handleBounce();

            const dx = mousePos.x - (this.positionX + this.elementSize / 2);
            const dy = (mousePos.y + window.scrollY) - (this.positionY + this.elementSize / 2);
            const dxy = Math.hypot(dx, dy);

            if (dxy > (this.elementSize * 1.5)) {
                this.directionChaseX = dx / dxy;
                this.directionChaseY = dy / dxy;
                this.chaseSpeed = (dxy / (this.elementSize * 1.5));
                if (this.speed < (this.maxSpeed * 1.1)) {
                    this.speed = 0;
                    this.positionX += this.directionChaseX * this.chaseSpeed;
                    this.positionY += this.directionChaseY * this.chaseSpeed;
                    this.facing = (this.directionChaseX > 0 ? 1 : -1);
                    return false;
                }
            }

            if (this.speed > 0) {
                this.positionX += this.directionX * this.speed;
                this.positionY += this.directionY * this.speed;
                this.facing = (this.directionX > 0 ? 1 : -1);
            }

            return true;
        }

        heartPat() {
            this.currentClicks += 1;
            this.background = imageCache.blushHearts;

            if (this.currentClicks > 12) {
                // Reset the clicks.
                this.currentClicks = 0;
                this.createChild();
            }

            var c = document.createDocumentFragment();
            var cc = document.createElement("div");
            for (var i = 0; i < 3; i++) {
                var e = document.createElement("i");
                e.className = 'seia-heart';
                setStyles(e, {
                    width: '15px',
                    left: `${(this.facing > 0 ? (mousePos.x - this.positionX - 7.5) : -(mousePos.x - this.positionX - this.elementSize + 7.5))}px`,
                    top: `${(mousePos.y + window.scrollY) - this.positionY - 7.5}px`,
                    transform: `translate3d(${randomInt(-75, 125)}px, ${randomInt(-80, 80)}px, 0) rotate(${randomInt(-20, 20)}deg)`,
                    animation: `seia-heart-animation 1000ms ease-out forwards`,
                    opacity: 0,
                    position: `absolute`,
                    overflow: `visible`,
                    pointerEvents: 'none'
                })
                cc.appendChild(e);
            }
            // document.body.appendChild(c);
            c.append(cc);
            this.htmlElement.append(c);
            setTimeout(() => cc.remove(), 1100);
        }

        createChild() {
            let elementSize = DEFAULT_SIZE * 0.6;
            let directionX = (Math.random() >= 0.5) ? 1 : -1;
            let directionY = (Math.random() >= 0.5) ? 1 : -1;
            let speed = DEFAULT_SPEED * 0.75;
            let facing = 1;
            let background = imageCache.defaultHearts;
            const doomChild = new DVDoomWifeChild(this, elementSize, this.positionX, this.positionY, directionX, directionY, speed, 0, background, facing);
            // Add the doomchild.
            this.doomChildren.push(doomChild);
            seiaEnclosure.insertBefore(doomChild.htmlElement, this.htmlElement);
            // SEIA_TYPE_MAP.get(DVDoomWifeChild).push(doomChild);
        }

        handleBounce() {
            const nextPosY = this.positionY + (this.elementSize * 1.3);
            const nextPosX = this.positionX + (this.elementSize * 1.3);

            if ((nextPosY >= screenHeight && this.directionY > 0) || (this.positionY < 0 && this.directionY < 0)) {
                this.directionY *= -1;
            }

            if ((nextPosX >= screenWidth && this.directionX > 0) || (this.positionX < 0 && this.directionX < 0)) {
                this.directionX *= -1;
            }
        }

        destroy() {
            try {
                document.removeEventListener('visibilitychange', this.windowVisibilityChange);
            } catch {};
            this.doomChildren.forEach((doomChild) => doomChild.destroy());
            super.destroy();
        }

        static create() {
            let elementSize = DEFAULT_SIZE;
            let directionX = (Math.random() >= 0.5) ? 1 : -1;
            let directionY = (Math.random() >= 0.5) ? 1 : -1;
            let speed = DEFAULT_SPEED;
            let facing = 1;
            let background = imageCache.defaultHearts;
            return new DVDoomWife(elementSize, mousePos.x, mousePos.y, directionX, directionY, speed, 0, background, facing);
        }
    }

    // Wife Seia's (Child) => a Seia that moves towards the Seia (Wife).
    class DVDoomWifeChild extends DVDoomCursorDragMixin {
        constructor(parentSeia, ...args) {
            super(...args);
            this.parentSeia = parentSeia;
            this.chaseSpeed = 0;
            this.speed = this.speed * 2;
            this.directionChaseX = this.directionX;
            this.directionChaseY = this.directionY;
            this.heightModifier = 100;
            this.currentCursorX = mousePos.x;
            this.currentCursorY = mousePos.y;
            this.currentClicks = 0;
            setStyles(this.htmlElement, {
                backgroundSize: `100% ${this.heightModifier}%`,
                backgroundRepeat: 'no-repeat',
                backgroundPosition: 'bottom',
            });

        }

        syncUI() {
            super.syncUI();
            setStyles(this.htmlElement, {
                transform: `scaleX(${this.facing})`,
                background: `url("${this.background}")`,
                backgroundSize: `100% ${this.heightModifier}%`,
                backgroundRepeat: 'no-repeat',
                backgroundPosition: 'bottom',
            });
        }

        handleMouseDown(event) {
            super.handleMouseDown(event);
            this.heightModifier = 85;
            this.heartPat();
        }

        adjust() {

            if (this.heightModifier < 100) {
                this.heightModifier += 1;
            } else {
                this.currentClicks = 0;
                this.background = imageCache.defaultHearts;
            }

            // Call the superclass method, if it returns false, consider the adjustment concluded and return immediatly.
            if (!super.adjust()) return false;

            // Use a helper function to handle the bounce logic
            this.handleBounce();

            const dx = this.parentSeia.positionX + (this.parentSeia.elementSize / 2) - (this.positionX + this.elementSize / 2);
            const dy = this.parentSeia.positionY + (this.parentSeia.elementSize / 2) - (this.positionY + this.elementSize / 2);
            const dxy = Math.hypot(dx, dy);

            if (dxy > (this.elementSize * 3)) {
                this.directionChaseX = dx / dxy;
                this.directionChaseY = dy / dxy;
                this.chaseSpeed = (dxy / (this.elementSize * 1.5));
                if (this.speed < (this.maxSpeed * 1.1)) {
                    this.speed = 0;
                    this.positionX += this.directionChaseX * this.chaseSpeed;
                    this.positionY += this.directionChaseY * this.chaseSpeed;
                    this.facing = (this.directionChaseX > 0 ? 1 : -1);
                    return false;
                }
            }

            if (this.speed > 0) {
                this.positionX += this.directionX * this.speed;
                this.positionY += this.directionY * this.speed;
                this.facing = (this.directionX > 0 ? 1 : -1);
            }

            return true;
        }

        heartPat() {
            this.background = imageCache.blushHearts;
        }

        handleBounce() {
            const nextPosY = this.positionY + (this.elementSize * 1.3);
            const nextPosX = this.positionX + (this.elementSize * 1.3);

            if ((nextPosY >= screenHeight && this.directionY > 0) || (this.positionY < 0 && this.directionY < 0)) {
                this.directionY *= -1;
            }

            if ((nextPosX >= screenWidth && this.directionX > 0) || (this.positionX < 0 && this.directionX < 0)) {
                this.directionX *= -1;
            }
        }
    }

    // Seia (Canvas) => Colored or Uncolored Seias, when a seia with color clashes with a colorless, the colorless becomes colored, when opposite colors clash they both become colorless.
    class DVDoomCanvas extends CoordinatesListItem(DVDoom) {
        constructor(...args) {
            super(...args);
        }

        adjust() {
            // Call the superclass method, if it returns false, consider the adjustment concluded and return immediatly.
            if (!super.adjust()) return false;

            // Use a helper function to handle the bounce logic
            this.handleBounce();

            // Update the position in the coordinate array.
            this.updateCoordinatePosition();

            return true;
        }

        syncUI() {
            // Call the superclass method is called to update the UI.
            super.syncUI();
            // Directly update styles using the setStyles function.
            setStyles(this.htmlElement, {
                left: `${this.positionX}px`,
                top: `${this.positionY}px`,
                filter: (this.hue === null) ? `grayscale(1)` : `hue-rotate(${this.hue}deg)`,
                transform: `scaleX(${this.facing})`
            });
        }

        handleBounce() {
            if (
                (this.positionY + this.elementSize * 1.3 >= screenHeight && this.directionY > 0) ||
                (this.positionY <= 0 && this.directionY < 0)
            ) {
                this.directionY *= -1;
            }
            if (
                (this.positionX + this.elementSize * 1.3 >= screenWidth && this.directionX > 0) ||
                (this.positionX <= 0 && this.directionX < 0)
            ) {
                this.directionX *= -1;
                this.facing = (this.directionX > 0 ? 1 : -1);
            }

            this.positionX += this.directionX * this.speed;
            this.positionY += this.directionY * this.speed;
        }

        static handleCollisions() {
            for (let i = 0; i < SEIA_COORDINATE_MAP.length; i++) {
                // Obtain the current coordinate.
                let currentSeia = SEIA_COORDINATE_MAP[i];
                // Loop until no more seias can be found.
                while (currentSeia) {
                    currentSeia.collision(currentSeia.next);
                    currentSeia.collision(SEIA_COORDINATE_MAP[i + 1]);
                    currentSeia = currentSeia.next;
                }
            }
        }

        static create() {
            // Existing make method implementation
            // As in, I left it untouched because I was starting to spend a significant time trying to "make it better"
            let elementSize = DEFAULT_SIZE;
            let positionX = Math.floor(Math.random() * ((screenWidth * 0.99) - elementSize));
            let positionY = Math.floor(Math.random() * ((screenHeight * 0.99) - elementSize));
            let directionX = ((Math.random() * 4 * 0.8) + (2 * 0.2)) * ((Math.random() >= 0.5) ? 1 : -1);
            let directionY = (4 - Math.abs(directionX)) * ((Math.random() >= 0.5) ? 1 : -1);
            let speed = 1;
            let hue = Math.floor(Math.random() * 360);
            let facing = (directionX > 0 ? 1 : -1);
            let background = imageCache.shiny;
            if (Math.random() < 0.05) {
                return new DVDoomCanvas(elementSize, positionX, positionY, directionX, directionY, speed, hue, background, facing);
            } else {
                return new DVDoomCanvas(elementSize, positionX, positionY, directionX, directionY, speed, null, background, facing);
            }
        }
    }

    //////////////////// Other

    // Class used for static "ghost" Seia, mainly used for trails and the like.
    class DvDoomAuxStationary extends DVDoom {
        adjust() {}
    }

    ////////////////////////////////////////////////////
    ///////////////// SEIA MAIN LOGIC //////////////////
    ////////////////////////////////////////////////////

    // Changed how it works, and batch updated so it's less resource heavy
    function addNewSeia(seiaCountToAdd, seiaTypeString, clearPrevious) {
        const seiaType = SEIA_STRING_ENUM[seiaTypeString];
        const seiaTypeList = SEIA_TYPE_MAP.get(seiaType);

        // Clear existing Seias of the same type if specified
        if (clearPrevious) {
            seiaTypeList.forEach(seia => seia.destroy());
            seiaTypeList.length = 0; // Clear the array efficiently
        }

        const documentFragment = new DocumentFragment();
        for (let i = 0; i < seiaCountToAdd; i++) {
            let seia = seiaType.create(); // Create new Seia
            seiaTypeList.push(seia); // Add it to the type list
            documentFragment.appendChild(seia.htmlElement); // Append to the document fragment
        }
        seiaEnclosure.appendChild(documentFragment); // Batch DOM update
    }


    // Here we're going to call this at a lower frame rate so it reduces lag when anons want to have 1k+ Seias on screen
    // Is 60 low these days... I'm getting old
    let fpsInterval = 1000 / 60; // Adjust to 60 FPS
    let lastFrameTime = Date.now();

    function animateSEIAS() {
        window.requestAnimationFrame(animateSEIAS); // Recursively call the animation frame
        screenHeight = document.body.clientHeight;
        screenWidth = document.body.clientWidth;
        let now = Date.now();
        let elapsed = now - lastFrameTime;

        // Flatten the list of all seias just once per animation frame
        const allSeias = [];
        SEIA_TYPE_MAP.forEach(seias => allSeias.push(...seias));

        if (elapsed > fpsInterval) {
            lastFrameTime = now - (elapsed % fpsInterval);
            // Iterate over all Seia types and their lists
            SEIA_TYPE_MAP.forEach((seiaTypeList, seiaType) => {
                for (let i = seiaTypeList.length - 1; i >= 0; i--) {
                    const seia = seiaTypeList[i];
                    if (!seia.eos) {
                        seia.adjust();
                        if (!seia.eos) {
                            seia.syncUI();
                        } else {
                            seia.destroy(); // Clean up resources
                            seiaTypeList.splice(i, 1); // Remove from list
                        }
                    } else {
                        seia.destroy(); // Clean up resources
                        seiaTypeList.splice(i, 1); // Remove from list
                    }
                }
                // Handle collisions.
                seiaType.handleCollisions();
            });

            // Collision checks
            if (allSeias.length > 1) { // Only perform if there are Seias to check
                // checkCollisions(allSeias);
            }

            // Check End of Service flag
            // Let's call it tha- Nyo! It's EoS "End of Service"!
            // I had a FASTER way to do this and a lot more optimized but it messed it up to where it wouldn't work
            // WILL come back to this later
            if (EOS) {
                for (const [seiaType, seiaTypeList] of SEIA_TYPE_MAP) {
                    for (let index = seiaTypeList.length - 1; index >= 0; index--) {
                        let currentSeia = seiaTypeList[index];
                        currentSeia.destroy();
                        seiaTypeList.splice(index, 1);
                    }
                }
                EOS = false;
            }
        }
    }

    const SEIA_TYPES = [
        DVDoomRE,
        DVDoomClassic,
        DVDoomFractal,
        DVDoomTrailing,
        DVDoomRain,
        DVDoomPlayer,
        DVDoomPlayerPoint,
        DVDoomCanvas,
        DVDoomWife,
    ];

    SEIA_TYPES.forEach(seiaType => {
        SEIA_TYPE_MAP.set(seiaType, []); // Initialize the map with an empty array for each type
        SEIA_STRING_ENUM[seiaType.name] = seiaType; // Map the class name to the class constructor
    });

    window.addNewSeia = addNewSeia;
    window.forceEoS = () => {
        EOS = true;
    };

    //////////////////////////////////////////////////
    // DVD Seia Menu UI
    //

    // Class containing the seia table menu UI logic.
    class SeiaMenuUI {
        static INPUTS = {
            "single": [1],
            "small": [1, 2, 3, 4, 5],
            "medium": [1, 2, 3, 4, 5, 10, 25, 50],
            "large": [1, 2, 3, 4, 5, 10, 25, 50, 75, 100, 150, 200, 300, 400, 500, 1000],
        }

        constructor(name, color, possibleValues, defaultValueIndex) {
            this.steps = possibleValues;
            this.startIndex = defaultValueIndex;
            this.value = this.steps[this.startIndex];
            this.color = color;
            this.name = name;

            this.body = document.createElement("div");
            this.body.className = 'menu-item';

            // Set background color dynamically
            this.body.style.backgroundColor = colorToRGBA(color);

            const header = document.createElement("div");
            header.className = 'menu-item-header';
            header.textContent = this.name;
            header.style.color = color;

            const content = document.createElement("div");
            content.className = 'menu-item-content';

            this.body.appendChild(header);
            this.body.appendChild(content);
            this.contentDiv = content;
        }

        createInput() {
            const parentDiv = document.createElement("div");
            parentDiv.className = 'quantity';

            const input = document.createElement('input');
            input.className = 'quantity__input';
            input.name = 'quantity';
            input.type = 'number';
            input.addEventListener('input', (function() {
                this.value = input.value;
            }).bind(this));
            let currentIndex = 0;
            input.value = this.value;

            const orderedSteps = this.steps;
            const reversedSteps = [...this.steps].reverse();

            const incrementButton = (function(e) {
                e.preventDefault();
                var currentValue = input.value;
                if (currentValue < orderedSteps[0]) {
                    currentIndex = 0;
                } else if (currentValue !== orderedSteps[currentIndex]) {
                    var index = orderedSteps.findIndex(function(number) {
                        return number > currentValue;
                    });
                    currentIndex = (index > 0) ? index : orderedSteps.length - 1;
                } else if (currentIndex < orderedSteps.length) {
                    currentIndex++;
                } else {
                    currentIndex = orderedSteps.length - 1;
                }
                input.value = orderedSteps[currentIndex];
                this.value = input.value;
            }).bind(this);

            const decrementButton = (function(e) {
                e.preventDefault();
                var currentValue = parseInt(input.value, 10);
                if (currentValue > orderedSteps[orderedSteps.length - 1]) {
                    currentIndex = orderedSteps.length - 1;
                } else if (currentValue !== orderedSteps[currentIndex]) {
                    var index = reversedSteps.findIndex(function(number) {
                        return number < currentValue;
                    });
                    currentIndex = (index > 0) ? (orderedSteps.length - index - 1) : 0;
                } else if (currentIndex > 0) {
                    currentIndex -= 1;
                } else {
                    currentIndex = 0;
                }
                input.value = orderedSteps[currentIndex];
                this.value = input.value;
            }).bind(this);

            const buttonMinus = document.createElement('a');
            buttonMinus.className = 'quantity__minus';
            buttonMinus.onclick = decrementButton;
            buttonMinus.innerHTML = '<span>-</span>';

            const buttonPlus = document.createElement('a');
            buttonPlus.className = 'quantity__plus';
            buttonPlus.onclick = incrementButton;
            buttonPlus.innerHTML = '<span>+</span>';

            parentDiv.appendChild(buttonMinus);
            parentDiv.appendChild(input);
            parentDiv.appendChild(buttonPlus);

            this.contentDiv.appendChild(parentDiv);
            return this;
        }

        createButton(buttonText, buttonTitle, buttonAction) {
            const buttonElement = document.createElement("button");
            buttonElement.textContent = buttonText;
            buttonElement.onclick = () => buttonAction(this.value);
            buttonElement.className = 'dvdoom-button';
            buttonElement.title = buttonTitle;
            buttonElement.style.color = this.color;

            this.contentDiv.appendChild(buttonElement);
            return this;
        }

        make() {
            return this.body;
        }

    }

    // List of seia cells in the table.
    const seiaGridMap = [
        [
            new SeiaMenuUI('Seia', 'red', SeiaMenuUI.INPUTS.large, 9).createInput().createButton('Spawn', 'Add Seia', (n) => addNewSeia(n, 'DVDoomRE')).make(),
            new SeiaMenuUI('Seia (Classic)', 'limegreen', SeiaMenuUI.INPUTS.large, 9).createInput().createButton('Spawn', 'Add Classic Seia', (n) => addNewSeia(n, 'DVDoomClassic')).make(),
            new SeiaMenuUI('Seia (Fractal)', 'blue', SeiaMenuUI.INPUTS.small, 0).createInput().createButton('Spawn', 'Add Fractal Seia', (n) => addNewSeia(n, 'DVDoomFractal')).make(),
            new SeiaMenuUI('Seia (Trailing)', 'sandybrown', SeiaMenuUI.INPUTS.medium, 2).createInput().createButton('Spawn', 'Add Trailing Seia', (n) => addNewSeia(n, 'DVDoomTrailing')).make(),
        ],
        [
            new SeiaMenuUI('Seia (Rain)', 'cornflowerblue', SeiaMenuUI.INPUTS.large, 9).createInput().createButton('Spawn', 'Add Rain Seia', (n) => addNewSeia(n, 'DVDoomRain')).make(),
            new SeiaMenuUI('Seia (Game)', 'indigo', SeiaMenuUI.INPUTS.large, 9).createInput().createButton('Spawn', 'Add game point Seia', (n) => addNewSeia(n, 'DVDoomPlayerPoint')).createButton('Start', 'Add game player Seia', (n) => addNewSeia(1, 'DVDoomPlayer', true)).make(),
            new SeiaMenuUI('Seia (Canvas)', 'darkturquoise', SeiaMenuUI.INPUTS.large, 9).createInput().createButton('Spawn', 'Add canvas Seia', (n) => addNewSeia(n, 'DVDoomCanvas')).make(),
            new SeiaMenuUI('Seia (Wife)', 'deeppink', SeiaMenuUI.INPUTS.single, 0).createButton('Spawn', 'Span a wife Seia', (n) => addNewSeia(n, 'DVDoomWife', true)).make(),
        ]
    ];


    /*

    // Modify the table creation part
    const tableElement = document.getElementById("seia-table");
    const tableDocumentFragment = document.createDocumentFragment();
    seiaGridMap.forEach((rowUI) => {
        const rowElement = document.createElement('tr');
        rowElement.className = 'dvdoom-row';
        rowUI.forEach((cellUI) => {
            rowElement.appendChild(cellUI);
        });
        tableDocumentFragment.append(rowElement);
    });
    tableElement.appendChild(tableDocumentFragment);

    // Modify the EoS button addition
    tableElement.insertAdjacentHTML('beforeend', `
    <tr>
        <td colspan="4" class="dvdoom-footer" style="padding: 0;">
            <button class="dvdoom-button dvdoom-eos-button" title="End of Session, remove all Seias" onclick="forceEoS()">EoS</button>
        </td>
    </tr>`);

    */

    // Add this function after drawer creation
    function handleDrawerScroll(event) {
        const drawerContent = drawer.querySelector('.drawer-content');
        const scrollTop = drawerContent.scrollTop;
        const scrollHeight = drawerContent.scrollHeight;
        const clientHeight = drawerContent.clientHeight;

        // Check if we're at the top or bottom of the scroll
        const isAtTop = scrollTop === 0;
        const isAtBottom = Math.abs(scrollTop + clientHeight - scrollHeight) < 1;

        // If we're at the boundaries and trying to scroll further, prevent it
        if ((isAtTop && event.deltaY < 0) || (isAtBottom && event.deltaY > 0)) {
            event.preventDefault();
            event.stopPropagation();
        }
    }


    // Modify how the menu items are added
    const drawerContent = drawer.querySelector('.drawer-content');
    seiaGridMap.flat().forEach(menuItem => {
        drawerContent.appendChild(menuItem);
    });
    drawerContent.addEventListener('wheel', handleDrawerScroll, {
        passive: false
    });


    // Handle touch events for mobile
    let touchStartY = 0;
    drawerContent.addEventListener('touchstart', (e) => {
        touchStartY = e.touches[0].pageY;
    }, {
        passive: true
    });

    drawerContent.addEventListener('touchmove', (e) => {
        const touchY = e.touches[0].pageY;
        const scrollTop = drawerContent.scrollTop;
        const scrollHeight = drawerContent.scrollHeight;
        const clientHeight = drawerContent.clientHeight;

        const isAtTop = scrollTop === 0;
        const isAtBottom = Math.abs(scrollTop + clientHeight - scrollHeight) < 1;

        // Prevent scrolling parent when at scroll boundaries
        if ((isAtTop && touchY > touchStartY) || (isAtBottom && touchY < touchStartY)) {
            e.preventDefault();
        }
    }, {
        passive: false
    });

    // Clean up event listeners when script is unloaded
    window.addEventListener('unload', () => {
        drawerContent.removeEventListener('wheel', handleDrawerScroll);
        observers.forEach(observer => observer.disconnect());
    });

    animateSEIAS();
})();

//////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////// FEED SECTION ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
await (async function() {
    const countdownTimers = {};

    // Add styles for feed table with correct borders
    const feedStyles = `
    .feed-table {
        border-collapse: separate;
        border-spacing: 0;
        border: 1px solid #ccc;
        border-radius: 5px;
        overflow: hidden;
    }
    .feed-table th, .feed-table td {
        border-right: 1px solid #ccc;
        border-bottom: 1px solid #ccc;
    }
    .feed-table th:last-child, .feed-table td:last-child {
        border-right: none;
    }
    .feed-table tr:last-child th, .feed-table tr:last-child td {
        border-bottom: none;
    }
    .feed-table tr:first-child th:first-child {
        border-top-left-radius: 5px;
    }
    .feed-table tr:first-child th:last-child {
        border-top-right-radius: 5px;
    }
    .feed-table tr:last-child td:first-child {
        border-bottom-left-radius: 5px;
    }
    .feed-table tr:last-child td:last-child {
        border-bottom-right-radius: 5px;
    }
`;

    // Add the styles to the document
    const styleElement = document.createElement('style');
    styleElement.textContent = feedStyles;
    document.head.appendChild(styleElement);

    function updateCountdown(feedElementId, countDownDate) {
        return function() {
            const now = new Date().getTime();
            const distance = countDownDate - now;

            if (distance < 0) {
                clearInterval(countdownTimers[feedElementId]);
                document.getElementById(feedElementId).innerHTML = "";
                delete countdownTimers[feedElementId];
            } else {
                const days = Math.floor(distance / (1000 * 60 * 60 * 24));
                const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                const seconds = Math.floor((distance % (1000 * 60)) / 1000);

                let displayString = "";
                if (days > 0) {
                    displayString = `${days}d ${hours}h ${minutes}m ${seconds}s`;
                } else if (hours > 0) {
                    displayString = `${hours}h ${minutes}m ${seconds}s`;
                } else if (minutes > 0) {
                    displayString = `${minutes}m ${seconds}s`;
                } else if (seconds > 0) {
                    displayString = `${seconds}s`;
                }

                document.getElementById(feedElementId).innerHTML = displayString;
            }
        };
    }

    async function fetchFeed() {
        const response = await fetch('https://rentry.org/DVDoomFEED/raw');
        const data = await response.json();
        let feedString = "";
        data.forEach((feedItem) => {
            if (feedItem["approved"]) {
                const feedElementId = feedItem["id"];
                feedString += `
                    <td style="font-weight: bold; text-align: center; vertical-align: top;">
                        <div style="position: relative; text-align: justify;">
                            <center style="white-space: pre; padding-top: 5px; padding-left: 5px; padding-right: 5px;">${feedItem['text']}</center>
                            <hr style="margin-left: 20px; margin-right: 20px;">
                            <center class="image-container" data-images="${feedItem['icon']}" style="width:240px; height:65px; padding-bottom: 2px;">
                                <a href="${feedItem['url']}" target="_blank">
                                    <img src="${feedItem['icon']}" alt="${feedItem['text']}" style="width:216px; height:65px; padding-left: 10px; padding-right: 10px;">
                                </a>
                            </center>
                            <center style="white-space: pre; padding-left: 5px; padding-right: 5px; padding-bottom: 2px; padding-top: 2px;">${feedItem['description']}</center>
                            <center id="${feedElementId}" style="white-space: pre; padding-left: 5px; padding-right: 5px; padding-bottom: 2px; padding-top: 2px;"></center>
                        </div>
                    </td>
            `;

                if (feedItem["countdown"]) {
                    const countDownDate = new Date(feedItem["countdown"]).getTime();
                    countdownTimers[feedElementId] = setInterval(updateCountdown(feedElementId, countDownDate), 1000);
                }
            }
        });

        // Check if DVDoomParent exists, if not, create it
        let dvDoomParent = document.getElementById("DVDoomParent");
        if (!dvDoomParent) {
            dvDoomParent = document.createElement('div');
            dvDoomParent.id = "DVDoomParent";
            dvDoomParent.style.display = 'flex';
            dvDoomParent.style.marginLeft = '3.5px';
            dvDoomParent.style.marginRight = '12.5px';
            dvDoomParent.style.justifyContent = 'space-between';

            // Find an appropriate place to insert DVDoomParent
            let targetElement = document.querySelector('.navLinks.desktop');
            if (targetElement) {
                targetElement.parentNode.insertBefore(dvDoomParent, targetElement);
            } else {
                document.body.appendChild(dvDoomParent);
            }
        }

        // Create and append the feed container
        let feedContainer = document.createElement('div');
        feedContainer.style.flexGrow = '5';
        feedContainer.style.flexBasis = '0';
        feedContainer.style.display = 'flex';
        feedContainer.style.flexDirection = 'column';
        feedContainer.style.alignItems = 'flex-end';
        feedContainer.style.justifyContent = 'center';


        if (feedString !== "") {
            feedContainer.innerHTML = `
            <table id="seia-feed" class="feed-table" style="margin-left: 0px; margin-right: 0px;">
                <caption>
                    <tr>
                        <th colspan="4" style="padding: 8px; text-align: center;">
                            \<<span style="font-weight: bold;"> /bag/ Feed </span>\>
                        </th>
                    </tr>
                </caption>
                <tr>
                    ${feedString}
                </tr>
            </table>
        `;
            feedContainer.hidden = false;
        }

        dvDoomParent.appendChild(feedContainer);
    }

    // Initialize the feed functionality
    fetchFeed();
})();

//////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////// GUIDE SECTION ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
await (async function() {
    async function fetchUsefulLinks() {
        // Create the useful links container
        let usefulLinksContainer = document.createElement('div');
        usefulLinksContainer.style.flexGrow = '1';
        usefulLinksContainer.style.flexBasis = '0';
        usefulLinksContainer.id = "seia-useful-links";

        // Find DVDoomParent
        let dvDoomParent = document.getElementById("DVDoomParent");
        if (!dvDoomParent) {
            // If DVDoomParent doesn't exist, we'll insert after .navLinks.desktop
            let targetElement = document.querySelector('.navLinks.desktop');
            if (targetElement) {
                dvDoomParent = document.createElement('div');
                dvDoomParent.id = "DVDoomParent";
                targetElement.parentNode.insertBefore(dvDoomParent, targetElement.nextSibling);
            } else {
                // If .navLinks.desktop doesn't exist, we'll append to body
                dvDoomParent = document.createElement('div');
                dvDoomParent.id = "DVDoomParent";
                document.body.appendChild(dvDoomParent);
            }
        }

        // Insert the useful links container after DVDoomParent
        dvDoomParent.insertAdjacentElement('afterend', usefulLinksContainer);

        // Add a horizontal rule after DVDoomParent
        dvDoomParent.insertAdjacentElement('afterend', document.createElement('hr'));
        usefulLinksContainer.insertAdjacentElement('afterend', document.createElement('hr'));

        const response = await fetch('https://rentry.org/DVDoomMISC/raw');
        const data = await response.json();
        let usefulStuffLeft = "";
        let usefulStuffRight = "";

        data.forEach((feedItem) => {
            if (feedItem["enabled"]) {
                // The string to add.
                const stringToAdd = `
                <div style="text-align: center; max-width: 300px;">
                    <a href="${feedItem['url']}" target="_blank">
                        <img src="${feedItem['icon']}" style="max-height: 60px; width: auto; display: block; margin: 0 auto;">
                    </a>
                </div>
            `;
                if (feedItem["side"] === "left") {
                    // Set the string.
                    usefulStuffLeft += stringToAdd;
                } else if (feedItem["side"] === "right") {
                    // Set the string.
                    usefulStuffRight += stringToAdd;
                }
            }
        });

        if (usefulStuffLeft === "" && usefulStuffRight === "") {
            usefulLinksContainer.hidden = true;
        } else {
            usefulLinksContainer.innerHTML = `
            <div style="display: flex; flex-wrap: wrap; padding-left: 10px; padding-right: 10px; justify-content: space-between; gap: 20px;">
                <div style="display: flex; gap: 20px;">
                    ${usefulStuffLeft}
                </div>
                <div style="display: flex; gap: 20px;">
                    ${usefulStuffRight}
                </div>
            </div>
        `;
            usefulLinksContainer.hidden = false;
        }
    }

    // Initialize the useful links functionality
    fetchUsefulLinks();
})();

//////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////// TWITTER SECTION ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
await (async function() {
    function functionHideMenu(currentElement) {
        window.removeEventListener('click', clickToHideDisplayMenu);
        document.removeEventListener("keydown", keyToHideDisplayMenu);
        currentElement.previousSibling.className = 'menu-button';
        currentElement.remove();
    }

    function clickToHideDisplayMenu(e) {
        const currentElement = document.getElementById('twitter-menu');
        if (!currentElement.contains(e.target)) {
            functionHideMenu(currentElement);
        }
    }

    function keyToHideDisplayMenu(e) {
        if (e.key === 'Escape') {
            const currentElement = document.getElementById('twitter-menu');
            functionHideMenu(currentElement);
        }
    }

    function functionDisplayMenu(e, twitterArrowContainer, tweetUser, tweetId) {
        // Get the positions.
        const boundingBox = twitterArrowContainer.getBoundingClientRect();
        const fragment = document.createDocumentFragment();
        const twitterMenu = document.createElement('div');
        twitterMenu.className = 'dialog';
        twitterMenu.id = 'twitter-menu';
        twitterMenu.tabindex = 0;
        twitterMenu.dataType = "get";

        let nitterURL, sotweURL;
        if (tweetId === '') {
            nitterURL = `https://nitter.poast.org/${tweetUser}`;
            sotweURL = `https://sotwe.com/${tweetUser}`;
        } else {
            nitterURL = `https://nitter.poast.org/${tweetUser}/status/${tweetId}`;
            sotweURL = `https://sotwe.com/tweet/${tweetId}`;
        }

        twitterMenu.innerHTML = `
        <a class="copy-text-link entry" href="${nitterURL}" target="_blank" style="order: 10;">Nitter</a>
        <a class="copy-text-link entry" href="${sotweURL}" target="_blank" style="order: 20;">Sotwe</a>
    `;
        window.addEventListener('click', clickToHideDisplayMenu);
        document.addEventListener("keydown", keyToHideDisplayMenu);
        Object.assign(twitterMenu.style, {
            zIndex: 2,
            position: 'absolute',
            top: `${boundingBox.bottom + window.scrollY}px`,
            left: `${boundingBox.left + window.scrollX}px`,
        });
        fragment.appendChild(twitterMenu);
        twitterArrowContainer.parentNode.insertBefore(fragment, twitterArrowContainer.nextElementSibling);
    }

    window.getAlternativeURLs = (twitterArrowContainer, e, tweetUser, tweetId) => {
        const currentActiveElement = document.getElementById('twitter-menu');
        if (currentActiveElement) {
            if (twitterArrowContainer.className == 'menu-button') {
                functionHideMenu(currentActiveElement);
                twitterArrowContainer.className = 'menu-button active';
                functionDisplayMenu(e, twitterArrowContainer, tweetUser, tweetId);
            } else {
                functionHideMenu(currentActiveElement);
            }
        } else {
            twitterArrowContainer.className = 'menu-button active';
            functionDisplayMenu(e, twitterArrowContainer, tweetUser, tweetId);
        }
        e.stopPropagation();
    };

    function addTwitterOptions(linkifiedTwitter) {
        linkifiedTwitter.classList.add("seia-checked");
        const fragment = document.createDocumentFragment();
        const twitterArrowContainer = document.createElement('a');
        twitterArrowContainer.className = 'menu-button';
        Object.assign(twitterArrowContainer.style, {
            'width': '18px',
            'textAlign': 'center'
        });
        const twitterArrowIcon = document.createElement('i');
        twitterArrowIcon.className = 'fa fa-angle-down';
        twitterArrowContainer.appendChild(twitterArrowIcon);

        // Obtain the host.
        const host = linkifiedTwitter.text.replace('https://', '').replace('www.', '').split('.com')[0].toLowerCase();

        let prefixElement;
        if (host == 'x' || host == 'fixupx' || host == 'twitter') {
            prefixElement = linkifiedTwitter.nextElementSibling;
            if (prefixElement !== null && prefixElement.className === 'embedder') {
                prefixElement = prefixElement.nextElementSibling;
            }
        } else {
            return;
        }

        const tweetId = (linkifiedTwitter.text.includes('/status/')) ? linkifiedTwitter.text.split('/status/').pop() : '';
        const tweetUser = linkifiedTwitter.text.split('.com/').pop().split('/')[0];
        fragment.appendChild(twitterArrowContainer);
        twitterArrowContainer.setAttribute('onclick', `getAlternativeURLs(this, event, '${tweetUser}', '${tweetId}')`);
        linkifiedTwitter.parentNode.insertBefore(fragment, prefixElement);
    }

    // The live collection to listen.
    const linkifyListener = document.getElementsByClassName("linkify");
    // Every 5 seconds add twitter options to the links.
    setInterval(() => {
        // Obtain the linkified twitter.
        [...linkifyListener].forEach((element) => {
            // Check if element does not have the right class.
            if (!element.classList.contains('seia-checked')) addTwitterOptions(element);
        });
    }, 5000);

})();

//////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////// SERVER SECTION ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
await (async function() {
    // Mimori was here
    const toggleStyles = `
    .server-toggle {
        position: relative;
        display: flex;
        flex-direction: column;
        width: 30px;
        padding: 1px;
        margin-top: 10px;
        margin-bottom: 10px;
    }
    .server-toggle button {
        border-collapse: separate;
        border-spacing 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
        color: inherit;
        background-color: transparent;
        cursor: pointer;
        transition: all 0.3s ease;
        padding: 10px 0;
        margin: 2.5px;
        width: 100%;
        writing-mode: vertical-rl;
        transform: rotate(180deg);
        text-align: center;
        opacity: 0.35;
    }
    .server-toggle button.selected {
        font-weight: 550;
        opacity: 1;
    }
    .server-toggle button:hover {
        background-color: rgba(0, 0, 0, 0.05);
    }
    .lang-toggle button {
        padding: 10px;
        margin-left: 10px; /* Add space between server and language toggles */
    }

    .server-toggle-tooltip-button {
        border-radius: 15px !important;
        opacity: 0.75 !important;
    }

    .server-toggle-tooltip {
        position: absolute;
        background-color: #333;
        color: white;
        padding: 10px;
        border-radius: 4px;
        display: none;
        left: 100%;
        top: 50%;
        transform: translateY(-100%);
        margin-left: 5px;
        white-space: nowrap;
        z-index: 1000;
    }

    .server-toggle-tooltip::after {
        content: '';
        position: absolute;
        top: 50%;
        right: 100%;
        margin-top: -5px;
        border-width: 5px;
        border-style: solid;
        border-color: transparent #333 transparent transparent;
    }

    .server-toggle-tooltip-button:hover {
        background-color: transparent!important;
    }

    .server-toggle-tooltip-button:hover + .server-toggle-tooltip,
    .server-toggle-tooltip:hover {
        display: block;
    }
    `;

    let timerIds = []; // Store active timer IDs

    // Function to check if an item has expired based on its end time (handles Unix timestamp and formatted date string)
    function hasExpired(endTime) {
        let expirationTime;

        // Check if endTime is a string (formatted date) or a Unix timestamp
        if (typeof endTime === 'string') {
            // If it's a string, we parse it to a timestamp
            const parsedDate = new Date(endTime); // Parse the formatted date string
            expirationTime = parsedDate.getTime(); // Get timestamp in milliseconds
        } else {
            // If it's a Unix timestamp, ensure it's in milliseconds
            expirationTime = endTime < 1e12 ? endTime * 1000 : endTime;
        }

        const currentTime = Date.now();
        return expirationTime <= currentTime;
    }

    // Function to check if an item has started based on its start time (handles Unix timestamp and formatted date string)
    function hasStarted(startTime) {
        let beginTime;

        // Check if startTime is a string (formatted date) or a Unix timestamp
        if (typeof startTime === 'string') {
            // If it's a string, we parse it to a timestamp
            const parsedDate = new Date(startTime); // Parse the formatted date string
            beginTime = parsedDate.getTime(); // Get timestamp in milliseconds
        } else {
            // If it's a Unix timestamp, ensure it's in milliseconds
            beginTime = startTime < 1e12 ? startTime * 1000 : startTime;
        }

        const currentTime = Date.now();
        return beginTime <= currentTime;
    }


    /**
     * Calculates the time remaining until the start or end of an event
     * @param {Date} endTime - The end time of the event
     * @param {Date} startTime - The start time of the event
     * @returns {string} Time left as "Starts in" or "Time Left" with countdown
     */
    function calculateTimeLeft(startTime, endTime) {
        const now = new Date().getTime();
        const start = new Date(startTime).getTime();
        const end = new Date(endTime).getTime();

        // If the event hasn't started yet, show "Starts in" with countdown to start
        if (now < start) {
            const timeUntilStart = start - now;
            return `Starts in: ${formatDuration(timeUntilStart)}`;
        }

        // If the event is ongoing, show "Time Left" with countdown to end
        if (now < end) {
            const timeUntilEnd = end - now;
            return `Time Left: ${formatDuration(timeUntilEnd)}`;
        }

        // If the event has ended
        return "Event Ended";
    }

    /**
     * Formats a duration in milliseconds into "D days, H hours, M minutes" format
     * @param {number} duration - Duration in milliseconds
     * @returns {string} Formatted duration string
     */
    function formatDuration(duration) {
        const days = Math.floor(duration / (1000 * 60 * 60 * 24));
        const hours = Math.floor((duration % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60));

        return `${days > 0 ? days + "d " : ""}${hours}h ${minutes}m`;
    }

    // Getting the current Gacha banner, Event(s), and Raid(s)
    // JFD's also fall under the "Raids" section
    // Total Assault, Grand Assault (same category as TA's), JFDs, Limit Break/Final Restriction, World Raid
    async function getCurrentGachaEventsRaids(region, lang) {

        function capitalizeFirstLetter(string) {
            return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
        }

        const baseUrl = "https://schaledb.com/data/";

        // Modify the fetch URLs to use the lang parameter
        // Use const raidsData = await fetch(`${baseUrl}/en/raids.json`).then(res => res.json()); for just English text
        const configData = await fetch(`${baseUrl}config.json`).then(res => res.json());
        const localizationData = await fetch(`${baseUrl}${lang}/localization.json`).then(res => res.json());
        const raidsData = await fetch(`${baseUrl}${lang}/raids.json`).then(res => res.json());

        // Fetch all student-related data including name and other details
        async function fetchStudentData() {
            // Fetch both students data and localization data in parallel
            const [studentsResponse, localizationResponse] = await Promise.all([
                fetch('https://schaledb.com/data/en/students.json'),
                fetch('https://schaledb.com/data/en/localization.json')
            ]);

            const studentsData = await studentsResponse.json();
            const localizationData = await localizationResponse.json();

            // Create a map with the student ID as the key and the student details as the value
            const studentMap = Object.values(studentsData).reduce((acc, student) => {
                const studentFullName = `${student.FamilyName} ${student.PersonalName}`;
                acc[student.Id] = {
                    name: studentFullName, // Student's full name
                    displayName: student.Name,
                    SquadType: getLocalizedDetail(student.SquadType, localizationData.SquadType),
                    TacticRole: getLocalizedDetail(student.TacticRole, localizationData.TacticRole),
                    BulletType: getLocalizedDetail(student.BulletType, localizationData.BulletType),
                    ArmorType: getLocalizedDetail(student.ArmorType, localizationData.ArmorType)
                };
                return acc;
            }, {});

            return studentMap;
        }

        // Helper function to get localized data
        function getLocalizedDetail(value, localizationData) {
            if (value && localizationData[value]) {
                // Capitalize the first letter and lowercase the rest
                return `${localizationData[value][0].toUpperCase()}${localizationData[value].slice(1).toLowerCase()}`;
            }
            return value; // Return value as is if no localization is found
        }

        // Function to get the student's details by ID (name and other details)
        async function getStudentDetailsById(id) {
            // Cache student data to avoid multiple fetches
            if (!window.studentMap) {
                window.studentMap = await fetchStudentData();
            }

            // Return the student's details or a message if the ID is not found
            return window.studentMap[id] ?? `Unknown student with ID ${id}`;
        }

        let tableCells = '';

        // Search for the region by Name within configData.Regions
        const regionData = configData.Regions.find(reg => reg.Name === region) || {};

        // Access CurrentEvents, CurrentGacha, and CurrentRaid using regionData
        const currentEvents = regionData.CurrentEvents || {};
        const currentGacha = regionData.CurrentGacha || {};
        const currentRaids = regionData.CurrentRaid || {};

        function formatDate(timestamp) {
            const date = new Date(timestamp * 1000);
            const formattedDate = date.toLocaleString('en-GB', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
            });
            const [datePart, timePart] = formattedDate.split(', ');
            const [day, month, year] = datePart.split('/');
            return `${year}/${month}/${day}, ${timePart}`;
        }

        /**
         * Sets up and updates the countdown timer every second
         * @param {Date} startTime - The start time of the event
         * @param {Date} endTime - The end time of the event
         * @param {string} elementId - The ID of the HTML element where the timer is displayed
         */
        function createCountdownTimer(startTime, endTime, elementId) {
            let timerId = setInterval(1000);
            const updateTimer = () => {
                const timerElement = document.getElementById(elementId);
                const displayText = calculateTimeLeft(startTime, endTime);

                if (timerElement) {
                    timerElement.textContent = displayText;
                } else {
                    clearInterval(timerId); // Clear interval if element is missing
                }

                // Stop the interval if the event has ended
                if (displayText === "Event Ended") {
                    clearInterval(timerId);
                }
            };

            updateTimer(); // Initial update
            timerId = setInterval(updateTimer, 1000); // Update every second
            timerIds.push(timerId); // Store the timer ID
        }

        const uniformSpacing = '10px';

        const cellStyle = `
        flex: 1;
        vertical-align: top;
        padding: 2.5px;
    `;

        const sectionStyle = `
        display: flex;
        flex-direction: column;
        gap: ${uniformSpacing};
    `;

        const rowStyle = `
        display: flex;
        gap: ${uniformSpacing};
    `;

        const innerDivStyle = `
        border: 1px solid #ccc;
        border-radius: 5px;
        display: flex;
        flex-direction: column;
        flex: 1;
    `;

        const headerStyle = `
        line-height: 1.2;
        text-size-adjust: 100%;
        font-weight: bold;
        padding: 10px;
        text-align: center;
        border-bottom: 1px solid #ccc;
    `;

        const contentStyle = `
        height: 125px;
        display: flex;
        justify-content: space-evenly;
        align-items: center;
        padding: 10px;
    `;

        const footerStyle = `
        padding: 10px;
        text-align: center;
        border-top: 1px solid #ccc;
    `;

        // Process Current Gacha
        let gachaCell = "";

        for (const [gachaNum, gachaData] of Object.entries(currentGacha)) {
            // Skip this gacha banner if expired
            if (hasExpired(gachaData.end)) {
                continue;
            }
            const startTime = formatDate(gachaData.start);
            const endTime = formatDate(gachaData.end);

            gachaCell += `
                <td style="${cellStyle}">
                    <div style="${sectionStyle}">
                        <div style="${innerDivStyle}">
                            <div style="${headerStyle}">${hasStarted(gachaData.start) ? 'Current Gacha' : 'Upcoming Gacha'}</div>
                            <div style="${contentStyle}">
            `;

            for (const studentId of gachaData.characters) {
                const studentDetails = await getStudentDetailsById(studentId);
                const studentName = studentDetails.displayName;
                const studentImage = `https://schaledb.com/images/student/collection/${studentId}.webp`;

                // Fetch additional student details from localizationData
                // Check and format each detail to avoid undefined values
                const bulletType = localizationData[studentDetails.BulletType] || studentDetails.BulletType || "Unknown";
                const armorType = localizationData[studentDetails.ArmorType] || studentDetails.ArmorType || "Unknown";
                const tacticRole = localizationData[studentDetails.TacticRole] || studentDetails.TacticRole || "Unknown";
                const squadType = localizationData[studentDetails.SquadType] || studentDetails.SquadType || "Unknown";



                gachaCell += `
                    <div style="display: inline-block; padding: 8px;">
                        <div style="position: relative; text-align: justify;">
                            <center class="image-container" style="width:60px;height:60px;">
                                <img src="${studentImage}" alt="${studentName}" style="width:50px;height:50px;">
                            </center>
                            <center style="font-weight: bold; white-space: pre;">${studentName.replace(' ', '\n')}</center>
                            <center style="text-align: center; font-size: 0.8em;">${squadType} | ${tacticRole}</center>
                            <center style="text-align: center; font-size: 0.8em;">${bulletType} / ${armorType}</center>
                        </div>
                    </div>
                `;
            }

            gachaCell += `</div>`;

            const timerId = `gacha-timer-${gachaNum}`;
            gachaCell += `
                            <div style="${footerStyle}">
                                <div>${startTime} - ${endTime}</div>
                                <div id="${timerId}" style="margin-top: 5px;">Time Left: ${calculateTimeLeft(gachaData.end)}</div>
                            </div>
                        </div>
                    </div>
                </td>
            `;
            // Set up the timer after the element is added to the DOM
            setTimeout(() => createCountdownTimer(startTime, endTime, timerId), 0);
        }

        if (gachaCell !== '') {
            tableCells += gachaCell;
        }

        if (Object.keys(currentEvents).length > 0) {
            // Process Current Events
            let eventsCell = "";

            for (let i = 0; i < Object.keys(currentEvents).length; i += 2) {
                const eventEntries = Object.entries(currentEvents).slice(i, i + 2);
                let innerEventsCell = '';

                eventEntries.forEach(([eventNum, eventData]) => {
                    // Check if the event has expired
                    if (hasExpired(eventData.end)) {
                        console.log(`Event ${eventNum} has expired, skipping.`);
                        return; // Skip this event if expired
                    }

                    // Get the full event ID
                    const fullEventId = eventData.event.toString();

                    // Check if it's a rerun based on the "10" prefix
                    const isRerun = fullEventId.startsWith("10");

                    // Slice off the prefix "10" for the actual event ID
                    const eventId = isRerun ? fullEventId.slice(2) : fullEventId;

                    // Get the event name from localizationData
                    let eventName = localizationData.EventName?.[eventId] || "Unknown Event";

                    // If it's a rerun, append "(Rerun)" to the event name
                    if (isRerun) {
                        eventName += " (Rerun)";
                    }
                    const eventImage = `https://schaledb.com/images/eventlogo/${eventId}_${region === 'Global' ? 'En' : 'Jp'}.webp`;
                    const startTime = formatDate(eventData.start);
                    const endTime = formatDate(eventData.end);
                    const timerId = `event-timer-${eventNum}`;
                    innerEventsCell += `
                        <div style="${innerDivStyle}">
                            <div style="${headerStyle}">Event</div>
                            <div style="${contentStyle}">
                                <div style="display: block;">
                                    <div style="display: flex; justify-content: space-evenly; align-items: center;">
                                        <img src="${eventImage}" alt="${eventName}" style="max-width: 240px; max-height: 80px; width: auto; height: auto; object-fit: contain;">
                                    </div>
                                    <center style="flex: 1; width: 100%; min-width: 0;">${eventName}</center>
                                </div>
                            </div>
                            <div style="${footerStyle}">
                                <div>${startTime} - ${endTime}</div>
                                <div id="${timerId}" style="margin-top: 5px;">Time Left: ${calculateTimeLeft(eventData.end)}</div>
                            </div>
                        </div>
                    `;
                    // Set up the timer after the element is added to the DOM
                    setTimeout(() => createCountdownTimer(startTime, endTime, timerId), 0);
                });

                if (innerEventsCell !== '') {
                    eventsCell += `<div style="${rowStyle}">` + innerEventsCell + `</div>`;
                }
            }

            if (eventsCell !== '') {
                tableCells += `<td style="${cellStyle}"><div style="${sectionStyle}">` + eventsCell + `</div></td>`;
            }
        }

        // Process Current Raids

        // Function to get Torment armor type from the dvdoomutils data
        // Defaults to JP data, but can be changed for EN
        // Define the color-to-armor type mappings (using lowercase and no punctuation for keys)
        // This should work no matter what so long as its spelled right
        function getTormentArmorType(region, localizationData) {
            return fetch("https://rentry.org/dvdoomutils/raw")
                .then(response => response.json())
                .then(dvdoomutilsData => {
                    // Normalize region name to lowercase and strip punctuation
                    let normalizedRegion = region.toLowerCase().replace(/[^\w]/g, '');

                    // Treat "en" as equivalent to "global" and map it to "EN"
                    if (normalizedRegion === 'en' || normalizedRegion === 'global') {
                        normalizedRegion = 'en';
                    }

                    // Find matching region key in dvdoomutilsData, default to "JP" if no match
                    const regionKey = Object.keys(dvdoomutilsData).find(key =>
                        key.toLowerCase().replace(/[^\w]/g, '') === normalizedRegion
                    ) || 'JP';

                    // Access torment armor color, using the matched region key
                    const tormentColor = dvdoomutilsData[regionKey]["GA"]["ARMOR"]["TORMENT"];

                    // Normalize the color to lowercase without punctuation
                    const normalizedColor = tormentColor.toLowerCase().replace(/[^\w]/g, '');

                    // Define color-to-armor type mappings
                    const colorToArmorType = {
                        "red": "LightArmor",
                        "yellow": "HeavyArmor",
                        "blue": "Unarmed",
                        "structure": "Structure",
                        "purple": "ElasticArmor",
                        "gray": "Normal",
                        "grey": "Normal",
                        "mixed": "Mixed"
                    };

                    // Fetch the corresponding armor type from localization data
                    const armorTypeKey = colorToArmorType[normalizedColor];
                    return localizationData.ArmorTypeLong[armorTypeKey] || "Unknown Armor Type";
                })
                .catch(error => {
                    console.error("Error fetching Torment Armor Type:", error);
                    return "Error loading";
                });
        }

        let raidsCell = ''; //`<td style="${cellStyle}"><div style="${sectionStyle}">`;

        // Map raid types to display names
        const raidTypeMapping = {
            "Raid": "Total Assault",
            "EliminateRaid": "Grand Assault",
            "MultiFloorRaid": "Final Restriction Release",
            "TimeAttack": "Joint Firing Drill",
            "WorldRaid": "World Raid"
        };

        for (let i = 0; i < Object.keys(currentRaids).length; i += 2) {
            const raidEntries = Object.entries(currentRaids).slice(i, i + 2);

            raidEntries.forEach(([raidNum, raidData]) => {
                const startTime = formatDate(raidData.start);
                const endTime = formatDate(raidData.end);
                // Use hasExpired to check if the raid is ongoing or expired
                if (hasExpired(endTime)) {
                    // Optional: Skip expired raids
                    console.log(`Raid ${raidNum} has expired and will not be displayed.`);
                    return; // Skip to the next raid if expired
                }
                const raidId = raidData.raid;
                const raidType = raidData.type || "Unknown Type";
                const displayType = raidTypeMapping[raidType] || "Unknown Type";
                let raidInfo = {};
                let season = raidData.season || ""; // Only use season if relevant
                let innerRaidsCell = '';
                // Handle different raid types
                if (raidType === "Raid") {
                    // Standard raids data, indexed by raidId - 1
                    const raidIndex = raidId - 1;
                    raidInfo = raidsData.Raid?.[raidIndex] || {};
                } else if (raidType === "EliminateRaid") {
                    const raidIndex = raidId - 1;
                    raidInfo = raidsData.Raid?.[raidIndex] || {};

                    // Generate a unique ID for the raid timer
                    const timerId = `raid-timer-${raidNum}`;

                    // Gather other raid information
                    const terrain = raidData.terrain || raidInfo.Terrain || "Unknown Terrain";
                    const startTime = formatDate(raidData.start);
                    const endTime = formatDate(raidData.end);
                    const raidName = raidInfo.Name || "Unknown Raid";
                    const raidDevName = raidInfo.DevName || "Unknown DevName";
                    const iconName = `Boss_Portrait_${raidDevName}_Lobby` || `Boss_Portrait_${raidName}_Lobby`;
                    const raidImage = `https://schaledb.com/images/raid/${iconName}.png`;
                    const attackType = localizationData.BulletType?.[raidInfo.BulletTypeInsane] || raidInfo.BulletTypeInsane;


                    innerRaidsCell += `
                        <div style="${innerDivStyle}">
                            <div style="${headerStyle}">${displayType} | ${raidName} ${season ? `| Season: ${season}` : ""}</div>
                            <div style="${contentStyle}">
                                <div style="display: block;">
                                    <div style="display: flex; justify-content: space-evenly; align-items: center;">
                                        <img src="${raidImage}" alt="${raidName}" style="max-width: 240px; max-height: 80px; width: auto; height: auto; object-fit: contain;">
                                    </div>
                                    <center style="flex: 1; width: 100%; min-width: 0;"><b>Terrain:</b> ${terrain}</center>
                                    <center style="flex: 1; width: 100%; min-width: 0;"><b>Torment+ Armor Type:</b> <span id="armor-type-${raidNum}">Loading...</span></center>
                                    <center style="flex: 1; width: 100%; min-width: 0;"><b>Attack Type:</b> ${attackType}</center>
                                </div>
                            </div>
                            <div style="${footerStyle}">
                                <div>${startTime} - ${endTime}</div>
                                <div id="${timerId}" style="margin-top: 5px;">Time Left: ${calculateTimeLeft(raidData.end)}</div>
                            </div>
                        </div>
                    `;

                    // Set up the timer after the element is added to the DOM
                    setTimeout(() => createCountdownTimer(startTime, endTime, timerId), 0);

                    // Fetch and load the Torment armor type without duplicating the cell (because it used to do that)
                    getTormentArmorType(region, localizationData).then(tormentArmorType => {
                        const element = document.getElementById(`armor-type-${raidNum}`);
                        if (element) {
                            element.innerText = tormentArmorType;
                        }
                    });
                    raidsCell += `<td style="${cellStyle}"><div style="${sectionStyle}"><div style="${rowStyle}">` + innerRaidsCell + `</div></td>`;
                    return;
                } else if (raidType === "MultiFloorRaid") {
                    // MultiFloorRaid data, matched by Id, no season
                    raidInfo = Object.values(raidsData.MultiFloorRaid || {}).find(raid => raid.Id === raidData.raid) || {};

                    // Extract data or set default values if missing
                    const terrain = raidInfo.Terrain || "Unknown Terrain";
                    const raidName = raidInfo.Name || "Unknown Raid";
                    const raidDevName = raidInfo.DevName || "Unknown DevName";
                    const startTime = formatDate(raidData.start);
                    const endTime = formatDate(raidData.end);
                    const iconName = raidInfo.icon || `Boss_Portrait_${raidDevName}_Lobby`;
                    const raidImage = `https://schaledb.com/images/raid/${iconName}.png`;
                    const timerId = `raid-timer-${raidNum}`;

                    // Set up the timer after the element is added to the DOM
                    setTimeout(() => createCountdownTimer(startTime, endTime, timerId), 0);

                    // Check BulletType and ArmorType
                    const bulletTypes = raidInfo.BulletType || [];
                    const armorType = raidInfo.ArmorType || "Unknown Armor";

                    // Map bullet types to localized names
                    const localizedArmorType = capitalizeFirstLetter(localizationData.ArmorType?.[armorType] || armorType);

                    // Construct floor change message
                    let minFloor = '';
                    let minFloorAttackType = '';
                    let floor = 0;

                    // Loop through the floors to check where the BulletType changes
                    for (let i = 0; i < raidInfo.BulletType.length; i++) {
                        const bulletType = raidInfo.BulletType[i - 1]; // Get the BulletType at the current floor index
                        const currentBulletType = raidInfo.BulletType[i]; // Current BulletType at this floor
                        if (bulletType == "Normal" && currentBulletType !== "Normal") {
                            // Once the BulletType changes from "Normal", capture the floor and change the message
                            minFloor = `F${floor}+`;
                            minFloorAttackType = `${localizationData.BulletType?.[currentBulletType]}`;
                            break; // Stop once the change is found
                        }
                        floor += 25;
                    }
                    // Add content to raidsCell
                    innerRaidsCell = `
                        <div style="${innerDivStyle}">
                            <div style="${headerStyle}">Limit Break Assault | ${raidName}</div>
                            <div style="${contentStyle}">
                                <div style="display: block;">
                                    <div style="display: flex; justify-content: space-evenly; align-items: center;">
                                        <img src="${raidImage}" alt="${raidName}" style="max-width: 240px; max-height: 80px; width: auto; height: auto; object-fit: contain;">
                                    </div>
                                    <center style="flex: 1; width: 100%; min-width: 0;"><b>Terrain:</b> ${terrain}</center>
                                    <center style="flex: 1; width: 100%; min-width: 0;">
                                        <b>Armor Type:</b> ${localizedArmorType}
                                    </center>
                                    ${minFloor ? `<center style="flex: 1; width: 100%; min-width: 0;"><b>${minFloor} Attack Type:</b> ${minFloorAttackType}</center>` : ''}
                                </div>
                            </div>
                            <div style="${footerStyle}">
                                <div>${startTime} - ${endTime}</div>
                                <div id="${timerId}" style="margin-top: 5px;">Time Left: ${calculateTimeLeft(raidData.end)}</div>
                            </div>
                        </div>
                    `;
                    raidsCell += `<td style="${cellStyle}"><div style="${sectionStyle}"><div style="${rowStyle}">` + innerRaidsCell + `</div></td>`;
                    return;
                } else if (raidType === "TimeAttack") {
                    // TimeAttack uses raidId as the key in raidsData.TimeAttack
                    // Find the TimeAttack data in raids.json by matching the 'raid' value from config.json
                    raidInfo = Object.values(raidsData.TimeAttack || {}).find(raid => raid.Id === raidData.raid) || {};

                    // Extract TimeAttack-specific data or set default values if missing
                    const dungeonType = raidInfo.DungeonType || "Unknown Dungeon";
                    const terrain = raidInfo.Terrain || "Unknown Terrain";
                    const startTime = formatDate(raidData.start);
                    const endTime = formatDate(raidData.end);
                    const iconName = raidInfo.Icon || `enemyinfo_placeholder`;
                    const raidImage = `https://schaledb.com/images/enemy/${iconName}.webp`;

                    // Only take the last set of rule IDs from TimeAttack -> Rules
                    // Usually, the final set (stage 4) will have all rules applied
                    const rulesArray = raidInfo.Rules || [];
                    const lastRuleSet = rulesArray[rulesArray.length - 1] || []; // Get the last set or an empty array if not found
                    let rulesDescriptions = `<div><ul>`;

                    // Function to replace identifiers with localized names, making every identifier bold
                    // ba-col is used as a class to color text based off its type (Explosive = red, Piercing = yellow, etc)
                    const replaceIdentifiers = (text, localizationData) => {
                        return text.replace(/<([a-z]):([A-Za-z0-9_]+)>/g, (match, type, identifier) => {
                            // Determine prefix based on type
                            let prefix;
                            if (type === 'b') prefix = 'Buff'; // Bolden Buff types
                            else if (type === 'c') prefix = 'CC'; // Bolden CC types
                            else if (type === 'd') prefix = 'Debuff'; // Bolden Debuff types
                            else if (type === 's') prefix = 'Special'; // Bolden Special types
                            else return match; // Return the match as-is if type doesn't match any of the above

                            // Construct localization key and look up with BuffName priority over BuffNameLong
                            const localizationKey = `${prefix}_${identifier}`;
                            let replacementText;

                            if (localizationData.BuffName && localizationData.BuffName[localizationKey]) {
                                replacementText = localizationData.BuffName[localizationKey];
                            } else if (localizationData.BuffNameLong && localizationData.BuffNameLong[localizationKey]) {
                                replacementText = localizationData.BuffNameLong[localizationKey];
                            } else {
                                // If no match is found in localization data, use the identifier with spaces for underscores
                                replacementText = identifier.replace(/_/g, ' ');
                            }

                            // Bolden the whole match (<type:identifier>) and replace with replacementText
                            return `<b>${replacementText}</b>`;
                        });
                    };

                    // Process each rule ID in the last rule set
                    lastRuleSet.forEach(ruleObj => {
                        const ruleId = ruleObj.Id;
                        const parameters = ruleObj.Parameters || [];

                        if (ruleId === 990306261 || ruleId === 1329507091 || ruleId === 3938056289) return;

                        // Find the matching rule in TimeAttackRules by Id
                        const matchedRule = (raidsData.TimeAttackRules || []).find(rule => rule.Id === ruleId);

                        if (matchedRule) {
                            let ruleName = matchedRule.Name || "Unknown Rule Name";
                            let ruleDesc = matchedRule.Desc || "No Description Available";

                            // Replace placeholders in the description if parameters are present
                            if (parameters.length > 0) {
                                parameters.forEach((paramGroup, index) => {
                                    const placeholder = `<?${index + 1}>`; // Placeholder format is <?1>, <?2>, etc.
                                    if (paramGroup[0]) {
                                        ruleDesc = ruleDesc.replace(placeholder, paramGroup[0]);
                                    }
                                });
                            }

                            // Replace identifiers like <s:ImmuneDamage> using localization data
                            // Do we call these indentifiers anyways?
                            ruleDesc = replaceIdentifiers(ruleDesc, localizationData);

                            rulesDescriptions += `<li style="font-size: 11px;">${ruleDesc}</li>`;
                        } else {
                            rulesDescriptions += `<li style="font-size: 11px;">Unknown Rule - No Description Available</li>`;
                        }
                    });

                    rulesDescriptions += `</ul></div>`; // Close the rules descriptions div

                    const timerId = `raid-timer-${raidNum}`;
                    innerRaidsCell = `
                        <div style="${innerDivStyle}">
                            <div style="${headerStyle}">Joint Firing Drill | ${dungeonType} | ${terrain}</div>
                            <div style="${contentStyle}">
                                <div style="display: block;">
                                    <div style="display: flex; justify-content: space-evenly; align-items: center;">
                                        <img src="${raidImage}" alt="${dungeonType}" style="max-width: 240px; max-height: 60px; width: 240px; height: auto; object-fit: contain;">
                                    </div>
                                    ${rulesDescriptions}
                                </div>
                            </div>
                            <div style="${footerStyle}">
                                <div>${startTime} - ${endTime}</div>
                                <div id="${timerId}" style="margin-top: 5px;">Time Left: ${calculateTimeLeft(raidData.end)}</div>
                            </div>
                        </div>
                    `;
                    raidsCell += `<td style="${cellStyle}"><div style="${sectionStyle}"><div style="${rowStyle}">` + innerRaidsCell + `</div></div></td>`;
                    // Set up the timer after the element is added to the DOM
                    setTimeout(() => createCountdownTimer(startTime, endTime, timerId), 0);
                    return;
                } else if (raidType === "WorldRaid") {
                    // WorldRaid data can use direct matching without season
                    // Good old untested code because these run so rarely
                    // This will probably not work, honestly
                    raidInfo = raidsData.WorldRaid?.find(raid => raid.Id === raidId) || {};
                }

                // Gather details with default fallbacks
                const terrain = raidData.terrain || raidInfo.Terrain || "Unknown Terrain";
                const raidName = raidInfo.Name || "Unknown Raid";
                const raidDevName = raidInfo.DevName || "Unknown DevName";
                const iconName = `Boss_Portrait_${raidDevName}_Lobby` || `Boss_Portrait_${raidName}_Lobby`;
                const raidImage = `https://schaledb.com/images/raid/${iconName}.png`;
                const attackType = localizationData.BulletType?.[raidInfo.BulletTypeInsane] || raidInfo.BulletTypeInsane;
                const armorType = raidInfo.ArmorType || "Unknown Armor";

                // Map bullet types to localized names
                const localizedArmorType = capitalizeFirstLetter(localizationData.ArmorType?.[armorType] || armorType);

                const timerId = `raid-timer-${raidNum}`;
                innerRaidsCell = `
                    <div style="${innerDivStyle}">
                        <div style="${headerStyle}">${displayType} ${season ? `Season: ${season}` : ""} | ${raidName}</div>
                        <div style="${contentStyle}">
                            <div style="display: block;">
                                <div style="display: flex; justify-content: space-evenly; align-items: center;">
                                    <img src="${raidImage}" alt="${raidName}" style="max-width: 240px; max-height: 80px; width: auto; height: auto; object-fit: contain;">
                                </div>
                                <center style="flex: 1; width: 100%; min-width: 0;"><b>Terrain:</b> ${terrain}</center>
                        <center style="flex: 1; width: 100%; min-width: 0;"><b>Armor Type:</b> ${localizedArmorType}</center>
                                <center style="flex: 1; width: 100%; min-width: 0;"><b>Insane+ Attack Type:</b> ${attackType}</center>
                            </div>
                        </div>
                        <div style="${footerStyle}">
                            <div>${startTime} - ${endTime}</div>
                            <div id="${timerId}" style="margin-top: 5px;">Time Left: ${calculateTimeLeft(raidData.end)}</div>
                        </div>
                    </div>
                `;
                raidsCell += `<td style="${cellStyle}"><div style="${sectionStyle}"><div style="${rowStyle}">` + innerRaidsCell + `</div></td>`;
                // Set up the timer after the element is added to the DOM
                setTimeout(() => createCountdownTimer(startTime, endTime, timerId), 0);
            });
        }

        if (raidsCell !== '') {
            tableCells += raidsCell + `</div></td>`;
        }

        if (tableCells === '') {
            tableCells = `
                <td style="${cellStyle}">
                    <div style="${sectionStyle}">
                        <div style="${rowStyle}">
                            <div style="${innerDivStyle}">
                                <div style="${headerStyle}"></div>
                                <div style="${contentStyle}">
                                    No data currently available to display.
                                </div>
                                <div style="${footerStyle}">

                                </div>
                            </div>
                        </div>
                    </div>
                </td>
            `;
        }

        // Insert final HTML into the page
        let finalString = `
            <div style="width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch;">
                <table style="width: 100%; display: table; border-collapse: separate; padding-right: ${uniformSpacing}; padding-top: ${uniformSpacing}; padding-bottom: ${uniformSpacing};">
                    <tr style="display: flex; width: 100%;">${tableCells}</tr>
                </table>
            </div>
        `;

        // Modify the part where inserting the final HTML to append it to the container
        const serverToggle = document.querySelector('.server-toggle');
        if (serverToggle) {
            const container = serverToggle.parentNode;

            // Create a wrapper div for the table
            const tableWrapper = document.createElement('div');
            tableWrapper.id = "current-ba-info"
            tableWrapper.innerHTML = finalString;
            tableWrapper.style.cssText = `flex: 1; min-width: 0;`;

            // Remove top padding from the table wrapper
            const tableElement = tableWrapper.querySelector('table');
            if (tableElement) {
                tableElement.style.marginTop = '0';
            }

            container.appendChild(tableWrapper);
        }
    }

    let currentRegion = localStorage.getItem("currentRegion") || "Global";
    let currentLang = localStorage.getItem("currentLang") || 'en';

    // Extend the createUI function
    function createUI() {
        // Add the styles
        const styleElement = document.createElement('style');
        styleElement.textContent = toggleStyles;
        document.head.appendChild(styleElement);

        const serverSelection = document.createElement("div");
        serverSelection.className = "server-toggle";

        const toggleServerButton = document.createElement("button");
        toggleServerButton.className = "server-toggle-button-en"; // Add a specific class for server button
        toggleServerButton.textContent = "EN"; // Set initial state.
        if (currentRegion === "Global") toggleServerButton.classList.add("selected");
        toggleServerButton.onclick = () => changeServer('Global');
        // Add the server toggle button
        serverSelection.appendChild(toggleServerButton);

        const toggleServerButtonJP = document.createElement("button");
        toggleServerButtonJP.className = "server-toggle-button-jp"; // Add a specific class for server button
        toggleServerButtonJP.textContent = "JP"; // Set initial state.
        if (currentRegion !== "Global") toggleServerButtonJP.classList.add("selected");
        toggleServerButtonJP.onclick = () => changeServer('Jp');
        // Add the server toggle button
        serverSelection.appendChild(toggleServerButtonJP);

        const infoPopopButton = document.createElement("button");
        infoPopopButton.className = "server-toggle-tooltip-button"; // Add a specific class for server button
        infoPopopButton.innerHTML = '<span style="display: inline-block; transform: rotate(90deg);">?</span>'
        infoPopopButton.classList.add("selected");
        // Add the server toggle button
        serverSelection.appendChild(infoPopopButton);

        const infoPopopMessage = document.createElement("div");
        // infoPopopButton.className = "server-toggle-button"; // Add a specific class for server button
        infoPopopMessage.className = "server-toggle-tooltip"
        infoPopopMessage.textContent = "Data is obtained from SchaleDB's API and is completely dependant on if the website is still alive and when and even if the owner makes the data available.";
         // Add the server toggle button
        serverSelection.appendChild(infoPopopMessage);


        // Create the language toggle button
        const toggleLangButton = document.createElement("button");
        toggleLangButton.className = "lang-toggle-button"; // Add a specific class for language button
        toggleLangButton.textContent = currentLang === 'en' ? "English" : "Japanese"; // Set initial state based on currentLang
        toggleLangButton.onclick = changeLanguage;

        // Add the language toggle button next to the server toggle button
        // serverSelection.appendChild(toggleLangButton);

        // Create a container for the toggles and the table
        const container = document.createElement("div");
        container.style.cssText = `
            display: flex;
            width: 100%;
        `;
        // container.style.flexDirection = "column";
        // container.style.width = "100%";
        container.appendChild(serverSelection);

        // Insert the container after DVDoomParent
        const dvDoomParent = document.getElementById("DVDoomParent");
        if (dvDoomParent) {
            dvDoomParent.parentNode.insertBefore(container, dvDoomParent.nextSibling);
        } else {
            document.body.appendChild(container);
        }

        // Initial load of data
        getCurrentGachaEventsRaids(currentRegion, currentLang);
    }

    // New function to change the language and reload data
    async function changeLanguage() {
        // Toggle language between 'en' and 'jp'
        currentLang = currentLang === 'en' ? 'jp' : 'en';

        // Save the language setting to localStorage
        localStorage.setItem("currentLang", currentLang);

        // Update button text immediately
        const toggleLangButton = document.querySelector('.lang-toggle-button'); // Target language button specifically
        if (toggleLangButton) {
            toggleLangButton.textContent = currentLang === 'en' ? "English" : "Japanese";
        }

        // Remove the existing table if it exists
        const serverToggle = document.querySelector('.server-toggle');
        if (serverToggle) {
            const existingTable = serverToggle.nextElementSibling;
            if (existingTable) {
                existingTable.remove();
            }
        }

        // Reload the data with the updated language
        await getCurrentGachaEventsRaids(currentRegion, currentLang);
    }

    // Function to change the server and reload data
    async function changeServer(region = "Global") {
        timerIds.forEach(id => clearInterval(id));
        timerIds = []; // Reset the array after clearing

        // Toggle the region immediately
        currentRegion = region;

        // Save the current selection to localStorage
        localStorage.setItem("currentRegion", region);

        const toggleButtonEN = document.querySelector('.server-toggle-button-en'); // Target server button specifically
        const toggleButtonJP = document.querySelector('.server-toggle-button-jp'); // Target server button specifically

        if (currentRegion === 'Global') {
            toggleButtonEN.classList.add('selected');
            toggleButtonJP.classList.remove('selected');
        } else {
            toggleButtonEN.classList.remove('selected');
            toggleButtonJP.classList.add('selected');
        }

        // Remove the existing table if it exists
        document.getElementById('current-ba-info')?.remove();

        // Reload the data for the new server
        await getCurrentGachaEventsRaids(currentRegion, currentLang);
    }

    // Run the UI creation function
    createUI();
})();

})();

Edit

Pub: 16 Apr 2024 10:55 UTC

Edit: 31 Jan 2025 10:46 UTC

Views: 298