let fisher_bet_array = new Map();
let useTotalLossFlag = true;


let default_balance_values = [
    "0, 5, 8, 10, 11, 23, 30",
    "0, 2, 3, 5, 32",
    "0, 1, 3, 5, 17, 29, 35",
    "0, 1, 2, 5",
    "2, 6, 7, 8, 28, 29",
    "0, 2, 8, 10, 25",
    "4, 8, 7, 28, 29",
    "4, 10, 14, 27",
    "0, 4, 5, 6, 10, 28",
    "0, 5, 6, 14, 29, 31",
    "0, 5, 7, 8, 13, 20",
    "0, 8, 12, 14, 22, 29",
    "0, 11, 14, 15, 21",
    "0, 2, 10, 29, 31",
    "7, 11, 12, 16, 20",
    "0, 12, 18, 30",
    "0, 18, 19, 32",
    "0, 2, 20, 29, 32, 35",
    "0, 15, 16, 19, 21",
    "0, 16, 18, 20",
    "0, 10, 17, 23",
    "0, 12, 18, 20",
    "11, 23, 24, 28, 29",
    "0, 5, 8, 10, 11, 26, 30, 32",
    "22, 23, 28, 29",
    "0, 5, 27, 29",
    "0, 6, 7, 23, 28, 29",
    "0, 7, 25, 28, 29, 30",
    "0, 6, 8, 31, 32",
    "0, 8, 11, 17, 30, 32",
    "0, 8, 10, 11, 23, 15, 27",
    "0, 2, 13, 28, 33",
    "0, 1, 16, 28, 34, 36",
    "0, 2, 31, 35",
    "2, 17, 25, 29, 32",
    "0, 2, 17, 29, 32, 33", 
    "0, 11, 33, 34, 35", 
    "" // Empty strings for values 33 to 36
];

let balance_values = [...default_balance_values];

function sim_fisher_history_table() {
    const container = document.createElement('div');
    container.id = 'chart';


    container.innerHTML = '<span class="title">History</span>'; // Clear the container
    

    // Create a table element
    const table = document.createElement('table');
    table.style.width = '100%';
    table.style.borderCollapse = 'collapse';
    table.style.marginTop = '10px';

    // Add a header row
    const headerRow = document.createElement('tr');
    const headers = ["Spin", "#", "W/L",  "Bet Amount", "Wager", "Bet Location", "Session","Session Wager","Won","Profit", "Bank"];
    headers.forEach(headerText => {
        const th = document.createElement('th');
        th.textContent = headerText;
        th.style.border = '1px solid #000';
        th.style.padding = '8px';
        th.style.backgroundColor = '#f4f4f4';
        th.style.textAlign = 'center';
        headerRow.appendChild(th);
    });
    table.appendChild(headerRow);

    // Call another function to populate table rows
    sim_fisher_history_table_data(table);

    // Append the table to the container
    container.appendChild(table);

    return container;
  
}


function sim_fisher_history_table_data(table) {

    

     var betValueElement = document.getElementById('baseBet');
            var betValue = parseInt(betValueElement.value, 10);
       
            // Validate betValue
            if (isNaN(betValue) || betValue <= 0) {
                betValue = 1;
                betValueElement.value = betValue; // Update the input field to reflect the corrected value
            }

    let currentBet = betValue; // Initial bet amount



    undoButtonPressed = false;

    let sessionCount = 1;
    let bank = 0;
    let sessionSpinCount = 0;

    let placingBetInd = false;

  

    let winOnce = false;

    let next_bet_numbers = [];
    let running_bank_session = 0;
    let running_bank = 0;

    let wager_amount = 0;




    numbers.forEach((n, index) => {


        var converted_n = isZero0(n)? "0": isZero00(n)? "00": n;
        var number_color = isRed(n) ? "red": isBlack(n) ? "black": "green";

        var wonLoss = next_bet_numbers.includes(n);
        running_bank -= wager_amount;


        if(placingBetInd)
        {
            sessionSpinCount+=1;
          
        }

        if(wonLoss)
        {
            running_bank += currentBet*35+currentBet;
        }

        var tableWinAmount = placingBetInd && wonLoss? (currentBet*35) : "";
        // "Spin", "#", "W/L",  "Bet Amount", "Bet Location", "Session", "Session Bank", "Bank"
        var data_spin = index + 1;
        var data_number_up = `<span style="color: ${number_color}">${converted_n}</span>`;
        var data_win_loss = placingBetInd == true? wonLoss?"W":"L": "";
        var data_bet_amount = placingBetInd == true?  currentBet: '';
        var data_bet_location = next_bet_numbers.map(n => n === 37 ? "00" : n).join(", ");
       // var data_bet_location = next_bet_numbers.join(", ");
  

        var data_session =  placingBetInd? wonLoss? sessionCount+' End' : sessionCount + ' ('+ sessionSpinCount+')':"";

        
        var data_wager = placingBetInd? wager_amount:"";
        var data_session_wager = placingBetInd? running_bank_session:"";
        var data_won_amount = placingBetInd && wonLoss? tableWinAmount:"";
        var data_profit = placingBetInd && wonLoss? running_bank_session+(currentBet*35+ currentBet):"";

        var data_session_bank = placingBetInd? wager_amount + " ("+running_bank_session+") "+tableWinAmount:"";



        var data_bank = running_bank;




        const rowData = {
            spin: data_spin,
            numberUp: data_number_up,
            winLoss: data_win_loss,
            betAmount: data_bet_amount,
            betLocation: data_bet_location,
            session: data_session, 
            wager: data_wager,
            sessionWager: data_session_wager,
            wonAmount: data_won_amount,
            profit: data_profit,
            bank: data_bank 
        };

        // Create a table row and populate it with cells
        const row = document.createElement('tr');
        const cells = [rowData.spin, 
                    rowData.numberUp, 
                    rowData.winLoss, 
                    rowData.betAmount, 
                    rowData.wager, 
                    rowData.betLocation, 
                    rowData.session, 
                    rowData.sessionWager, 
                    rowData.wonAmount, 
                    rowData.profit, 
                    rowData.bank];

        let isWin = false;

        cells.forEach((cellData, cellIndex) => {
            const td = document.createElement('td');

            if (cellIndex === 2 && cellData === "W") {  // 2 is the index of `winLoss`
                isWin = true;  // Mark row for green background
            }

            if (cellIndex === 1) { // Assuming 'num' is the second column (index 1)
                // Use innerHTML for 'num' column to render the colored span
                td.innerHTML = cellData;
            } else if (cellIndex === 5) { // History column
                // Use innerHTML to render crossed-out bets in the history column
                td.innerHTML = cellData;
            } else if (cellIndex === 6) { // History column
                // Use innerHTML to render crossed-out bets in the history column
                td.innerHTML = cellData;
            } else {
                // Use textContent for other columns
                td.textContent = cellData;
            }

            td.style.border = '1px solid #000';
            td.style.padding = '8px';
            td.style.textAlign = 'center';

            row.appendChild(td);
        });
        if (isWin) {
            row.style.backgroundColor = "#b0f5bb";
        }
        // Append the row to the table
        table.appendChild(row);
        
        // END OF ROUND
        next_bet_numbers = processBulkNumbers(balance_values[n]);

        wager_amount = next_bet_numbers.length * currentBet;

        
        running_bank_session = wonLoss? 0 : running_bank_session;

        if(wonLoss)
        {
            sessionSpinCount = 0;   
            sessionCount += 1;
            currentBet = betValue;
        }
        


        // wage set on table for next spin
        running_bank_session -= wager_amount;
        if(keepProfit)
            {   

                while((currentBet*35+currentBet)+running_bank_session<=0)
                {
                    currentBet++;

                    running_bank_session +=wager_amount;
                    wager_amount = next_bet_numbers.length * currentBet;
                    running_bank_session -= wager_amount;
                    if(currentBet>500) break;
                }
            }

        placingBetInd = true;

        chart_place_bet(next_bet_numbers,currentBet);

    });
}



function display_last_row_history() {
    // Find the table generated by sim_fisher_history_table
    const table = document.getElementById('chart').querySelector('table');

    if (!table || table.rows.length < 2) {
        // If the table or rows are missing, return a placeholder
        const placeholder = document.createElement('div');
        placeholder.textContent = "No data available in history.";
        return placeholder;
    }

    // Create a new container for the one-row table
    const container = document.createElement('div');
    container.id = 'last-row-chart';

    container.innerHTML = '<span class="title">Last Spin Results</span>';

    // Create a new table element
    const oneRowTable = document.createElement('table');
    oneRowTable.style.width = '100%';
    oneRowTable.style.borderCollapse = 'collapse';
    oneRowTable.style.marginTop = '10px';

    // Copy the header row from the original table
    const headerRow = table.rows[0].cloneNode(true);
    oneRowTable.appendChild(headerRow);

    // Copy the last data row from the original table
    const lastRow = table.rows[table.rows.length - 1].cloneNode(true);
    oneRowTable.appendChild(lastRow);

    // Append the one-row table to the container
    container.appendChild(oneRowTable);

    return container;
}




function chart_place_bet(bet_numbers,amount) {
 
    betArray  = new Map();
    bet_numbers.forEach(n => {
        place_bet_straight_number(betArray, n.toString(), amount);
    });
 
}


function settings(event) {
    // Check if the popup already exists
    if (document.querySelector('.popup')) {
        return; // Exit if the popup is already open
    }

    const popupDiv = document.createElement('div');
    popupDiv.classList.add('popup');
    popupDiv.style.position = 'absolute';
    popupDiv.style.top = `${event.clientY}px`; // Y position based on cursor
    popupDiv.style.left = `${event.clientX}px`; // X position based on cursor
    popupDiv.style.border = '1px solid #ccc';
    popupDiv.style.backgroundColor = '#fff';
    popupDiv.style.padding = '20px';
    popupDiv.style.zIndex = '1000';
    popupDiv.style.boxShadow = '0px 0px 10px rgba(0, 0, 0, 0.5)';
    popupDiv.style.display = 'inline-block'; // Allow the popup to grow/shrink based on content
    popupDiv.style.overflow = 'visible'; // Prevent scrollbars unless necessary

    // "Default" Button
    const defaultButton = document.createElement('button');
    defaultButton.textContent = 'Restore Default';
    defaultButton.className = 'button-55';
    defaultButton.style.marginTop = '10px';
    defaultButton.style.backgroundColor = '#cfddfa';
   
    defaultButton.onclick = function () {
        balance_values = [...default_balance_values]; // Restore default values
        document.body.removeChild(popupDiv); // Close and reopen to reflect defaults
        settings(event);
    };
    popupDiv.appendChild(defaultButton);

    // Close Button
    const closeButton = document.createElement('button');
    closeButton.textContent = 'Close';
    closeButton.className = 'button-55';
    closeButton.style.marginTop = '10px';
    closeButton.style.marginLeft = '10px';
    closeButton.style.backgroundColor = '#fceae8';
    closeButton.onclick = function () {
        document.body.removeChild(popupDiv);
    };
    popupDiv.appendChild(closeButton);

    const title = document.createElement('h3');
    title.textContent = 'Settings';
    popupDiv.appendChild(title);

    // Create the table
    const table = document.createElement('table');
    table.style.width = '100%';
    table.style.borderCollapse = 'collapse';

    // Table Header
    const headerRow = document.createElement('tr');
    const keyHeader = document.createElement('th');
    keyHeader.textContent = 'Number Up';
    const valueHeader = document.createElement('th');
    valueHeader.textContent = 'Numbers to bet on';
    headerRow.appendChild(keyHeader);
    headerRow.appendChild(valueHeader);
    table.appendChild(headerRow);

    // Table Rows
    balance_values.forEach((value, index) => {
        const row = document.createElement('tr');

        // Key Column
        const keyCell = document.createElement('td');
        
        keyCell.textContent = index; // Non-editable key
        if(index == 37) keyCell.textContent = "00";
        keyCell.style.border = '1px solid #ddd';
        keyCell.style.padding = '8px';
        keyCell.style.textAlign = 'center';
        keyCell.style.fontSize = '18px';
        row.appendChild(keyCell);

// Value Column (Editable)
const valueCell = document.createElement('td');
const input = document.createElement('input');
input.type = 'text';
input.value = value;
input.style.width = '100%';  // Ensures the input takes up the full width of the cell
input.style.fontSize = '18px';  // Increase font size for better readability
input.style.padding = '10px';  // Add padding to make the input field taller
input.style.height = '40px';  // Set a consistent height for the input field
input.style.borderRadius = '5px';  // Add rounded corners for better aesthetics
input.style.border = '1px solid #aaa';  // Slightly darker border for visibility
input.oninput = function () {
    balance_values[index] = input.value; // Update the balance_values when the input changes



};
valueCell.appendChild(input);

// Style for the valueCell itself
valueCell.style.border = '1px solid #ddd';
valueCell.style.padding = '16px';  // Increase padding for more spacing around the input field
row.appendChild(valueCell);

        table.appendChild(row);
    });

    popupDiv.appendChild(table);

    

    // Append to the body
    document.body.appendChild(popupDiv);
}




/*
function addProfitEntry(bets) {
    // Filter out entries where "amt" is 0 or less
    const filteredBets = bets.filter(bet => bet.amt > 0);

    // Calculate the total sum of all "amt" in the filtered array
    const totalAmt = filteredBets.reduce((sum, bet) => sum + bet.amt, 0);

    // Add "profit" entry for each bet based on the formula
    return filteredBets.map(bet => {
        bet.profit = bet.amt * bet.odds - totalAmt + bet.amt;
        return bet;
    });
}
*/

function addProfitEntry_old(bets) {
    const frequencyMap = new Map(); // Track the frequency of each number
    let betsPlaced = bets.map(bet => ({ ...bet }));
    betsPlaced = betsPlaced.filter(bet => bet.amt > 0);

    // Build frequency map
    betsPlaced.forEach(bet => {
        const nums = bet.numbers.split(',').map(num => parseInt(num.trim()));  // Split and convert to integers
        nums.forEach(num => {
            frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1);  // Count occurrences
        });
    });

    let profits = new Array(37).fill(0);

    // Calculate profits/losses based on bets
    betsPlaced.forEach(bet => {
        const betNumbers = bet.numbers.split(',').map(num => parseInt(num.trim()));
        const betProfit = bet.amt * bet.odds;

        for (let number = 0; number <= 36; number++) {
            if (betNumbers.includes(number)) {
                // Profit for the numbers included in the bet
                profits[number] += betProfit;
            } else {
                // Loss for the numbers not included in the bet
                profits[number] -= bet.amt;
            }
        }
    });

    // Build the grouped profit display
    let results = betsPlaced.map(bet => {
        const betNumbers = bet.numbers.split(',').map(num => parseInt(num.trim()));
        let profitGroups = {};

        // Group numbers by profit value
        betNumbers.forEach(number => {
            let profit = profits[number];
            if (!profitGroups[profit]) {
                profitGroups[profit] = [];
            }
            profitGroups[profit].push(number);
        });

        // Create a readable display format with bold profit
        let formattedProfit = Object.entries(profitGroups)
            .map(([profit, numbers]) => `<strong>${profit}:</strong> ${numbers.join(', ')}`)
            .join(' | ');  // Separate different profit groups by " | "

        return {
            ...bet,
            formattedProfit: formattedProfit  // Add the formatted profit string to the bet object
        };
    });

    return results;
}

function addProfitEntry(bets) {
    const frequencyMap = new Map(); // Track the frequency of each number
    let betsPlaced = bets.map(bet => ({ ...bet }));
    betsPlaced = betsPlaced.filter(bet => bet.amt > 0);

    // Build frequency map
    betsPlaced.forEach(bet => {
        const nums = bet.numbers.split(',').map(num => parseInt(num.trim()));  // Split and convert to integers
        nums.forEach(num => {
            frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1);  // Count occurrences
        });
    });

    // Initialize profits with totalLoss instead of 0
    if(totalLost>0) totalLost = 0;
    let startAmount = useTotalLossFlag? totalLost : 0;
    let profits = new Array(37).fill(startAmount);  // Start with negative totalLoss for all numbers

    // Calculate profits/losses based on bets
    betsPlaced.forEach(bet => {
        const betNumbers = bet.numbers.split(',').map(num => parseInt(num.trim()));
        const betProfit = bet.amt * bet.odds;

        for (let number = 0; number <= 36; number++) {
            if (betNumbers.includes(number)) {
                // Profit for the numbers included in the bet
                profits[number] += betProfit;  // Add the original bet back when it wins
            } else {
                // Loss for the numbers not included in the bet
                profits[number] -= bet.amt;
            }
        }
    });

    // Build the grouped profit display
    let results = betsPlaced.map(bet => {
        const betNumbers = bet.numbers.split(',').map(num => parseInt(num.trim()));
        let profitGroups = {};

        // Group numbers by profit value
        betNumbers.forEach(number => {
            let profit = profits[number];
            if (!profitGroups[profit]) {
                profitGroups[profit] = [];
            }
            profitGroups[profit].push(number);
        });

        // Create a readable display format with bold profit
        let formattedProfit = Object.entries(profitGroups)
            .map(([profit, numbers]) => `<strong>${profit}:</strong> ${numbers.join(', ')}`)
            .join(' | ');  // Separate different profit groups by " | "

        return {
            ...bet,
            formattedProfit: formattedProfit  // Add the formatted profit string to the bet object
        };
    });

    return results;
}




function getAllBets() {

    // Highlight
    spin_profit_unhighlight();
    console.log('Array:', spin_profit_uniques_array);
console.log('Length:', spin_profit_uniques_array.length);

    if(spin_profit_uniques_checkbox)
    {
        spin_profit_highlight();
   
       
    }



    var temp_bet = bet.map(bet => ({ ...bet }));

    // Create a container div
    const div = document.createElement('div');
    div.classList.add('bet-table-container');

 const uniquesSpanttt = document.createElement('span');
uniquesSpanttt.id = 'spin_profit_uniques_span4';
uniquesSpanttt.textContent = 'Place a bet to see profits';
uniquesSpanttt.style.fontWeight = 'bold';
uniquesSpanttt.style.marginBottom = '10px';
uniquesSpanttt.style.display = 'block';
uniquesSpanttt.style.fontSize = '16px';

// Add it at the top of the container
div.insertBefore(uniquesSpanttt, div.firstChild);

        // === NEW: Placeholder span for dynamic content ===
    const uniquesSpan = document.createElement('span');
    uniquesSpan.id = 'spin_profit_uniques_span';
    uniquesSpan.style.marginLeft = '10px';
    uniquesSpan.style.fontWeight = 'bold';
    uniquesSpan.style.marginTop = '-20px';
    div.appendChild(uniquesSpan);

    // Calculate total bet amount
    const totalBetAmount = temp_bet.reduce((sum, bet) => sum + bet.amt, 0);

    // Create a display for the total bet amount
    const totalBetDiv = document.createElement('div');
    totalBetDiv.classList.add('total-bet-display');
    totalBetDiv.innerText = `Total Bet: ${totalBetAmount}`;
    div.appendChild(totalBetDiv);  // Add it above the table

    // Create a container for total loss, slider, and reset button
    const containerDiv = document.createElement('div');
    containerDiv.style.display = 'flex';
    containerDiv.style.alignItems = 'center';
    containerDiv.style.gap = '10px';  // Add some spacing between elements

// Create input for total loss
const totalLossInput = document.createElement('input');
totalLossInput.type = 'number';  // Only allow integer values
totalLossInput.value = session_user_amount_popup;  // Set the initial value
totalLost = parseInt(session_user_amount_popup, 10) || 0;
totalLossInput.classList.add('total-loss-input');  // Add a CSS class for styling
totalLossInput.style.width = '80px';  // Set width to avoid a large input box
totalLossInput.style.textAlign = 'right';  // Align the value to the right

// Add event listener to update `totalLost` on user input
totalLossInput.addEventListener('input', (e) => {
    const newValue = parseInt(e.target.value, 10);
    if (!isNaN(newValue)) {
        totalLost = newValue;  // Update the global `totalLost` value
        if(totalLost>0) totalLost = 0;
        show_bets();
    }
});

// Add label for better UX
const totalLossLabel = document.createElement('label');
totalLossLabel.innerText = 'Total Loss: ';
totalLossLabel.style.fontWeight = 'bold';
totalLossLabel.style.marginRight = '5px';

// Create a wrapper div for label and input
const totalLossDiv = document.createElement('div');
totalLossDiv.classList.add('total-bet-display');
totalLossDiv.style.display = 'flex';
totalLossDiv.style.alignItems = 'center';
totalLossDiv.style.gap = '5px';

// Append the label and input to the div
totalLossDiv.appendChild(totalLossLabel);
totalLossDiv.appendChild(totalLossInput);

// Add the total loss display to the container
containerDiv.appendChild(totalLossDiv);
    //containerDiv.appendChild(totalLossDiv);  // Add loss display

    // Create slider toggle (checkbox styled as a switch)
    const sliderLabel = document.createElement('label');
    sliderLabel.classList.add('switch');
    sliderLabel.innerHTML = `
        <input type="checkbox" id="useTotalLossSlider">
        <span class="slider"></span>
    `;
    sliderLabel.style.margin = '0 10px';

    // Handle slider toggle (to set the global flag)
      // Default value
    const sliderInput = sliderLabel.querySelector('input');
    sliderInput.checked = useTotalLossFlag;
    sliderInput.addEventListener('change', () => {
        useTotalLossFlag = sliderInput.checked;
        updateBetProfitPopup();
    });

    containerDiv.appendChild(sliderLabel);  // Add slider to container

    // Create reset button
    const resetButton = document.createElement('button');
    resetButton.innerText = 'Reset';
    resetButton.style.padding = '4px 8px';
    resetButton.addEventListener('click', () => {
            sessionProfitBox.value = '0';
            totalLossInput.value = '0';
            session_user_amount_array.push(session_user_amount);
            session_user_amount = 0;
            session_user_amount_popup = 0;
            totalLost = parseInt(session_user_amount_popup, 10) || 0;
            localStorage.setItem("sessionProfit", JSON.stringify(session_user_amount_array));
            localStorage.setItem("sessionProfitBoxValue", JSON.stringify(session_user_amount));
        updateBetProfitPopup();
    });
    containerDiv.appendChild(resetButton);  // Add button to container


    
    // === NEW: Show Uniques Checkbox ===
    const uniquesLabel = document.createElement('label');
    uniquesLabel.style.display = 'flex';
    uniquesLabel.style.alignItems = 'center';
    uniquesLabel.style.gap = '5px';

    const uniquesCheckbox = document.createElement('input');
    uniquesCheckbox.type = 'checkbox';
    uniquesCheckbox.id = 'spin_profit_uniques_checkbox';
    uniquesCheckbox.checked = spin_profit_uniques_checkbox;

    uniquesCheckbox.addEventListener('change', () => {
        spin_profit_uniques_checkbox = uniquesCheckbox.checked;
        updateBetProfitPopup();  // or another appropriate update function
    });

    const checkboxText = document.createElement('span');
    checkboxText.textContent = 'Show Uniques';

    uniquesLabel.appendChild(uniquesCheckbox);
    uniquesLabel.appendChild(checkboxText);
    containerDiv.appendChild(uniquesLabel);  // Add Show Uniques checkbox



    // Add the container div above the table
    div.appendChild(containerDiv);

    // Create table element
    const table = document.createElement('table');
    table.classList.add('bet-table');

    // Create table header
    const thead = document.createElement('thead');
    thead.innerHTML = `
        <tr>
            <th>Amount</th>
            <th>Type</th>
            <th>Numbers</th>
            <th>Profit</th>
        </tr>
    `;
    table.appendChild(thead);

    // Create table body
    const tbody = document.createElement('tbody');

    temp_bet = addProfitEntry(temp_bet);
    adjustBet(temp_bet);
/*
    temp_bet.forEach((bet) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${bet.amt}</td>
            <td>${bet.type.replace(/_/g, ' ')} (${bet.odds}:1)</td>
            <td>${bet.numbers}</td>
            <td>${bet.formattedProfit}</td>
        `;
        tbody.appendChild(row);
    });
    table.appendChild(tbody);
*/
    
    temp_bet.forEach((bet) => {
    // Dynamically determine the display label
    let displayType = bet.type.replace(/_/g, ' ');
    let displayNumbers = bet.numbers;
if (bet.odds === 35) displayType = 'Straight';        // 1 number
if (bet.odds === 17) displayType = 'Split';           // 2 numbers
if (bet.odds === 11) displayType = 'Street';          // 3 numbers (row)
if (bet.odds === 8)  displayType = 'Corner';          // 4 numbers
if (bet.odds === 6)  displayType = 'Basket';          // 0, 1, 2, 3 (only for American roulette)
if (bet.odds === 5)  displayType = 'Six Line';        // 6 numbers (double street)
if (bet.numbers == "19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36")
    {
        displayType = "High";
        displayNumbers = "19-36";
    }  
    if (bet.numbers == "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18")
    {
        displayType = "Low";
        displayNumbers ="1-18";
    }    

    const row = document.createElement('tr');
    row.innerHTML = `
        <td>${bet.amt}</td>
        <td>${displayType} (${bet.odds}:1)</td>
        <td>${displayNumbers}</td>
        <td>${bet.formattedProfit}</td>
    `;
    tbody.appendChild(row);
});
table.appendChild(tbody);





    // Append table to div
    div.appendChild(table);

    // Add inline CSS styles for table and elements
    const style = document.createElement('style');
    style.textContent = `
.bet-table-container {
    padding: 20px;
    max-width: 100%;
    margin: 20px 0;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    background-color: #f9f9f9;
    text-align: left;
 
    margin-left: 100px;
}

.total-bet-display {
    font-size: 20px;
    font-weight: bold;
    text-align: left;
    color: #333;
}

.bet-table {
    width: auto;
    border-collapse: collapse;
    font-size: 18px;
    text-align: left;
    overflow-x: auto;
}

.bet-table th, .bet-table td {
    padding: 12px 15px;
    border: 1px solid #ddd;
    white-space: nowrap;
}

.bet-table th {
    background-color: #4CAF50;
    color: white;
    text-transform: uppercase;
    letter-spacing: 1px;
}

.bet-table tr:nth-child(even) {
    background-color: #f2f2f2;
}

.bet-table tr:hover {
    background-color: #d1e7dd;
    transition: background-color 0.3s ease;
}

.switch {
    position: relative;
    display: inline-block;
    width: 34px;
    height: 20px;
}

.switch input {
    display: none;
}

.slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    border-radius: 34px;
}

.slider:before {
    position: absolute;
    content: "";
    height: 14px;
    width: 14px;
    left: 3px;
    bottom: 3px;
    background-color: white;
    border-radius: 50%;
    transition: 0.4s;
}

input:checked + .slider {
    background-color: #4caf50;
}

input:checked + .slider:before {
    transform: translateX(14px);
}
`;
    document.head.appendChild(style);

    return div;  // Return the div containing the table and total bet amount
}

function adjustBet(bet) {
    bet.forEach((bet) => {
        // Dozen 1
        if (bet.type == "outside_dozen" && bet.numbers == "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12") {
            bet.type = "Dozen 1";
            bet.numbers = "1 - 12";
        }
        // Dozen 2
        if (bet.type == "outside_dozen" && bet.numbers == "13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24") {
            bet.type = "Dozen 2";
            bet.numbers = "13 - 24";
        }
        // Dozen 3
        if (bet.type == "outside_dozen" && bet.numbers == "25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36") {
            bet.type = "Dozen 3";
            bet.numbers = "13 - 24";
        }

                // Even
                if (bet.type == "outside_oerb" && bet.numbers == "2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36") {
                    bet.type = "Even";
                    bet.numbers = "";
                }
                
                // Red
                if (bet.type == "outside_oerb" && bet.numbers == "1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36") {
                    bet.type = "Red";
                    bet.numbers = "";
                }
                
                // Black
                if (bet.type == "outside_oerb" && bet.numbers == "2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35") {
                    bet.type = "Black";
                    bet.numbers = "";
                }
                
                // Odd
                if (bet.type == "outside_oerb" && bet.numbers == "1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35") {
                    bet.type = "Odd";
                    bet.numbers = "";
                }
                                
                // High
                if (bet.type == "outside_high" && bet.numbers == "19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36") {
                    bet.type = "High";
                    bet.numbers = "";
                }
                                
                // Low
                if (bet.type == "outside_high" && bet.numbers == "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18") {
                    bet.type = "Low";
                    bet.numbers = "";
                }

                // Straights
                if(bet.type == "inside_whole")
                {
                    bet.type = "Straight";
                }

                                // Corner
                                if(bet.type == "corner_bet" && bet.numbers.split(",").length==4)
                                    {
                                        bet.type = "Corner";
                                    }
                                // Split
                                if(bet.type == "split")
                                    {
                                        bet.type = "Split";
                                    }
                                 // Street
                                 if(bet.type == "street")
                                    {
                                        bet.type = "Street";
                                    }
                                // Corner
                                if(bet.type == "corner_bet" && bet.numbers.split(",").length==6)
                                    {
                                        bet.type = "Line";
                                    }

        // Column 1
        if (bet.type == "outside_column" && bet.numbers == "1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34") {
            bet.type = "Column 1";
            bet.numbers = "1, 4, 7 ...";
        }
        // Column 2
        if (bet.type == "outside_column" && bet.numbers == "2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35") {
            bet.type = "Column 2";
            bet.numbers = "2, 5, 8 ...";
        }
        // Column 3
        if (bet.type == "outside_column" && bet.numbers == "3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36") {
            bet.type = "Column 3";
            bet.numbers = "3, 6, 9 ...";
        }
        if (bet.type == "zero" && bet.numbers == "0") {
            bet.type = "Zero";
            bet.numbers = "0";
        }
        // Zero 00
        if (bet.type == "zero" && bet.numbers == "37") {
            bet.type = "Zero";
            bet.numbers = "00";
        }


    });

   


    return bet;
}
function highlightNumbers(frequencyMap) {
    const storedColors = {
        1: localStorage.getItem("color1") || "#b3ffc9",
        2: localStorage.getItem("color2") || "#85e089",
        3: localStorage.getItem("color3") || "#58c56a",
        4: localStorage.getItem("color4") || "#2e8b4f",
        5: localStorage.getItem("color5") || "#1a5f3a",
        6: localStorage.getItem("color6") || "#0d3f25",
        7: localStorage.getItem("color7Plus") || "#e0f80b"
    };

    frequencyMap.forEach((count, item) => {
        let div;
        if (item === 0) {
            div = document.querySelector(`div[data-values="zero_${item}"]`);
        } else {
            div = document.querySelector(`div[data-values="${item}"]`);
        }

        if (div) {
            // Apply the corresponding stored color
            if (count === 1) div.style.backgroundColor = storedColors[1];
            if (count === 2) div.style.backgroundColor = storedColors[2];
            if (count === 3) div.style.backgroundColor = storedColors[3];
            if (count === 4) div.style.backgroundColor = storedColors[4];
            if (count === 5) div.style.backgroundColor = storedColors[5];
            if (count === 6) div.style.backgroundColor = storedColors[6];
            if (count > 6) div.style.backgroundColor = storedColors[7];

            div.style.color = 'black';  // Text color for contrast
            div.style.borderRadius = '25%';  // Keeps it circular
        }
    });
}


function highLightBoard() {
    unHighlightNumbers();

    const frequencyMap = new Map();  // Track the frequency of each number
    const filteredBets = bet.filter(bet => bet.amt > 0);

    filteredBets.forEach(bet => {
        const nums = bet.numbers.split(',').map(num => parseInt(num.trim()));  // Split and convert to integers
        nums.forEach(num => {
            frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1);  // Count occurrences
        });
    });

    highlightNumbers(frequencyMap);  // Pass the frequency map to highlightNumbers
}

function unHighlightNumbers() {
    let arr = Array.from({ length: 37 }, (_, i) => i);
    arr.forEach(item => {
        let div;
        if (item === 0) {
            div = document.querySelector(`div[data-values="zero_${item}"]`);
        } else {
            div = document.querySelector(`div[data-values="${item}"]`);
        }

        if (div) {
            div.style.backgroundColor = '';  // Reset background color
            div.style.color = '';  // Reset text color
        }
    });
}

function updateResults_old() {
    const frequencyMap = new Map(); // Track the frequency of each number
    let betsPlaced = bet.map(bet => ({ ...bet }));
    betsPlaced = betsPlaced.filter(bet => bet.amt > 0);

    // Build frequency map
    betsPlaced.forEach(bet => {
        const nums = bet.numbers.split(',').map(num => parseInt(num.trim()));  // Split and convert to integers
        nums.forEach(num => {
            frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1);  // Count occurrences
        });
    });

    let profits = new Array(37).fill(0);
    let numbersCovered = new Set();

    // Calculate profits/losses based on bets
    betsPlaced.forEach(bet => {
        const betNumbers = bet.numbers.split(',').map(num => parseInt(num.trim()));
        const betProfit = bet.amt * bet.odds;

        // Add numbers to the covered set
        betNumbers.forEach(number => numbersCovered.add(number));

        for (let number = 0; number <= 36; number++) {
            if (betNumbers.includes(number)) {
                // Profit for the numbers included in the bet
                profits[number] += betProfit;
            } else {
                // Loss for the numbers not included in the bet
                profits[number] -= bet.amt;
            }
        }
    });

    // Calculate board coverage
    let boardCoverage = ((numbersCovered.size / 37) * 100).toFixed(1);

    // Calculate winning and losing bets
    let winningBets = profits.filter(profit => profit > 0).length;
    let losingBets = 37 - winningBets;
    let winningPercentage = ((winningBets / 37) * 100).toFixed(1);
    let losingPercentage = ((losingBets / 37) * 100).toFixed(1);

    // Create main container div
    let container = document.createElement('div');
    container.style.marginLeft = '125px';
  
    // Create profit table title
    let title = document.createElement('h2');
    title.innerText = 'Profit Table';
    container.appendChild(title);

    // Create profit table grid
    let profitGrid = document.createElement('div');
    profitGrid.style.display = 'flex';
    profitGrid.style.flexWrap = 'wrap';
    profitGrid.style.gap = '10px';

    for (let number = 0; number <= 36; number++) {
        let profit = profits[number];
        let displayProfit = profit > 0 ? `+${profit}` : profit === 0 ? "0" : `${profit}`;

        let profitBox = document.createElement('div');
        profitBox.innerText = `${number}) ${displayProfit}`;
        profitBox.style.cssText = `
            flex: 1 1 calc(20%);
            text-align: center;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 8px;
            font-size: 16px;
            font-weight: ${profit > 0 ? 'bold' : 'normal'};
            color: ${profit > 0 ? '#ffffff' : profit === 0 ? '#666666' : '#ff4d4d'};
            background-color: ${profit > 0 ? '#28a745' : '#f9f9f9'};
            box-shadow: ${profit > 0 ? '0 0 10px rgba(40, 167, 69, 0.7)' : 'none'};
        `;
        profitGrid.appendChild(profitBox);
    }
    container.appendChild(profitGrid);

    // Create summary section
    let summaryContainer = document.createElement('div');
    summaryContainer.classList.add('summary-container');
/*
    let summaryTitle = document.createElement('h3');
    summaryTitle.innerText = 'Summary';
    summaryContainer.appendChild(summaryTitle);

    let boardCoverageParagraph = document.createElement('p');
    boardCoverageParagraph.innerHTML = `<span>Board Coverage:</span> ${boardCoverage}%`;
    summaryContainer.appendChild(boardCoverageParagraph);

    let winningBetsParagraph = document.createElement('p');
    winningBetsParagraph.innerHTML = `<span>Winning Bets:</span> ${winningPercentage}%`;
    summaryContainer.appendChild(winningBetsParagraph);

    let losingBetsParagraph = document.createElement('p');
    losingBetsParagraph.innerHTML = `<span>Losing Bets:</span> ${losingPercentage}%`;
    summaryContainer.appendChild(losingBetsParagraph);
*/
    container.appendChild(summaryContainer);

    return container;  // Return the div containing the entire results
}

function updateResults() {
    const container = document.createElement('div');
    container.style.marginLeft = '125px';

    const title = document.createElement('h2');
    title.innerText = 'Profit Table';
    container.appendChild(title);

    // --- Build profit data ---
    let profits = new Array(37).fill(0);
    let betsPlaced = bet.map(b => ({ ...b })).filter(b => b.amt > 0);

    betsPlaced.forEach(b => {
        const nums = b.numbers.split(',').map(n => parseInt(n.trim()));
        const profit = b.amt * b.odds;
        for (let i = 0; i <= 36; i++) {
            if (nums.includes(i)) profits[i] += profit;
            else profits[i] -= b.amt;
        }
    });

    // --- Helper to create a row ---
    function createRow(numbers, isProfit = false) {
        const row = document.createElement('div');
        row.style.display = 'flex';
        row.style.gap = '5px';
        row.style.marginBottom = '5px';

        numbers.forEach(num => {
            const box = document.createElement('div');
            box.style.padding = '6px 10px';
            box.style.border = '1px solid #ccc';
            box.style.borderRadius = '6px';
            box.style.minWidth = '40px';
            box.style.textAlign = 'center';
            box.style.fontWeight = isProfit ? 'bold' : 'normal';
            box.style.backgroundColor = isProfit
                ? '#fff'
                : (isRed(num) ? 'red' : isBlack(num) ? 'black' : 'green');
            box.style.color = isProfit
                ? (profits[num] > 0 ? 'green' : profits[num] < 0 ? 'red' : 'gray')
                : (num === 0 ? '#fff' : '#fff');

            box.innerText = isProfit
                ? (profits[num] > 0 ? `+${profits[num]}` : `${profits[num]}`)
                : num === 37 ? '00' : num;
            row.appendChild(box);
        });

        return row;
    }

    // --- 0 row ---
    container.appendChild(createRow([0]));
    container.appendChild(createRow([0], true));
    container.appendChild(document.createElement('br'));

    // --- Top Row (3, 6, ..., 36) ---
    const rowTop = [];
    const rowMid = [];
    const rowBot = [];
    for (let i = 3; i <= 36; i += 3) {
        rowTop.push(i);
        rowMid.push(i - 1);
        rowBot.push(i - 2);
    }

    container.appendChild(createRow(rowTop));
    container.appendChild(createRow(rowTop, true));
    container.appendChild(document.createElement('br'));

    container.appendChild(createRow(rowMid));
    container.appendChild(createRow(rowMid, true));
    container.appendChild(document.createElement('br'));

    container.appendChild(createRow(rowBot));
    container.appendChild(createRow(rowBot, true));

    return container;
}


function createColorSettingsPanel() {
    const settingsDiv = document.createElement('div');
    settingsDiv.id = 'color-settings-panel';
    settingsDiv.style.position = 'fixed';
    settingsDiv.style.top = '50%';
    settingsDiv.style.left = '50%';
    settingsDiv.style.transform = 'translate(-50%, -50%)';
    settingsDiv.style.border = '1px solid #ccc';
    settingsDiv.style.padding = '20px';
    settingsDiv.style.backgroundColor = '#f9f9f9';
    settingsDiv.style.borderRadius = '10px';
    settingsDiv.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.1)';
    settingsDiv.style.zIndex = '1000';
    settingsDiv.style.display = 'none'; // Initially hidden

    const title = document.createElement('h3');
    title.textContent = 'Change Colors';
    title.style.cursor = 'grab'; // Indicate draggable area
    settingsDiv.appendChild(title);

    const titleContainer = document.createElement('div'); // Container for both lines
    titleContainer.style.textAlign = 'center'; // Center align the text (optional)
    titleContainer.style.marginBottom = '10px'; // Add some spacing
    
    const title2 = document.createElement('h4'); // Use heading with proper size
    title2.textContent = 'How many times a number';
    title2.style.margin = '0'; // Remove default margin for better control
    
    const title3 = document.createElement('h4'); // Consistent style for second line
    title3.textContent = 'is covered by a bet';
    title3.style.margin = '0';
    
    titleContainer.appendChild(title2);
    titleContainer.appendChild(title3);
    
    settingsDiv.appendChild(titleContainer);

    const buttonContainer = document.createElement('div');
    buttonContainer.style.display = 'flex';
    buttonContainer.style.gap = '10px';
    buttonContainer.style.marginBottom = '10px';

    const closeButton = document.createElement('button');
    closeButton.textContent = 'Close';
    closeButton.addEventListener('click', () => {
        settingsDiv.style.display = 'none'; // Hide the panel when close button is clicked
    });

    const defaultButton = document.createElement('button');
    defaultButton.textContent = 'Default';
    defaultButton.addEventListener('click', () => {
        // Reset all color inputs to their default values
        colorOptions.forEach(option => {
            const colorBox = document.querySelector(`input[data-key="${option.key}"]`);
            const defaultColor = getDefaultColor(option.count);
            localStorage.setItem(option.key, defaultColor); // Store default color in localStorage
            colorBox.value = defaultColor; // Set color input to default
            const previewBox = colorBox.nextElementSibling;
            if (previewBox) {
                previewBox.style.backgroundColor = defaultColor; // Update the preview
            }
        });
        applyStoredColors(); // Apply default colors to the UI
    });
    buttonContainer.appendChild(defaultButton);
    buttonContainer.appendChild(closeButton);
    
    settingsDiv.appendChild(buttonContainer);

    const colorOptions = [
        { count: 1, label: "Count 1", key: "color1" },
        { count: 2, label: "Count 2", key: "color2" },
        { count: 3, label: "Count 3", key: "color3" },
        { count: 4, label: "Count 4", key: "color4" },
        { count: 5, label: "Count 5", key: "color5" },
        { count: 6, label: "Count 6", key: "color6" },
        { count: 7, label: "Count 7+", key: "color7Plus" }
    ];

    colorOptions.forEach(option => {
        const colorRow = document.createElement('div');
        colorRow.style.display = 'flex';
        colorRow.style.alignItems = 'center';
        colorRow.style.marginBottom = '10px';

        const label = document.createElement('span');
        label.textContent = `${option.count}: `;
        label.style.marginRight = '10px';

        const colorBox = document.createElement('input');
        colorBox.type = 'color';
        colorBox.value = localStorage.getItem(option.key) || getDefaultColor(option.count); // Default or stored color
        colorBox.dataset.key = option.key; // Add key as data attribute for easy selection
        colorBox.style.marginRight = '10px';

        colorBox.addEventListener('input', (e) => {
            localStorage.setItem(option.key, e.target.value); // Save the new color to localStorage
            applyStoredColors(); // Apply new colors live to divs
        });

        const previewBox = document.createElement('div');
        previewBox.style.width = '20px';
        previewBox.style.height = '20px';
        previewBox.style.backgroundColor = colorBox.value;
        previewBox.style.border = '1px solid #000';
        previewBox.style.borderRadius = '50%';

        colorBox.addEventListener('input', () => {
            previewBox.style.backgroundColor = colorBox.value;
        });

        colorRow.appendChild(label);
        colorRow.appendChild(colorBox);
        colorRow.appendChild(previewBox);
        settingsDiv.appendChild(colorRow);
    });

    // Draggable functionality
    let isDragging = false;
    let offsetX = 0;
    let offsetY = 0;

    title.addEventListener('mousedown', (e) => {
        isDragging = true;
        offsetX = e.clientX - settingsDiv.getBoundingClientRect().left;
        offsetY = e.clientY - settingsDiv.getBoundingClientRect().top;
        title.style.cursor = 'grabbing';
    });

    document.addEventListener('mousemove', (e) => {
        if (isDragging) {
            settingsDiv.style.left = `${e.clientX - offsetX}px`;
            settingsDiv.style.top = `${e.clientY - offsetY}px`;
            settingsDiv.style.transform = ''; // Remove center transform while dragging
        }
    });

    document.addEventListener('mouseup', () => {
        isDragging = false;
        title.style.cursor = 'grab';
    });

    return settingsDiv;
}


function getDefaultColor(count) {
    const defaultColors = {
        1: "#b3ffc9",  // Light green (starting point)
        2: "#85e089",  // Slightly darker green
        3: "#58c56a",  // Medium forest green
        4: "#2e8b4f",  // Richer green
        5: "#1a5f3a",  // Darker green
        6: "#0d3f25",  // Deep green (almost emerald)
        7: "#e0f80b"   // Yellow for attention for 7+
    };
    return defaultColors[count] || "#e0f80b";
}

function applyStoredColors() {
    const storedColors = {
        1: localStorage.getItem("color1") || "#b3ffc9",
        2: localStorage.getItem("color2") || "#85e089",
        3: localStorage.getItem("color3") || "#58c56a",
        4: localStorage.getItem("color4") || "#2e8b4f",
        5: localStorage.getItem("color5") || "#1a5f3a",
        6: localStorage.getItem("color6") || "#0d3f25",
        7: localStorage.getItem("color7Plus") || "#e0f80b"
    };

    const frequencyMap = new Map();  // Track the frequency of each number
    const filteredBets = bet.filter(bet => bet.amt > 0);

    filteredBets.forEach(bet => {
        const nums = bet.numbers.split(',').map(num => parseInt(num.trim()));  // Split and convert to integers
        nums.forEach(num => {
            frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1);  // Count occurrences
        });
    });

    frequencyMap.forEach((count, item) => {
        let div;
        if (item === 0) {
            div = document.querySelector(`div[data-values="zero_${item}"]`);
        } else {
            div = document.querySelector(`div[data-values="${item}"]`);
        }

        if (div) {
            // Apply the corresponding stored color
            if (count === 1) div.style.backgroundColor = storedColors[1];
            if (count === 2) div.style.backgroundColor = storedColors[2];
            if (count === 3) div.style.backgroundColor = storedColors[3];
            if (count === 4) div.style.backgroundColor = storedColors[4];
            if (count === 5) div.style.backgroundColor = storedColors[5];
            if (count === 6) div.style.backgroundColor = storedColors[6];
            if (count > 6) div.style.backgroundColor = storedColors[7];

            div.style.color = 'black';  // Text color for contrast
            div.style.borderRadius = '25%';  // Keeps it circular
        }
    });
}

function spin_profit_highlight()
{

    spin_profit_uniques_array.forEach(item => {
        let div;
        if (item === 0) {
            div = document.querySelector(`div[data-values="zero_${item}"]`);
        } else {
            div = document.querySelector(`div[data-values="${item}"]`);
        }

        if (div) {
            div.classList.add('slider-highlights');
        }
    });

}
function spin_profit_unhighlight()
{
    let arr = Array.from({ length: 37 }, (_, i) => i);
    arr.forEach(item => {
        let div;
        if (item === 0) {
            div = document.querySelector(`div[data-values="zero_${item}"]`);
        } else {
            div = document.querySelector(`div[data-values="${item}"]`);
        }

        if (div) {
            div.classList.remove('slider-highlights');
        }
    });
}

function spin_profit_display_outside_clear()
{
    const container = document.getElementById('spin_profit_uniques_span');
    if (!container) return;

        const counts = {
        E: 0, O: 0,
        H: 0, L: 0,
        R: 0, B: 0,
        D1: 0, D2: 0, D3: 0,
        R1: 0, R2: 0, R3: 0
    };


    container.textContent = 
        `E: ${counts.E}  | O: ${counts.O}  | H: ${counts.H}  | L: ${counts.L}  | ` +
        `R: ${counts.R}  | B: ${counts.B}  | ` +
        `D1: ${counts.D1}  | D2: ${counts.D2}  | D3: ${counts.D3}  | ` +
        `R1: ${counts.R1}  | R2: ${counts.R2}  | R3: ${counts.R3}`;
}


function spin_profit_display_outside() {
    const container = document.getElementById('spin_profit_uniques_span');
    console.log("SPAN ",container);
    if (!container) return;
console.log("WORL SPAN ");
    const counts = {
        E: 0, O: 0,
        H: 0, L: 0,
        R: 0, B: 0,
        D1: 0, D2: 0, D3: 0,
        R1: 0, R2: 0, R3: 0
    };

    // Red numbers on a single-zero roulette wheel
    const reds = [1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36];

    for (const n of spin_profit_uniques_array) {
        if (n < 1 || n > 36) continue;

        // Even/Odd
        if (n % 2 === 0) counts.E++;
        else counts.O++;

        // High/Low
        if (n >= 1 && n <= 18) counts.L++;
        else counts.H++;

        // Red/Black
        if (reds.includes(n)) counts.R++;
        else counts.B++;

        // Dozens
        if (n >= 1 && n <= 12) counts.D1++;
        else if (n >= 13 && n <= 24) counts.D2++;
        else if (n >= 25 && n <= 36) counts.D3++;

        // Rows
        if (n % 3 === 1) counts.R1++;
        else if (n % 3 === 2) counts.R2++;
        else if (n % 3 === 0) counts.R3++;
    }

    container.textContent = 
        `E: ${counts.E}  | O: ${counts.O}  | H: ${counts.H}  | L: ${counts.L}  | ` +
        `R: ${counts.R}  | B: ${counts.B}  | ` +
        `D1: ${counts.D1}  | D2: ${counts.D2}  | D3: ${counts.D3}  | ` +
        `R1: ${counts.R1}  | R2: ${counts.R2}  | R3: ${counts.R3}`;

}
