Can you make this better by adding more features to it, strengthening the code snippets. And fixing errors, try to add a variety of value to it that isnt in it already. // GOOD Comprehensive Betting Tracker Script v3
//===============================

// == Region: Inject jQuery if not loaded == //
(function() {
    if (typeof jQuery === 'undefined') {
        // Inject jQuery dynamically
        let script = document.createElement('script');
        script.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
        script.type = 'text/javascript';
        document.getElementsByTagName('head')[0].appendChild(script);

        // Wait for jQuery to load before running the rest of the script
        script.onload = function() {
            setGameObject();
        };
    } else {
        // jQuery is already loaded, execute the rest of the script
        setGameObject();
    }
})();

// == Region: Define Game Object based on URL == //
function setGameObject() {
    // Get the current page URL
    let url = window.location.href;
    let gameObject;

    // Set the game object based on the game URL
    if (url.includes("/limbo")) {
        gameObject = lbg;
    } else if (url.includes("/hash-dice")) {
        gameObject = hdg;
    } else if (url.includes("/wheel")) {
        gameObject = wlg;
    } else if (url.includes("/classic-dice")) {
        gameObject = cd;
    } else if (url.includes("/keno")) {
        gameObject = dg;
    } else {
        console.error("Unrecognized game URL");
        return; // Exit if the URL doesn't match any game
    }

    if (gameObject) {
        InjectHotkeys();
    }

    // Function to add hotkeys to the current game
    function InjectHotkeys() {
        gameObject.addHotkey(
            "x",
            () => {
                HalfUp();
            },
            "Multiplies current bet by 1.5"
        );
        gameObject.addHotkey(
            "z",
            () => {
                HalfDown();
            },
            "Divides current bet by 2.5"
        );
        gameObject.addHotkey(
            ",",
            () => {
                DoManualBet(true);
            },
            "Places shown bet and doubles the bet on win."
        );
        gameObject.addHotkey(
            ".",
            () => {
                DoManualBet();
            },
            "Places shown bet"
        );
        gameObject.addHotkey(
            "/",
            () => {
                DoManualMinBet();
            },
            "Makes min bet"
        );

        // Add the Payout Switch Hotkey (P key)
        gameObject.addHotkey('P', () => {
            const payout = getRandomPayout();
            // Apply the selected payout to the game object
            gameObject.payout = parseFloat(payout);
            console.log(`Payout switched: ${payout}`);
        });
    }

    // Functions for different actions
    function HalfUp() {
        gameObject.setAmount(gameObject.amount.mul(1.5));
    }

    function HalfDown() {
        gameObject.setAmount(gameObject.amount.div(2.5));
    }

    function DoManualBet(increaseOnWin = false) {
        gameObject.bet(gameObject.amount).then(() => {
            if (gameObject.myBets[0].profitAmount > 0) {
                if (increaseOnWin) {
                    gameObject.setAmount(gameObject.amount.mul(1.16)); // Change the multiplier here for increase on win
                }
            }
        });
    }

    function DoManualMinBet() {
        gameObject.bet(gameObject.minAmount);
    }

    // Function to watch for URL changes using history API
    function watchUrlChanges() {
        const originalPushState = history.pushState;
        const originalReplaceState = history.replaceState;

        // Override pushState and replaceState to detect navigation changes
        history.pushState = function() {
            originalPushState.apply(history, arguments);
            setGameObject(); // Ensure the correct game object is set on navigation
        };

        history.replaceState = function() {
            originalReplaceState.apply(history, arguments);
            setGameObject(); // Ensure the correct game object is set on navigation
        };

        // Listen for 'popstate' event (back/forward navigation)
        window.addEventListener('popstate', () => {
            setGameObject(); // Ensure the correct game object is set on navigation
        });
    }

    // Initial setup
    fetchRecentBets(); // Fetch recent bets on load
    watchUrlChanges();

    // Proceed to customize the button functionality after setting gameObject
    customizeButton(gameObject);
    adjustButtonSizes(); // Adjust button sizes
}

// == Region: Define Custom Functionality == //
function customizeButton(gameObject) {
    // Use jQuery to select the button with the text 'x2'
    let buttonX2 = $("button:contains('x2')");

    // Unbind any existing click events on the button
    buttonX2.off('click');

    // Define your custom function to modify the bet amount
    function HalfUp() {
        // Perform the calculation accurately
        let currentAmount = gameObject.amount;
        let newAmount = currentAmount.mul(1.5); // Multiply by 1.5
        newAmount = newAmount.div(2); // Divide by 2 to align with the logic

        // Set the new bet amount
        gameObject.setAmount(newAmount);
    }

    // Bind the new click event to the button
    buttonX2.on('click', function() {
        HalfUp();
    });
}

// == Region: Adjust Button Sizes == //
function adjustButtonSizes() {
    // Define the font size and adjusted padding
    let fontSize = '12px'; // Your chosen font size
    let paddingVertical = '5px'; // Adjusted vertical padding to center text
    let paddingHorizontal = '10px'; // Horizontal padding remains unchanged

    // Calculate the line height based on the font size
    let lineHeight = '-.5'; // Slightly increased line-height

    // Apply styles to buttons within the specific button-group class
    $(".sc-kDTinF.bswIvI.button-group button").each(function() {
        $(this).css({
            'font-size': fontSize,
            'padding': `${paddingVertical} ${paddingHorizontal}`, // Apply vertical and horizontal padding
            'line-height': lineHeight,
            'text-align': 'center', // Center text horizontally
            'min-width': '20px',    // Set a minimum width to fit text
        });
    });
}

// Ensure jQuery is loaded
if (typeof jQuery === 'undefined') {
    var script = document.createElement('script');
    script.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
    document.head.appendChild(script);
}

script.onload = function() {
    // ===============================
    // Initialize Variables
    // ===============================

    var betHistory = [];
    var trackerStats = [
        {input: null, lastSeen: null, hotCold: null, maxStreak: 0, currentStreak: 0, totalHits: 0, betsSinceHit: 0, alertsEnabled: true, intensity: 2.5},
        {input: null, lastSeen: null, hotCold: null, maxStreak: 0, currentStreak: 0, totalHits: 0, betsSinceHit: 0, alertsEnabled: true, intensity: 2.5},
        {input: null, lastSeen: null, hotCold: null, maxStreak: 0, currentStreak: 0, totalHits: 0, betsSinceHit: 0, alertsEnabled: true, intensity: 2.5}
    ];
    var totalVaultedThisSession = 0;

    // ===============================
    // Add CSS Styles
    // ===============================

    var style = `
    <style>
        @import url("//fonts.googleapis.com/css2?family=Nanum+Gothic:ital,wght@0,300;0,400;0,500;0,600;0,700&display=swap");
        @import url("//fonts.googleapis.com/css2?family=Moulpali:ital,wght@0,300;0,400;0,500;0,600;0,700&display=swap");
        @import url("//fonts.googleapis.com/css2?family=Nerko+One:ital,wght@0,300;0,400;0,500;0,600;0,700&display=swap");
        @import url("//fonts.googleapis.com/css2?family=Palanquin+Dark:ital,wght@0,300;0,400;0,500;0,600;0,700&display=swap");
        @import url("//fonts.googleapis.com/css2?family=Pathway+Gothic+One:ital,wght@0,300;0,400;0,500;0,600;0,700&display=swap");

        #menuButton {
            position: fixed;
            left: 10px;
            top: 70px;
            background: #444;
            color: #fff;
            border: 1px solid #555;
            padding: 10px;
            cursor: pointer;
            z-index: 1001;
            border-radius: 0 5px 5px 0;
            font-family: 'Kanit', sans-serif;
            box-shadow: 2px 2px 5px rgba(0,0,0,0.5);
            transition: left 0.3s ease;
        }
        #menuButton:hover {
            background-color: #555;
        }
        #mainMenu {
            position: fixed;
            top: 10px;
            right: 10px;
            background: #1e1e1e;
            color: #fff;
            border: 1px solid #444;
            width: 340px;
            max-height: 400px;
            overflow-y: auto;
            z-index: 1000;
            font-size: 12px;
            display: none;
            font-family: 'Kanit', sans-serif;
            box-shadow: 2px 2px 10px rgba(0,0,0,0.5);
            transition: all 0.3s ease;
        }
        #mainMenu h3 {
            margin-top: 0;
            font-size: 16px;
            cursor: move;
            background: #2e2e2e;
            padding: 5px;
            border-bottom: 1px solid #444;
            text-align: center;
        }
        #mainMenu ul {
            list-style-type: none;
            padding-left: 0;
            margin: 0;
        }
        #mainMenu li {
            margin-bottom: 5px;
            padding: 5px;
            border-bottom: 1px solid #444;
        }
        #mainMenu li.winning {
            background: #2e4d32;
        }
        #mainMenu li.losing {
            background: #4d2e2e;
        }
        #mainMenu li .high-multiplier {
            color: yellow;
        }
        #mainMenu .minimize {
            position: absolute;
            top: 5px;
            right: 5px;
            cursor: pointer;
        }
        .section {
            display: none;
        }
        .section input {
            width: 100px;
            margin-right: 10px;
        }
        .section-title {
            cursor: pointer;
            background: #333;
            padding: 5px;
            border-bottom: 1px solid #444;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: background-color 0.3s;
        }
        .section-title:hover {
            background-color: #444;
        }
        .section-title .detach {
            cursor: pointer;
            font-weight: bold;
        }
        .autoVault-input, .tracker-input {
            margin-bottom: 5px;
        }
        .autoVault-input input, .tracker-input input {
            width: calc(100% - 20px);
            margin-bottom: 5px;
        }
        .autoVault-input button, .tracker-input button {
            width: calc(100% - 20px);
            margin-top: 5px;
        }
        .draggable {
            cursor: move;
        }
        .alert-checkbox {
            margin-right: 5px;
        }
        .intensity-input {
            width: 40px;
            margin-left: 10px;
        }

    /* Custom CSS for Limbo Page */
.game-main .game-view .sc-gFSQbh {
    background-image: url("https://imgur.com/a/FR8fkJc");
    background-attachment: fixed;
    transform: translatex(0px) translatey(0px);
}

#root .sc-lhMiDA {
    background-color: #0c0c0c;
    transform: translatex(0px) translatey(0px) !important;
    background-image: none;
}

#footer .footer-wrap {
    background-color: #0f0f0f;
}

.game-main .game-control .game-control-panel {
    background-image: none;
    background-color: #161616;
}

.game-area .game-main .game-control {
    background-color: #161616;
    border-style: solid;
    border-color: rgba(96, 96, 96, 0.2);
    border-top-left-radius: 23px;
    border-bottom-left-radius: 19px;
    border-top-right-radius: 50px;
    border-bottom-right-radius: 0px;
}

#root .sc-lhMiDA #game-Limbo .game-area .game-main .game-control {
    border-width: 8px !important;
}

.game-area .game-main .game-actions {
    background-color: #050000;
    background-position-x: 0%;
    box-shadow: 1px -4px 19px -2px rgba(2, 2, 2, 0.8);
}

#game-Limbo .game-area {
    box-shadow: 0px 0px 34px 9px rgba(2, 2, 2, 0.8);
    border-top-left-radius: 25px;
    border-top-right-radius: 25px;
    border-bottom-left-radius: 25px;
    border-bottom-right-radius: 25px;
    border-width: 4px;
    border-color: rgba(2, 2, 2, 0.95);
    border-style: solid;
    filter: contrast(1.025) saturate(1.05);
    visibility: visible;
    float: none;
    clear: none;
    align-items: normal;
    justify-content: normal;
    flex-direction: row;
    font-weight: 600;
    font-size: 16px;
    font-style: normal;
    text-transform: uppercase;
    text-align: left;
    text-shadow: rgba(0, 0, 0, 0.3) 0px 1px 1px;
}

#root {
    background-image: none;
    background-color: #000000;
    font-style: normal;
}

body {
    background-color: #020202 !important;
}

#footer {
    background-color: #0f0f0f;
}

#game-Limbo .sc-knKHOI {
    background-color: #131415;
    color: rgba(255, 255, 255, 0.8);
    font-style: italic;
    font-family: 'Nanum Gothic', sans-serif;
    text-align: left;
    text-transform: uppercase;
    box-shadow: 0px 0px 8px 1px rgba(2, 2, 2, 0.8);
}

.sc-cxpSdN .tabs-view .sc-eZhRLC {
    background-color: #111111;
    border-style: solid;
    border-width: 2px;
    border-color: rgba(2, 2, 2, 0.52);
    border-top-left-radius: 15px;
    border-top-right-radius: 15px;
    border-bottom-left-radius: 15px;
    border-bottom-right-radius: 15px;
    box-shadow: -2px 0px 13px 4px rgba(2, 2, 2, 0.8);
    font-family: 'Moulpali', display;
    font-size: 17px;
    font-style: normal;
    text-transform: uppercase;
    margin-left: 0px;
    padding-left: 8px;
    padding-bottom: 8px;
    letter-spacing: 0px;
    column-count: 1;
    direction: ltr;
    word-spacing: 0px;
    text-shadow: none;
    text-align: center;
}

.header-wrap .header .sc-hGnimi {
    background-color: #0a0a0a;
    font-family: 'Nerko One', handwriting;
}

#header .header-wrap .header {
    background-color: #0a0a0a;
}

#sidebar .large-sidebar .sc-uojGG {
    background-color: #0c0c0c;
    box-shadow: 0px 0px 12px 2px rgba(2, 2, 2, 0.8);
}

.large-sidebar .game-list .list-shadow {
    background-color: #191919;
}

#sidebar .large-sidebar {
    background-color: #161616;
    transform: translatex(0px) translatey(0px);
}

#header {
    background-color: #0a0a0a;
    box-shadow: 0px 0px 7px 0px rgba(2, 2, 2, 0.8);
}

.large-sidebar .menu-item .sc-gsDKAQ {
    background-color: #020202;
}

#game-Limbo .sc-bxDdli {
    width: 100%;
    height: auto;
    overflow: visible;
    min-width: 54px;
}

#game-Limbo .sc-knKHOI .intro-title {
    font-size: 11px;
    text-align: left;
}

#sidebar .large-sidebar .menu-item {
    color: rgba(239, 239, 239, 0.8);
    font-weight: 600;
    border-color: rgba(2, 2, 2, 0.52);
    border-style: solid;
    border-width: 0px;
}

.header-wrap .header .sc-DtmNo {
    background-color: #141414;
    border-color: rgba(255, 255, 255, 0.52);
    border-style: solid;
    border-width: 1px;
    border-left-style: solid;
    border-bottom-style: solid;
    border-top-style: none;
    border-right-style: none;
    border-right-width: 3px;
    box-shadow: 0px 0px 9px -3px rgba(153, 164, 176, 0.8);
    border-top-left-radius: 5px;
    border-top-right-radius: 10px;
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 10px;
}

.sc-jtXEFf .search-input-wrap-pc .sc-kTLmzF {
    border-color: rgba(61, 5, 183, 0.52);
    box-shadow: 0px 0px 7px 0px rgba(2, 2, 2, 0.8) inset;
}

@media (max-width: 621px) {
    body {
        overflow-x: hidden;
    }
    .bottom .sc-dcgwPl .sc-fotOHu {
        filter: contrast(1.04);
        background-blend-mode: screen;
        background-color: rgba(67, 179, 9, 0);
        font-family: 'Palanquin Dark', sans-serif;
        font-style: normal;
        text-transform: none;
        text-align: left;
        text-decoration: none;
        text-shadow: rgba(0, 0, 0, 0.3) 0px 1px 1px;
        letter-spacing: -0.4px;
        color: rgba(255, 255, 255, 0);
    }
    .bottom .shitcode img {
        background-image: none;
        opacity: 1;
        visibility: hidden;
    }
    .bottom .wrap .img-bg {
        display: inline-block;
        float: none;
        clear: none;
        visibility: hidden;
        transform: translatex(0px) translatey(0px);
    }
    .bottom .wrap:nth-child(1) .img-bg {
        visibility: hidden;
    }
    .bottom .wrap .shitcode {
        visibility: hidden;
    }
    .bottom .wrap {
        visibility: hidden;
    }
    .bottom .active img {
        transform: translatex(0px) translatey(0px);
    }
    .sc-efQSVx div {
        visibility: hidden;
    }
    .sc-efQSVx {
        visibility: hidden;
    }
    .game-view .game-recent .jackpot-enter {
        transform: translatex(0px) translatey(0px);
        visibility: hidden;
        top: 400px;
    }
    .recent-list-wrap .recent-list .recent-item {
        position: relative;
        left: 23px;
        visibility: visible;
    }
    .recent-list .recent-item .item-wrap {
        transform: translatex(-22px);
    }
    .game-main .game-view .game-recent {
        visibility: visible;
        transform: translatex(0px) translatey(0px);
    }
    .game-view .game-recent .recent-list-wrap {
        visibility: visible;
    }
    .sc-gFSQbh .sc-jwQYvw .game-rocket {
        transform: translatex(0px) translatey(0px);
        display: inline-block;
    }
    .sc-jwQYvw .game-rocket .rocket-number {
        font-family: 'Pathway Gothic One', sans-serif;
        font-style: normal;
        text-transform: none;
        text-decoration: none;
        text-align: center;
        text-shadow: rgba(0, 0, 0, 0.3) 0px 1px 1px;
        letter-spacing: 0px;
        direction: ltr;
    }
}
    </style>
    `;
    $('head').append(style);

//===============================
    // Create HTML Structure
    //===============================

    var mainMenuHTML = `
    <div id="menuButton">☰ Menu</div>
    <div id="mainMenu">
        <h3>Nanobot Bet Assistant v1.5<span class="minimize">[-]</span></h3>
        <div class="section-title" id="toggleBetResultsSection">Bet Results<span class="detach">+</span></div>
        <div id="betResultsSection" class="section">
            <ul id="betList"></ul>
        </div>
        <div class="section-title" id="toggleTrackerSection">Payout Tracker<span class="detach">+</span></div>
        <div id="trackerSection" class="section">
            <div class="tracker-input">
                <input type="number" id="trackerInput1" placeholder="Track 1">
                <label><input type="checkbox" id="alert1" class="alert-checkbox" checked>Alert</label>
                <input type="number" id="intensity1" class="intensity-input" value="2.5">
            </div>
            <div class="tracker-input">
                <input type="number" id="trackerInput2" placeholder="Track 2">
                <label><input type="checkbox" id="alert2" class="alert-checkbox" checked>Alert</label>
                <input type="number" id="intensity2" class="intensity-input" value="2.5">
            </div>
            <div class="tracker-input">
                <input type="number" id="trackerInput3" placeholder="Track 3">
                <label><input type="checkbox" id="alert3" class="alert-checkbox" checked>Alert</label>
                <input type="number" id="intensity3" class="intensity-input" value="2.5">
            </div>
            <ul id="trackerList"></ul>
        </div>
        <div class="section-title" id="toggleAutoVaultSection">Autovaulter V1.2<span class="detach">+</span></div>
        <div id="autoVaultSection" class="section">
            <div class="autoVault-input">
                <input type="number" id="vaultThreshold" placeholder="Max Coins">
                <input type="number" id="vaultInterval" placeholder="Interval (ms)">
                <button id="startAutoVault">Start Auto Vault</button>
            </div>
            <ul id="autoVaultList"></ul>
        </div>
    </div>
    `;
    $('body').append(mainMenuHTML);

    // Function to hide specified elements
    function hideElements(selectors) {
        selectors.forEach(selector => {
            $(selector).hide();
        });
    }

    // Hide specified elements
    hideElements([
        '.sc-bxDdli.dIbEXE.sc-haTkiu.jqCVCc',
        '.swrap-header',
        '.navigation-btns-wrap',
        '.swiper',
        '#footer'
    ]);

    //===============================
    // Function Definitions
    //===============================

    // Function to update the bet history display
    function updateBetHistory(bet) {
        var target = (bet.bv.payout / 100).toFixed(2);
        var result = (bet.gv / 100).toFixed(2);
        var multiplier = result >= target ? target : 0;
        var isWinning = result >= target;
        var nonce = bet.nonce.toString().slice(-3);
        var profit = (bet.gv / 100) * parseFloat(bet.betAmount) - parseFloat(bet.betAmount);

        var formattedBet = {
            betSize: parseFloat(bet.betAmount).toFixed(8),
            nonce: nonce,
            target: target,
            result: result,
            multiplier: multiplier,
            profit: profit.toFixed(8)
        };

        betHistory.push(formattedBet);
        if (betHistory.length > 20) {
            betHistory.shift(); // Keep only the last 20 bets
        }

        var betList = $('#betList');
        betList.empty();
        betHistory.forEach(function(bet) {
            var betClass = bet.multiplier > 0 ? 'winning' : 'losing';
            var highMultiplierClass = bet.result >= 10 ? 'high-multiplier' : '';
            betList.append(`
                <li class="${betClass}">
                    <div class="bet-info">
                        <span>Bet: ${bet.betSize}</span>
                        <span>Nonce: ${bet.nonce}</span>
                    </div>
                    <div class="bet-info">
                        <span>Target: ${bet.target}x</span>
                        <span class="${highMultiplierClass}">Result: ${bet.result}x</span>
                    </div>
                    <div class="bet-info">
                        <span>Multiplier: ${bet.multiplier}x</span>
                        <span>Profit: ${bet.profit}</span>
                    </div>
                </li>
            `);
        });
        updateTrackerStats(formattedBet);
    }

    // Function to update tracker stats
    function updateTrackerStats(bet) {
        trackerStats.forEach((tracker, index) => {
            if (tracker.input) {
                if (bet.result >= tracker.input) {
                    tracker.betsSinceHit = 0; // Reset bets since hit
                    tracker.totalHits += 1;
                    tracker.currentStreak += 1;
                    if (tracker.currentStreak > tracker.maxStreak) {
                        tracker.maxStreak = tracker.currentStreak;
                    }
                } else {
                    tracker.currentStreak = 0;
                }
                tracker.betsSinceHit += 1; // Increment bets since hit

                // Calculate Hot/Cold
                var expectedFrequency = betHistory.length / tracker.totalHits;
                tracker.hotCold = (tracker.totalHits > expectedFrequency) ? '🔥' : '❄️';

                // Check for alerts
                if (tracker.alertsEnabled && tracker.betsSinceHit >= Math.floor(tracker.input * tracker.intensity)) {
                    alert(`Multiplier ${tracker.input} has not been seen for ${tracker.betsSinceHit} bets.`);
                }
            }
        });
        updateTrackerDisplay();
    }

    // Function to update tracker display
    function updateTrackerDisplay() {
        var trackerList = $('#trackerList');
        trackerList.empty();
        trackerStats.forEach((tracker, index) => {
            if (tracker.input) {
                trackerList.append(`
                    <li>
                        <div class="tracker-info">
                            <span>Input: ${tracker.input}x</span>
                            <span>Bets Ago: ${tracker.betsSinceHit}</span>
                        </div>
                        <div class="tracker-info">
                            <span>${tracker.hotCold}</span>
                            <span>Max Streak: ${tracker.maxStreak}</span>
                        </div>
                    </li>
                `);
            }
        });
    }

    // Function to fetch recent bets from the API
    function fetchRecentBets() {
        $.ajax({
            url: 'https://nanogames.io/api/single/game/v2/recent-bet/',
            type: 'POST',
            data: JSON.stringify({"gameName":"Limbo","size":20}),
            contentType: 'application/json',
            success: function(response) {
                var bets = response.data;
                bets.forEach(function(bet) {
                    updateBetHistory(bet);
                });
            },
            error: function(error) {
                console.log('Error fetching recent bets:', error);
            }
        });
    }

    // Function to handle Auto Vault logic
    function startAutoVault() {
        var threshold = parseFloat($('#vaultThreshold').val());
        var interval = parseFloat($('#vaultInterval').val());

        if (threshold && interval) {
            $('#autoVaultList').append(`
                <li>Auto Vault started with Max Coins: ${threshold} and Interval: ${interval}ms</li>
            `);

            if (window.autoVaulterInterval) clearInterval(window.autoVaulterInterval);
            window.autoVaulterInterval = setInterval(() => {
                if (ss.wallet.dict[ss.wallet.current].amount > threshold) {
                    let amountToMove = ss.wallet.dict[ss.wallet.current].amount - threshold;
                    vaultMyCoin(ss.wallet.current, amountToMove.toFixed(6));
                }
            }, interval);
        } else {
            alert('Please enter valid Max Coins and Interval.');
        }
    }

    function stopAutoVault() {
        if (window.autoVaulterInterval) clearInterval(window.autoVaulterInterval);
    }

    function vaultMyCoin(theCoin, theAmount) {
        var fetchAddress = "https://" + window.location.host + "/api/vault/amount/recharge/";
        var referrerAddress = "https://" + window.location.host + "/wallet/vault";

        fetch(fetchAddress, {
            "headers": {
                "accept": "application/json, text/plain, */*",
                "accept-language": "en-US,en;q=0.9",
                "content-type": "application/json",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "same-origin",
                "sec-gpc": "1"
            },
            "referrer": referrerAddress,
            "referrerPolicy": "strict-origin-when-cross-origin",
            "body": `{"currencyName":"${theCoin}","amount":${theAmount}}`,
            "method": "POST",
            "mode": "cors",
            "credentials": "include"
        })
        .then(r => r.json())
        .then(r => {
            if (r.code) console.log(r);
        })
        .then(() => {
            totalVaultedThisSession += Number.parseFloat(theAmount);
            document.getElementById("vaultedAmount").innerText = totalVaultedThisSession.toFixed(6);
        })
        .catch(error => {
            console.log(error);
        });
    }

    // Function to make sections detachable
    function detachSection(sectionId, title) {
        var section = $(`#${sectionId}`);
        var detachedSection = section.detach().css({
            position: 'fixed',
            top: '10%',
            right: '10%',
            background: '#1e1e1e',
            border: '1px solid #444',
            padding: '10px',
            zIndex: '1002',
            maxHeight: '300px',
            overflowY: 'auto'
        }).attr('id', `${sectionId}Detached`);

        $('body').append(detachedSection);
        detachedSection.prepend(`<h3>${title} <span class="minimize">[-]</span></h3>`);

        detachedSection.find('.minimize').on('click', function() {
            $(`#${sectionId}Detached`).remove();
            var reattachedSection = $(`#${sectionId}Detached`);
            reattachedSection.attr('id', sectionId).appendTo('#mainMenu').hide();
        });

        detachedSection.draggable();
    }

    //===============================
    // Event Handlers
    //===============================

    // Toggle main menu visibility
    $('#menuButton').on('click', function() {
        $('#mainMenu').toggle();
    });

    // Toggle sections visibility
    $('#toggleBetResultsSection').on('click', function() {
        var section = $('#betResultsSection');
        if (!section.is(':visible')) {
            $('#mainMenu').find('.section').hide();
            section.show();
        } else {
            section.hide();
        }
    });

    $('#toggleTrackerSection').on('click', function() {
        var section = $('#trackerSection');
        if (!section.is(':visible')) {
            $('#mainMenu').find('.section').hide();
            section.show();
        } else {
            section.hide();
        }
    });

    $('#toggleAutoVaultSection').on('click', function() {
        var section = $('#autoVaultSection');
        if (!section.is(':visible')) {
            $('#mainMenu').find('.section').hide();
            section.show();
        } else {
            section.hide();
        }
    });

    // Detach sections
    $('#toggleBetResultsSection .detach').on('click', function() {
        detachSection('betResultsSection', 'Bet Results');
    });

    $('#toggleTrackerSection .detach').on('click', function() {
        detachSection('trackerSection', 'Payout Tracker');
    });

    $('#toggleAutoVaultSection .detach').on('click', function() {
        detachSection('autoVaultSection', 'Autovaulter V1.2');
    });

    // Make mainMenu draggable
    $('#mainMenu h3').on('mousedown touchstart', function(e) {
        var drag = $(this).parent().addClass('draggable');
        var drg_h = drag.outerHeight(),
            drg_w = drag.outerWidth(),
            pos_y = drag.offset().top + drg_h - e.pageY,
            pos_x = drag.offset().left + drg_w - e.pageX;
        $(document).on('mousemove touchmove', function(e) {
            $('.draggable').offset({
                top: e.pageY + pos_y - drg_h,
                left: e.pageX + pos_x - drg_w
            });
        });
        e.preventDefault(); // disable selection
    }).on('mouseup touchend', function() {
        $(this).parent().removeClass('draggable');
        $(document).off('mousemove touchmove');
    });

    // Tracker input change handling
    $('#trackerInput1, #trackerInput2, #trackerInput3').on('change', function() {
        var index = $(this).attr('id').replace('trackerInput', '') - 1;
        trackerStats[index].input = parseFloat($(this).val());
        trackerStats[index].lastSeen = null;
        trackerStats[index].hotCold = null;
        trackerStats[index].maxStreak = 0;
        trackerStats[index].currentStreak = 0;
        trackerStats[index].totalHits = 0;
        trackerStats[index].betsSinceHit = 0;
        trackerStats[index].alertsEnabled = $(`#alert${index + 1}`).is(':checked');
        trackerStats[index].intensity = parseFloat($(`#intensity${index + 1}`).val());
        updateTrackerDisplay();
    });

    $('#trackerInput1, #trackerInput2, #trackerInput3').on('input', function() {
        var index = $(this).attr('id').replace('trackerInput', '') - 1;
        trackerStats[index].alertsEnabled = $(`#alert${index + 1}`).is(':checked');
        trackerStats[index].intensity = parseFloat($(`#intensity${index + 1}`).val());
    });

    // Start Auto Vault button click
    $('#startAutoVault').on('click', startAutoVault);

    // Fetch recent bets immediately and then every 10 seconds
    fetchRecentBets();
    setInterval(fetchRecentBets, 10000);
};