Can you help me upgrade this so its an even more functional version than itself, its a keno betting script for nanogames.io that is initialized by the user by pasting it into the javascript console while on the website. I wanted to add better practical, correct  and working functionality to the target tracking portion of the menu as well, the logic isnt quite working how Im wanting it to, also add some logic to the autovault section to enable the user to be able to automatically vault a percentage of every winning bet, if they want to, bs vaulting over a certain  balance  they have in wallet,   Heres the script,       COMPREHENSIVE COMPLETE🤘🏾

(function () {
    'use strict';

    // **Encapsulate the entire script to avoid polluting the global namespace**
    const BettingTracker = (() => {
        // **Configuration**
        const CONFIG = {
            recentBetsApi: 'https://nanogames.io/api/single/game/v2/recent-bet/',
            exportFileName: 'bet_history.csv',
            autoVaultDefault: { threshold: 1000, interval: 60000 }, // Example default values
            fetchInterval: 10000, // 10 seconds
            maxBetHistory: 50, // Increased from 20 for more data
            profitThreshold: 100, // For notifications
            lossStreakThreshold: 5, // For notifications
        };

        // **Variables**
        let gameObject = null;
        let betHistory = [];
        let 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 }
        ];
        let totalVaultedThisSession = 0;
        let totalProfit = 0;
        let totalLoss = 0;
        let winCount = 0;
        let lossCount = 0;

        // **Utility Functions**
        const loadDependencies = () => {
            return new Promise(async (resolve, reject) => {
                try {
                    if (typeof window.jQuery === 'undefined') {
                        const jqScript = document.createElement('script');
                        jqScript.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
                        jqScript.type = 'text/javascript';
                        jqScript.onload = () => console.log('jQuery loaded.');
                        jqScript.onerror = () => reject(new Error('Failed to load jQuery.'));
                        document.head.appendChild(jqScript);
                        await new Promise(res => jqScript.onload = res);
                    } else {
                        console.log('jQuery already loaded.');
                    }

                    if (typeof window.jQuery.ui === 'undefined') {
                        const uiScript = document.createElement('script');
                        uiScript.src = 'https://code.jquery.com/ui/1.13.2/jquery-ui.min.js';
                        uiScript.type = 'text/javascript';
                        uiScript.onload = () => console.log('jQuery UI loaded.');
                        uiScript.onerror = () => reject(new Error('Failed to load jQuery UI.'));
                        document.head.appendChild(uiScript);

                        const uiLink = document.createElement('link');
                        uiLink.rel = 'stylesheet';
                        uiLink.href = 'https://code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css';
                        document.head.appendChild(uiLink);
                        await new Promise(res => uiScript.onload = res);
                    } else {
                        console.log('jQuery UI already loaded.');
                    }

                    resolve();
                } catch (error) {
                    reject(error);
                }
            });
        };

        const setGameObject = () => {
            const url = window.location.href;

            if (url.includes("/limbo") && typeof lbg !== 'undefined') {
                gameObject = lbg;
            } else if (url.includes("/hash-dice") && typeof hdg !== 'undefined') {
                gameObject = hdg;
            } else if (url.includes("/wheel") && typeof wlg !== 'undefined') {
                gameObject = wlg;
            } else if (url.includes("/classic-dice") && typeof cd !== 'undefined') {
                gameObject = cd;
            } else if (url.includes("/keno") && typeof dg !== 'undefined') {
                gameObject = dg;
            } else {
                console.error("Unrecognized or undefined game URL or game object");
                gameObject = null; // Explicitly set to null if not found
            }

            if (gameObject) {
                injectHotkeys();
            } else {
                console.warn("Game object is not set. Hotkeys will not be injected.");
            }
        };

        const injectHotkeys = () => {
            if (!gameObject || !gameObject.addHotkey) return;

            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");
            gameObject.addHotkey('P', switchPayout, "Switches payout to a random value");
        };

        const HalfUp = () => {
            try {
                const newAmount = gameObject.amount.mul(1.5);
                gameObject.setAmount(newAmount);
            } catch (error) {
                console.error('Error in HalfUp:', error);
            }
        };

        const HalfDown = () => {
            try {
                const newAmount = gameObject.amount.div(2.5);
                gameObject.setAmount(newAmount);
            } catch (error) {
                console.error('Error in HalfDown:', error);
            }
        };

        const DoManualBet = (increaseOnWin = false) => {
            try {
                gameObject.bet(gameObject.amount).then(() => {
                    const latestBet = gameObject.myBets[0];
                    if (latestBet && latestBet.profitAmount > 0 && increaseOnWin) {
                        const updatedAmount = gameObject.amount.mul(1.16); // Adjustable multiplier
                        gameObject.setAmount(updatedAmount);
                    }
                });
            } catch (error) {
                console.error('Error in DoManualBet:', error);
            }
        };

        const DoManualMinBet = () => {
            try {
                gameObject.bet(gameObject.minAmount);
            } catch (error) {
                console.error('Error in DoManualMinBet:', error);
            }
        };

        const switchPayout = () => {
            try {
                const payout = getRandomPayout();
                gameObject.payout = parseFloat(payout);
                console.log(`Payout switched: ${payout}`);
            } catch (error) {
                console.error('Error in switchPayout:', error);
            }
        };

        const getRandomPayout = () => {
            // Assuming a function that returns a random payout value
            return (Math.random() * (10 - 1) + 1).toFixed(2); // Example: between 1.00 and 10.00
        };

        const adjustButtonSizes = () => {
            const fontSize = '12px';
            const paddingVertical = '5px';
            const paddingHorizontal = '10px';
            const lineHeight = '1.2';

            $(".sc-kDTinF.bswIvI.button-group button").css({
                'font-size': fontSize,
                'padding': `${paddingVertical} ${paddingHorizontal}`,
                'line-height': lineHeight,
                'text-align': 'center',
                'min-width': '20px',
            });
        };

        const customizeButton = () => {
            const buttonX2 = $("button:contains('x2')");
            buttonX2.off('click').on('click', HalfUp);
        };

        const watchUrlChanges = () => {
            const originalPushState = history.pushState;
            const originalReplaceState = history.replaceState;

            history.pushState = function () {
                originalPushState.apply(history, arguments);
                setGameObject();
            };

            history.replaceState = function () {
                originalReplaceState.apply(history, arguments);
                setGameObject();
            };

            window.addEventListener('popstate', setGameObject);
        };

        const fetchRecentBets = () => {
            $.ajax({
                url: CONFIG.recentBetsApi,
                type: 'POST',
                data: JSON.stringify({ "gameName": "Limbo", "size": 50 }), // Increased size
                contentType: 'application/json',
                success: (response) => {
                    console.log("Fetched recent bets:", response);
                    if (response && response.data) {
                        response.data.forEach(bet => updateBetHistory(bet));
                    } else {
                        console.error("Unexpected API response format:", response);
                    }
                },
                error: (error) => console.error('Error fetching recent bets:', error)
            });
        };

        const updateBetHistory = (bet) => {
            try {
                // Log the bet object for debugging
                console.log("Received bet:", bet);

                // Check if required properties exist
                if (!bet || !bet.bv || typeof bet.bv.payout === 'undefined' || typeof bet.gv === 'undefined' || typeof bet.betAmount === 'undefined') {
                    console.error("Bet object is missing required properties:", bet);
                    return;
                }

                const target = (bet.bv.payout / 100).toFixed(2);
                const result = (bet.gv / 100).toFixed(2);
                const multiplier = result >= target ? target : 0;
                const isWinning = result >= target;
                const nonce = bet.nonce.toString().slice(-3);
                const profit = (bet.gv / 100) * parseFloat(bet.betAmount) - parseFloat(bet.betAmount);

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

                // Update overall stats
                if (profit > 0) {
                    totalProfit += profit;
                    winCount += 1;
                } else {
                    totalLoss += Math.abs(profit);
                    lossCount += 1;
                }

                betHistory.unshift(formattedBet);
                if (betHistory.length > CONFIG.maxBetHistory) {
                    betHistory.pop();
                }

                renderBetHistory();
                updateTrackerStats(formattedBet);
                updateStatistics();
            } catch (error) {
                console.error('Error in updateBetHistory:', error, bet);
            }
        };

        const renderBetHistory = () => {
            const betList = $('#betList');
            betList.empty();
            betHistory.forEach(bet => {
                const betClass = bet.multiplier > 0 ? 'winning' : 'losing';
                const highMultiplierClass = parseFloat(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>
                `);
            });
        };

        const updateTrackerStats = (bet) => {
            trackerStats.forEach((tracker, index) => {
                if (tracker.input && bet.result >= tracker.input) {
                    tracker.betsSinceHit = 0;
                    tracker.totalHits += 1;
                    tracker.currentStreak += 1;
                    if (tracker.currentStreak > tracker.maxStreak) {
                        tracker.maxStreak = tracker.currentStreak;
                    }
                    notifications.checkWinThreshold(totalProfit, CONFIG.profitThreshold);
                } else if (tracker.input) {
                    tracker.currentStreak = 0;
                    tracker.betsSinceHit += 1;

                    if (tracker.alertsEnabled && tracker.betsSinceHit >= Math.floor(tracker.input * tracker.intensity)) {
                        notifications.notify(`Multiplier ${tracker.input}x has not been seen for ${tracker.betsSinceHit} bets.`);
                        // Reset betsSinceHit or handle accordingly
                        tracker.betsSinceHit = 0; // Avoid repeated alerts
                    }

                    // Example Hot/Cold calculation
                    const expectedFrequency = betHistory.length / (tracker.totalHits || 1); // Avoid division by zero
                    tracker.hotCold = (tracker.totalHits > expectedFrequency) ? '🔥 Hot' : '❄️ Cold';
                }
            });
            renderTrackerDisplay();
        };

        const renderTrackerDisplay = () => {
            const 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>
                    `);
                }
            });
        };

        const updateStatistics = () => {
            $('#totalProfit').text(totalProfit.toFixed(2));
            $('#totalLoss').text(totalLoss.toFixed(2));
            $('#winRate').text(((winCount / (winCount + lossCount)) * 100).toFixed(2) + '%');
            $('#averageProfit').text((totalProfit / (winCount || 1)).toFixed(2));
        };

        const initializeUI = () => {
            // **Inject CSS Styles**
            const style = `
            <style>
                /* Updated Styles for Main Menu and Menu Button */
                #menuButton {
                    position: fixed;
                    left: 10px;
                    top: 10px;
                    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: 50px; /* Adjusted to below the menu button */
                    left: 10px; /* Align with menu button */
                    background: #1e1e1e;
                    color: #fff;
                    border: 1px solid #444;
                    width: 300px; /* Adjusted width for better fit */
                    max-height: 70vh; /* Max height relative to viewport */
                    overflow-y: auto; /* Enable scroll if content exceeds max height */
                    z-index: 1000;
                    font-size: 14px; /* Increased font size for readability */
                    display: none; /* Initially hidden */
                    font-family: 'Kanit', sans-serif;
                    box-shadow: 2px 2px 10px rgba(0,0,0,0.5);
                    border-radius: 5px;
                    transition: all 0.3s ease;
                }
                #mainMenu h3 {
                    margin-top: 0;
                    font-size: 16px;
                    cursor: move;
                    background: #2e2e2e;
                    padding: 10px;
                    border-bottom: 1px solid #444;
                    text-align: center;
                    border-radius: 5px 5px 0 0;
                }
                #mainMenu ul {
                    list-style-type: none;
                    padding-left: 0;
                    margin: 0;
                }
                #mainMenu li {
                    margin-bottom: 5px;
                    padding: 10px;
                    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: 10px;
                    right: 10px;
                    cursor: pointer;
                    font-size: 14px;
                }
                .section {
                    display: none;
                    padding: 10px;
                }
                .section input {
                    width: 80%;
                    margin-right: 10px;
                    padding: 5px;
                    border-radius: 3px;
                    border: 1px solid #555;
                }
                .section button {
                    padding: 5px 10px;
                    background-color: #444;
                    color: #fff;
                    border: none;
                    cursor: pointer;
                    border-radius: 3px;
                }
                .section button:hover {
                    background-color: #555;
                }
                .section-title {
                    cursor: pointer;
                    background: #333;
                    padding: 10px;
                    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;
                    font-size: 16px;
                }
                .autoVault-input, .tracker-input {
                    margin-bottom: 10px;
                }
                .alert-checkbox {
                    margin-right: 5px;
                }
                .intensity-input {
                    width: 40px;
                    margin-left: 10px;
                    padding: 5px;
                    border-radius: 3px;
                    border: 1px solid #555;
                }

                /* Additional Styles for New Features */
                #statisticsSection {
                    padding: 10px;
                    border-bottom: 1px solid #444;
                }
                #statisticsSection h4 {
                    margin: 5px 0;
                }
                .export-button, .import-button {
                    margin-top: 10px;
                    padding: 8px 12px;
                    background-color: #444;
                    color: #fff;
                    border: none;
                    cursor: pointer;
                    border-radius: 3px;
                    width: 100%;
                }
                .export-button:hover, .import-button:hover {
                    background-color: #555;
                }
                /* Dark Mode Styles */
                body.dark-mode {
                    background-color: #121212 !important;
                    color: #e0e0e0;
                }
                body.dark-mode #mainMenu {
                    background: #1e1e1e;
                }
                /* Responsive Enhancements */
                @media (max-width: 768px) {
                    #mainMenu {
                        width: 90%;
                        left: 5%;
                    }
                }
                /* Tooltip Styles */
                .tooltip {
                    position: relative;
                    display: inline-block;
                }
                .tooltip .tooltiptext {
                    visibility: hidden;
                    width: 150px;
                    background-color: #555;
                    color: #fff;
                    text-align: center;
                    border-radius: 6px;
                    padding: 5px 0;
                    position: absolute;
                    z-index: 1;
                    bottom: 125%; /* Position above the button */
                    left: 50%;
                    margin-left: -75px;
                    opacity: 0;
                    transition: opacity 0.3s;
                }
                .tooltip:hover .tooltiptext {
                    visibility: visible;
                    opacity: 1;
                }
            </style>
            `;
            $('head').append(style);

            // **Create Main Menu HTML**
            const mainMenuHTML = `
            <div id="menuButton" class="tooltip">☰ Menu
                <span class="tooltiptext">Open Betting Tracker Menu</span>
            </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>
                    <button id="exportBetHistory" class="export-button">Export Bet History</button>
                </div>
                <div class="section-title" id="toggleTrackerSection">📈 Payout Tracker<span class="detach">⎋</span></div>
                <div id="trackerSection" class="section">
                    ${generateTrackerInputs()}
                    <ul id="trackerList"></ul>
                </div>
                <div class="section-title" id="toggleAutoVaultSection">💰 Autovaulter V1.2<span class="detach">⎋</span></div>
                <div id="autoVaultSection" class="section">
                    ${generateAutoVaultInputs()}
                </div>
                <div class="section-title" id="toggleStatisticsSection">📊 Statistics<span class="detach">⎋</span></div>
                <div id="statisticsSection" class="section">
                    <h4>Total Profit: <span id="totalProfit">0.00</span></h4>
                    <h4>Total Loss: <span id="totalLoss">0.00</span></h4>
                    <h4>Win Rate: <span id="winRate">0.00%</span></h4>
                    <h4>Average Profit per Win: <span id="averageProfit">0.00</span></h4>
                    <button id="exportSettings" class="export-button">Export Settings</button>
                    <button id="importSettings" class="import-button">Import Settings</button>
                    <br><br>
                    <label class="tooltip">Dark Mode
                        <input type="checkbox" id="darkModeToggle">
                        <span class="tooltiptext">Toggle Dark Mode</span>
                    </label>
                </div>
            </div>
            `;
            $('body').append(mainMenuHTML);

            // **Initialize Draggable after mainMenu is appended**
            $('#mainMenu').draggable({
                handle: 'h3', // Specify the handle for dragging
                containment: 'window' // Restrict dragging within the window
            });

            // **Attach Event Handlers**
            attachEventHandlers();
        };

        const generateTrackerInputs = () => {
            let inputs = '';
            trackerStats.forEach((tracker, index) => {
                inputs += `
                <div class="tracker-input">
                    <input type="number" id="trackerInput${index + 1}" placeholder="Track ${index + 1}">
                    <label><input type="checkbox" id="alert${index + 1}" class="alert-checkbox" checked>Alert</label>
                    <input type="number" id="intensity${index + 1}" class="intensity-input" value="${tracker.intensity}">
                </div>
                `;
            });
            return inputs;
        };

        const generateAutoVaultInputs = () => {
            const storedSettings = JSON.parse(localStorage.getItem('autoVaultSettings')) || CONFIG.autoVaultDefault;
            return `
                <div class="autoVault-input">
                    <input type="number" id="vaultThreshold" placeholder="Max Coins" value="${storedSettings.threshold}">
                    <input type="number" id="vaultInterval" placeholder="Interval (ms)" value="${storedSettings.interval}">
                    <button id="startAutoVault">Start Auto Vault</button>
                    <button id="stopAutoVault">Stop Auto Vault</button>
                </div>
                <ul id="autoVaultList"></ul>
                <h4>Total Vaulted This Session: <span id="vaultedAmount">0.000000</span></h4>
            `;
        };

        const attachEventHandlers = () => {
            // **Menu Toggle**
            $('#menuButton').on('click', () => {
                $('#mainMenu').toggle();
            });

            // **Section Toggles**
            $('#toggleBetResultsSection').on('click', () => toggleSection('betResultsSection'));
            $('#toggleTrackerSection').on('click', () => toggleSection('trackerSection'));
            $('#toggleAutoVaultSection').on('click', () => toggleSection('autoVaultSection'));
            $('#toggleStatisticsSection').on('click', () => toggleSection('statisticsSection'));

            // **Detach Sections**
            $('.section-title').find('.detach').on('click', function (e) {
                e.stopPropagation(); // Prevent triggering the section toggle
                const sectionId = $(this).parent().attr('id').replace('toggle', '').replace('Section', '');
                detachSection(`${sectionId}Section`, $(this).parent().text().trim());
            });

            // **Export Bet History**
            $('#exportBetHistory').on('click', exportBetHistory);

            // **Export/Import Settings**
            $('#exportSettings').on('click', exportSettings);
            $('#importSettings').on('click', () => {
                $('#importSettings').html('<input type="file" id="importFile" accept="application/json">');
                $('#importFile').on('change', handleImportSettings);
            });

            // **Dark Mode Toggle**
            $('#darkModeToggle').on('change', toggleDarkMode);

            // **Auto Vault Controls**
            $('#startAutoVault').on('click', startAutoVault);
            $('#stopAutoVault').on('click', stopAutoVault);

            // **Tracker Inputs**
            $('#trackerInput1, #trackerInput2, #trackerInput3').on('change', handleTrackerInputChange);
            $('#trackerInput1, #trackerInput2, #trackerInput3').on('input', handleTrackerInputInput);
        };

        const toggleSection = (sectionId) => {
            $(`#${sectionId}`).toggle();
        };

        const detachSection = (sectionId, title) => {
            const section = $(`#${sectionId}`);
            const detachedSection = section.detach().css({
                position: 'fixed',
                top: '20%',
                left: '20%',
                background: '#1e1e1e',
                border: '1px solid #444',
                padding: '10px',
                zIndex: '1002',
                maxHeight: '400px',
                overflowY: 'auto',
                width: '300px'
            }).addClass('detached-section');

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

            detachedSection.find('.minimize').on('click', function () {
                const parent = $(this).parent().parent();
                parent.removeClass('detached-section').css({
                    position: '',
                    top: '',
                    left: '',
                    background: '',
                    border: '',
                    padding: '',
                    zIndex: '',
                    maxHeight: '',
                    width: '',
                    overflowY: ''
                }).detach().appendTo('#mainMenu').hide();
                toggleSection(sectionId); // Hide the section after reattaching
            });

            makeDraggable(detachedSection);
        };

        const makeDraggable = (element) => {
            element.draggable({
                handle: 'h3',
                containment: 'window'
            });
        };

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

            // Reset tracker stats
            trackerStats[index].lastSeen = null;
            trackerStats[index].hotCold = null;
            trackerStats[index].maxStreak = 0;
            trackerStats[index].currentStreak = 0;
            trackerStats[index].totalHits = 0;
            trackerStats[index].betsSinceHit = 0;

            renderTrackerDisplay();
        };

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

        const startAutoVault = () => {
            const threshold = parseFloat($('#vaultThreshold').val());
            const interval = parseFloat($('#vaultInterval').val());

            if (threshold && interval) {
                $('#autoVaultList').append(`
                    <li>Auto Vault started with Max Coins: ${threshold} and Interval: ${interval}ms</li>
                `);
                saveAutoVaultSettings(threshold, interval);
                window.autoVaulterInterval = setInterval(() => {
                    try {
                        if (typeof ss !== 'undefined' && ss.wallet && ss.wallet.dict && ss.wallet.current && typeof ss.wallet.dict[ss.wallet.current].amount !== 'undefined') {
                            if (ss.wallet.dict[ss.wallet.current].amount > threshold) {
                                const amountToMove = ss.wallet.dict[ss.wallet.current].amount - threshold;
                                vaultMyCoin(ss.wallet.current, amountToMove.toFixed(6));
                            }
                        } else {
                            console.warn("ss.wallet.dict or related properties are undefined.");
                        }
                    } catch (error) {
                        console.error('Error in Auto Vault Interval:', error);
                    }
                }, interval);
            } else {
                alert('Please enter valid Max Coins and Interval.');
            }
        };

        const stopAutoVault = () => {
            if (window.autoVaulterInterval) {
                clearInterval(window.autoVaulterInterval);
                $('#autoVaultList').append(`<li>Auto Vault stopped.</li>`);
            }
        };

        const saveAutoVaultSettings = (threshold, interval) => {
            const settings = { threshold, interval };
            localStorage.setItem('autoVaultSettings', JSON.stringify(settings));
        };

        const vaultMyCoin = (theCoin, theAmount) => {
            const fetchAddress = `https://${window.location.host}/api/vault/amount/recharge/`;
            const 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: JSON.stringify({ "currencyName": theCoin, "amount": parseFloat(theAmount) }),
                method: "POST",
                mode: "cors",
                credentials: "include"
            })
                .then(r => r.json())
                .then(r => {
                    if (r.code) console.log(r);
                })
                .then(() => {
                    totalVaultedThisSession += parseFloat(theAmount);
                    $('#vaultedAmount').text(totalVaultedThisSession.toFixed(6));
                })
                .catch(error => console.error('Error in vaultMyCoin:', error));
        };

        const exportBetHistory = () => {
            let csvContent = "data:text/csv;charset=utf-8,";
            csvContent += "Bet Size,Nonce,Target,Result,Multiplier,Profit\n";
            betHistory.forEach(bet => {
                const row = [bet.betSize, bet.nonce, bet.target, bet.result, bet.multiplier, bet.profit].join(",");
                csvContent += row + "\n";
            });
            const encodedUri = encodeURI(csvContent);
            const link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", CONFIG.exportFileName);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        };

        const exportSettings = () => {
            const settings = {
                trackerStats,
                autoVaultSettings: JSON.parse(localStorage.getItem('autoVaultSettings')) || CONFIG.autoVaultDefault
            };
            const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(settings, null, 2));
            const downloadAnchorNode = document.createElement('a');
            downloadAnchorNode.setAttribute("href", dataStr);
            downloadAnchorNode.setAttribute("download", "bet_tracker_settings.json");
            document.body.appendChild(downloadAnchorNode);
            downloadAnchorNode.click();
            downloadAnchorNode.remove();
        };

        const handleImportSettings = (event) => {
            const file = event.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const importedSettings = JSON.parse(e.target.result);
                    if (importedSettings.trackerStats && importedSettings.autoVaultSettings) {
                        trackerStats = importedSettings.trackerStats;
                        localStorage.setItem('autoVaultSettings', JSON.stringify(importedSettings.autoVaultSettings));
                        renderTrackerDisplay();
                        // Update Auto Vault inputs
                        $('#vaultThreshold').val(importedSettings.autoVaultSettings.threshold);
                        $('#vaultInterval').val(importedSettings.autoVaultSettings.interval);
                        alert('Settings imported successfully.');
                    } else {
                        throw new Error('Invalid settings format.');
                    }
                } catch (error) {
                    console.error('Error importing settings:', error);
                    alert('Failed to import settings. Please check the file format.');
                }
            };
            reader.readAsText(file);
        };

        const toggleDarkMode = () => {
            $('body').toggleClass('dark-mode', $('#darkModeToggle').is(':checked'));
            // Save preference
            localStorage.setItem('darkMode', $('#darkModeToggle').is(':checked'));
        };

        const notifications = {
            notify: (message) => {
                if (Notification.permission === 'granted') {
                    new Notification('Betting Tracker Alert', { body: message });
                } else if (Notification.permission !== 'denied') {
                    Notification.requestPermission().then(permission => {
                        if (permission === 'granted') {
                            new Notification('Betting Tracker Alert', { body: message });
                        }
                    });
                }
            },
            checkWinThreshold: (profit, threshold) => {
                if (profit >= threshold) {
                    notifications.notify(`Congratulations! You've reached a profit of ${profit.toFixed(2)}.`);
                }
            }
        };

        const initializeNotifications = () => {
            if ("Notification" in window) {
                if (Notification.permission !== "granted" && Notification.permission !== "denied") {
                    Notification.requestPermission();
                }
            }
        };

        const initializeLocalStorage = () => {
            // Load saved settings if any
            const savedTrackers = JSON.parse(localStorage.getItem('trackerStats'));
            if (savedTrackers) {
                trackerStats = savedTrackers;
            }

            // Load Auto Vault settings
            const autoVaultSettings = JSON.parse(localStorage.getItem('autoVaultSettings'));
            if (autoVaultSettings) {
                $('#vaultThreshold').val(autoVaultSettings.threshold);
                $('#vaultInterval').val(autoVaultSettings.interval);
            }

            // Load Dark Mode preference
            const darkMode = JSON.parse(localStorage.getItem('darkMode')) || false;
            $('#darkModeToggle').prop('checked', darkMode);
            toggleDarkMode();
        };

        const attachBeforeUnloadHandler = () => {
            window.addEventListener('beforeunload', () => {
                // Save tracker and Auto Vault settings on page unload
                localStorage.setItem('trackerStats', JSON.stringify(trackerStats));
                const autoVaultSettings = {
                    threshold: parseFloat($('#vaultThreshold').val()),
                    interval: parseFloat($('#vaultInterval').val())
                };
                localStorage.setItem('autoVaultSettings', JSON.stringify(autoVaultSettings));
                localStorage.setItem('darkMode', $('#darkModeToggle').is(':checked'));
            });
        };

        // **Persisting Data**
        const persistData = () => {
            localStorage.setItem('betHistory', JSON.stringify(betHistory));
            // Additional persistence as needed
        };

        const loadPersistedData = () => {
            const savedBetHistory = JSON.parse(localStorage.getItem('betHistory'));
            if (savedBetHistory && Array.isArray(savedBetHistory)) {
                betHistory = savedBetHistory;
                renderBetHistory();
            }
        };

        // **Initialization**
        const init = async () => {
            try {
                console.log("Initializing Betting Tracker...");
                await loadDependencies();
                console.log("Dependencies loaded.");
                initializeLocalStorage();
                initializeNotifications();
                loadPersistedData();
                setGameObject();
                watchUrlChanges();
                customizeButton();
                adjustButtonSizes();
                initializeUI();
                attachBeforeUnloadHandler();
                fetchRecentBets();
                setInterval(fetchRecentBets, CONFIG.fetchInterval);
                console.log("Betting Tracker initialized successfully.");
                showStatusMessage("Betting Tracker Initialized Successfully.");
            } catch (error) {
                console.error('Initialization error:', error);
                showStatusMessage("Betting Tracker Initialization Failed.");
            }
        };

        // **Show Status Message**
        const showStatusMessage = (message) => {
            const existingMessage = $('#btStatusMessage');
            if (existingMessage.length) {
                existingMessage.remove();
            }
            const statusDiv = $('<div id="btStatusMessage"></div>').css({
                position: 'fixed',
                bottom: '10px',
                right: '10px',
                background: '#444',
                color: '#fff',
                padding: '10px',
                borderRadius: '5px',
                zIndex: '1003',
                opacity: '0.8'
            }).text(message);
            $('body').append(statusDiv);
            setTimeout(() => {
                statusDiv.fadeOut(500, () => statusDiv.remove());
            }, 3000);
        };

        // **Expose Public Methods (if needed)**
        return {
            init
        };
    })();

    // **Initialize Notifications Permission**
    if ("Notification" in window && Notification.permission !== "granted" && Notification.permission !== "denied") {
        Notification.requestPermission().then(permission => {
            if (permission === "granted") {
                console.log("Notification permission granted.");
            }
        });
    }

    // **Initialize the Betting Tracker**
    BettingTracker.init();

})();