// This allows the user to click the rebet and double bet buttons

let savedBets = [];



function setOldBet() {

    userBets = new Map();
    bet.forEach(betObj => {
       
        userBets.set(betObj.numbers, [betObj.amt, betObj.type, betObj.odds]);
    });

    oldBet = [...bet];
    oldUserBets = new Map(userBets);

    // Check if the current oldUserBets already exists in savedBets
    if (!isDuplicateBet(oldUserBets)) {
        let betName = "Bet " + (savedBets.length + 1); // Generate a unique name

        // Convert the Map to an array of key-value pairs before saving
        savedBets.push({ name: betName, bets: Array.from(oldUserBets) });

        // Add option to the list
        let betList = document.getElementById('betList');
        let option = document.createElement('option');
        option.value = savedBets.length - 1; // Use index as value
        option.text = betName;
        betList.add(option);
    }
}

// Function to save oldUserBets to localStorage and repopulate betCache
function saveToCache() {
    let betCache = document.getElementById('betCache');
    let betList = document.getElementById('betList');

    // Prepare to save oldUserBets to localStorage
    let savedCache = JSON.parse(localStorage.getItem('betCache')) || [];

    // Get the selected item from betList
    let selectedIndex = betList.selectedIndex;
    if (selectedIndex === -1) {

        return;
    }

    // Get the text and value of the selected option in betList
    let selectedOption = betList.options[selectedIndex];
    let selectedText = selectedOption.text;

    // Convert oldUserBets (which is a Map) to an array of key-value pairs
    let newCacheItem = {
        bets: Array.from(oldUserBets), // Save the bets as key-value pairs
        name: selectedText, // Save the text from the betList
        text: selectedText
    };

    // Push the new item to the savedCache array
    savedCache.push(newCacheItem);

    // Save updated betCache to localStorage
    localStorage.setItem('betCache', JSON.stringify(savedCache));




    // Repopulate the betCache select element with updated localStorage values
    loadCacheFromLocalStorage();
}


// Function to load the betCache from localStorage
function loadCacheFromLocalStorage() {
    let betCache = document.getElementById('betCache');
    betCache.innerHTML = ''; // Clear existing items

    // Retrieve the saved cache from localStorage
    let savedCache = JSON.parse(localStorage.getItem('betCache')) || [];

    // Loop through the cacheItems and add them back to the betCache
    savedCache.forEach((item, index) => {
        let option = document.createElement('option');
        option.value = index; // Use the index as value
        option.text = item.text; // Use the name for the display
        betCache.add(option);
    });


}

function clearBetCache() {
    localStorage.removeItem('betCache');
    let betCache = document.getElementById('betCache');
    betCache.innerHTML = '';

}
function clearList() {
    // Clear localStorage for 'betList'
    localStorage.removeItem('betList');

    // Clear the bet list in the DOM
    let betList = document.getElementById('betList');
    betList.innerHTML = '';

    // Reset savedBets to an empty array, not an object
    savedBets = [];
    localStorage.removeItem('savedBets');


}





// Save the betCache to localStorage
function saveCacheToLocalStorage() {
    let betCache = document.getElementById('betCache');
    let cacheItems = [];

    // Loop through the betCache options and save them to an array
    for (let i = 0; i < betCache.options.length; i++) {
        cacheItems.push({
            value: betCache.options[i].value,
            text: betCache.options[i].text
        });
    }

    // Store the cacheItems array in localStorage as a JSON string
    localStorage.setItem('betCache', JSON.stringify(cacheItems));
}

function isDuplicateBet(newBet) {
    for (let savedBet of savedBets) {
        if (areMapsEqual(new Map(savedBet.bets), newBet)) { // Convert savedBet.bets back to a Map
            return true; // Found a duplicate
        }
    }
    return false; // No duplicate found
}

function areMapsEqual(map1, map2) {
    if (map1.size !== map2.size) {
        return false; // Different size, not equal
    }

    for (let [key, value] of map1) {
        if (!map2.has(key) || !areArraysEqual(value, map2.get(key))) {
            return false; // Different keys or values
        }
    }

    return true; // Maps are equal
}

function areArraysEqual(arr1, arr2) {
    if (arr1.length !== arr2.length) {
        return false; // Different lengths, not equal
    }

    for (let i = 0; i < arr1.length; i++) {
        if (arr1[i] !== arr2[i]) {
            return false; // Different elements, not equal
        }
    }

    return true; // Arrays are equal
}


function selectOldBet() {
    let betList = document.getElementById('betList');
    let selectedIndex = betList.value; // Get the index of selected bet

    oldUserBets = new Map(savedBets[selectedIndex].bets); // Set oldUserBets to the selected bet
    event.preventDefault();
console.log("OLD BET");
    rebet();
}

function selectOldBetCache() {
    let betCache = document.getElementById('betCache');
    let selectedIndex = betCache.selectedIndex; // Get the index of the selected option

    if (selectedIndex === -1) {

        return;
    }

    // Retrieve the saved betCache from localStorage
    let savedCache = JSON.parse(localStorage.getItem('betCache'));

    // Use the selected index to find the selected bet in savedCache
    let selectedBet = savedCache[selectedIndex];

    if (selectedBet) {
        // Convert the saved bet array back to a Map and set it to oldUserBets
        oldUserBets = new Map(selectedBet.bets);



        rebet();
    }

    event.preventDefault();
}

function process_bouncy_dozen_rows() {



    if (oldUserBets_dozens.size > 0 || oldUserBets_rows.size > 0) {


        oldUserBets = new Map();
    }
    if (oldUserBets_dozens.size > 0) {



        oldUserBets_dozens.forEach((value, key) => {
            oldUserBets.set(key, value);
        });

    }
    if (oldUserBets_rows.size > 0) {

        oldUserBets_rows.forEach((value, key) => {
            oldUserBets.set(key, value);
        });


    }

}

function bet_minus()
{
   
    let newBetMap = new Map();
   
    bet.forEach(item=>{ 
        item.amt -= 1;
        session_user_amount =session_user_amount + 1;

        let mapArray = [];
        mapArray.push(item.amt);
        mapArray.push(item.type);
        mapArray.push(item.odds);
        newBetMap.set(item.numbers,mapArray);
    });

    if (newBetMap.size > 0) {
        placeBet(newBetMap);
    }

}
function bet_add() {
    let newBetMap = new Map();

    bet.forEach(item => {
        if (item.amt > 0) {
            item.amt += 1;
            session_user_amount -= 1;

            let mapArray = [item.amt, item.type, item.odds];
            newBetMap.set(item.numbers, mapArray);
        }
    });

    if (newBetMap.size > 0) {
        placeBet(newBetMap);
    }
}
function bet_double()
{

    let newBetMap = new Map();
   
    bet.forEach(item=>{ 
        
        session_user_amount =session_user_amount - item.amt;

item.amt *= 2;
        let mapArray = [];
        mapArray.push(item.amt);
        mapArray.push(item.type);
        mapArray.push(item.odds);
        newBetMap.set(item.numbers,mapArray);
    });

    if (newBetMap.size > 0) {
        placeBet(newBetMap);
    }

}

function rebet(mulitiplier = 1) {

    session_user_amount = session_user_amount_previous;
    process_bouncy_dozen_rows();
    clearBet();
    removeChips();



    if (oldUserBets.size > 0) {


        bet = [];
        numbersBet = [];
        currentBet = 0;
        bankValue = previousBankValue;



        // Step 1: Convert the map values to an array
        const valuesArray = Array.from(oldUserBets.values());

        // Step 2: Sum the `amt` using reduce
        var totalBetsOnTable = valuesArray.reduce((acc, currentValue) => {
            return acc + currentValue[0]; // currentValue[0] is the `amt`
        }, 0); // Initialize accumulator to 0

        totalBetsOnTable = totalBetsOnTable * mulitiplier;


        // Setting the bank values	
        bankValue = bankValue - totalBetsOnTable;
        currentBet = totalBetsOnTable;

        
session_user_amount = session_user_amount - totalBetsOnTable;


        document.getElementById('bankSpan').innerText = '' + bankValue.toLocaleString("en-GB") + '';
        document.getElementById('betSpan').innerText = '' + currentBet.toLocaleString("en-GB") + '';

        oldUserBets.forEach((values, key) => {

            var amt = values[0] * mulitiplier;
            var type = values[1];
            var odds = values[2];


            // Assuming key is something like "1, 2, 3, 4, 5, 6" and you're matching it against the data-values attribute
            var element = document.querySelector(`[data-values="${key}"]`);

            if (element && amt > 0) {


                // Add the chip to the element first
                if (!element.querySelector('.chip')) {
                    let chipColour = (amt < 5) ? 'red' : ((amt < 10) ? 'blue' : ((amt < 100) ? 'orange' : 'gold'));
                    let chip = document.createElement('div');
                    chip.setAttribute('class', 'chip ' + chipColour);
                    let chipSpan = document.createElement('span');
                    chipSpan.id = '5_bet_location_'+global_chip_span_id_counter;
                    global_chip_id.push(chipSpan.id);
                    global_chip_span_id_counter +=1;
                    chipSpan.setAttribute('class', 'chipSpan');
                    chipSpan.innerText = amt;
               
                    chip.append(chipSpan);
                    element.append(chip);
                }

                setReBet(element, key, type, odds, amt);
            }
        });
    }

    everyBetClick();
}


function rebetEdge3(mulitiplier = 1) {


    clearBet();
    removeChips();



    if (oldUserBets_Edge3.size > 0) {


        bet = [];
        numbersBet = [];
        currentBet = 0;
        bankValue = previousBankValue;



        // Step 1: Convert the map values to an array
        const valuesArray = Array.from(oldUserBets_Edge3.values());

        // Step 2: Sum the `amt` using reduce
        var totalBetsOnTable = valuesArray.reduce((acc, currentValue) => {
            return acc + currentValue[0]; // currentValue[0] is the `amt`
        }, 0); // Initialize accumulator to 0

        totalBetsOnTable = totalBetsOnTable * mulitiplier;


        // Setting the bank values	
        bankValue = bankValue - totalBetsOnTable;
        currentBet = totalBetsOnTable;

        document.getElementById('bankSpan').innerText = '' + bankValue.toLocaleString("en-GB") + '';
        document.getElementById('betSpan').innerText = '' + currentBet.toLocaleString("en-GB") + '';

        oldUserBets_Edge3.forEach((values, key) => {

            var amt = values[0] * mulitiplier;
            var type = values[1];
            var odds = values[2];


            // Assuming key is something like "1, 2, 3, 4, 5, 6" and you're matching it against the data-values attribute
            var element = document.querySelector(`[data-values="${key}"]`);

            if (element && amt > 0) {


                // Add the chip to the element first
                if (!element.querySelector('.chip')) {
                    let chipColour = (amt < 5) ? 'red' : ((amt < 10) ? 'blue' : ((amt < 100) ? 'orange' : 'gold'));
                    let chip = document.createElement('div');
                    chip.setAttribute('class', 'chip ' + chipColour);
                    let chipSpan = document.createElement('span');
                    chipSpan.id = '6_bet_location_'+global_chip_span_id_counter;
                    global_chip_id.push(chipSpan.id);
                    global_chip_span_id_counter +=1;
                    chipSpan.setAttribute('class', 'chipSpan');
                    chipSpan.innerText = amt;
         
                    chip.append(chipSpan);
                    element.append(chip);
                    
                }

                setReBet(element, key, type, odds, amt);
            }
        });
    }
    everyBetClick();
}


function rebet2(mulitiplier = 1) {

    bet = [];
    numbersBet = [];
    currentBet = 0;
    bankValue = previousBankValue;


    userBets.forEach((values, key) => {



        var element = document.querySelector(`[data-values="${key}"]`);

        if (element) {
            // Assuming your setBet function accepts the element and an array of values
            //wager = values[3];

            // Add the chip to the element first
            if (!element.querySelector('.chip')) {
                let chipColour = (values.amt < 5) ? 'red' : ((values.amt < 10) ? 'blue' : ((values.amt < 100) ? 'orange' : 'gold'));
                let chip = document.createElement('div');
                chip.setAttribute('class', 'chip ' + chipColour);
                let chipSpan = document.createElement('span');
                chipSpan.id = '7_bet_location_'+global_chip_span_id_counter;
                global_chip_id.push(chipSpan.id);
                global_chip_span_id_counter +=1;
                chipSpan.setAttribute('class', 'chipSpan');
                chipSpan.innerText = values.amt;
       
                chip.append(chipSpan);
                element.append(chip);
            }
            setReBet(element, values.numbers, values.type, values.odds, values.amt * mulitiplier);
        } else {

        }
    });
    everyBetClick();
}

function zzzsetBet(e, b) {

    oldBet = [...bet];
    var keyValue = e.dataset.values;
    userBets.set(keyValue, b);


}

function setReBet(e, n, t, o, amt) {



    // Add the spin button
    if (!container.querySelector('.spinBtn')) {
        let spinBtn = document.createElement('div');
        spinBtn.setAttribute('class', 'spinBtn');
        spinBtn.innerText = 'spin';
        spinBtn.onclick = function () {
            this.remove();
            spin();
        };
        container.append(spinBtn);
    }



    // Set Bet Array
    var obj = {
        amt: amt,
        type: t,
        odds: o,
        numbers: n
    };
    bet.push(obj);
    

    // Set numbersBet
    let numArray = n.split(',').map(Number);
    for (i = 0; i < numArray.length; i++) {
        if (!numbersBet.includes(numArray[i])) {
            numbersBet.push(numArray[i]);
        }
    }

    // Create the Chip on the board.
    if (!e.querySelector('.chip')) {
        let chipColour = (amt < 5) ? 'red' : ((amt < 10) ? 'blue' : ((amt < 100) ? 'orange' : 'gold'));
        let chip = document.createElement('div');
        chip.setAttribute('class', 'chip ' + chipColour);
        let chipSpan = document.createElement('span');
        chipSpan.id = '3_bet_location_'+global_chip_span_id_counter;
        global_chip_id.push(chipSpan.id);
        global_chip_span_id_counter +=1;
        chipSpan.setAttribute('class', 'chipSpan');
        chipSpan.innerText = amt;
 
        chip.append(chipSpan);
        e.append(chip);
    }


    everyBetClick();
}


function renameSelectedBet() {
    let betList = document.getElementById('betList');


    // Check if an item is selected in betList
    let selectedListOption = betList.selectedIndex !== -1 ? betList.options[betList.selectedIndex] : null;



    if (!selectedListOption) {
        alert("Please select a bet to rename from betList or betCache.");
        return;
    }

    // Prompt the user for the new name
    let newName = prompt("Enter the new name for the selected bet:");
    if (newName && newName.trim() !== "") {
        if (selectedListOption) {
            selectedListOption.text = newName;
            updateLocalStorageForBetList(selectedListOption.value, newName, "betList"); // Update localStorage if needed
        }

    } else {
        alert("Invalid name. Rename operation canceled.");
    }
}
function renameSelectedBetCached() {

    let betCache = document.getElementById('betCache');



    // Check if an item is selected in betCache
    let selectedCacheOption = betCache.selectedIndex !== -1 ? betCache.options[betCache.selectedIndex] : null;

    if (!selectedCacheOption) {
        alert("Please select a bet to rename from betList or betCache.");
        return;
    }

    // Prompt the user for the new name
    let newName = prompt("Enter the new name for the selected bet:");
    if (newName && newName.trim() !== "") {

        if (selectedCacheOption) {
            selectedCacheOption.text = newName;
            updateLocalStorageForBetList(selectedCacheOption.value, newName, "betCache"); // Update localStorage if needed

        }
    } else {
        alert("Invalid name. Rename operation canceled.");
    }
}


function updateLocalStorageForBetList(value, newName, listType) {
    if (listType === "betList") {
        let savedBets = JSON.parse(localStorage.getItem('savedBets')) || [];
        if (savedBets[value]) {
            savedBets[value].name = newName; // Update the name in savedBets
            localStorage.setItem('savedBets', JSON.stringify(savedBets)); // Save updated list back to localStorage
        }
    } else if (listType === "betCache") {
        let savedCache = JSON.parse(localStorage.getItem('betCache')) || [];
        if (savedCache[value]) {
            savedCache[value].text = newName; // Update the name in betCache
            localStorage.setItem('betCache', JSON.stringify(savedCache)); // Save updated list back to localStorage


        }
    }
}

// Function to remove selected item from betList
// Function to remove selected item from betList and renumber indices
function removeSelectedBet() {
    let betList = document.getElementById('betList');
    let selectedIndex = betList.selectedIndex;

    if (selectedIndex === -1) {
        alert("Please select an item to remove.");
        return;
    }

    // Remove the item from savedBets array
    savedBets.splice(selectedIndex, 1);

    // Remove the item from the list
    betList.remove(selectedIndex);

    // Renumber the remaining items in the list
    for (let i = 0; i < betList.options.length; i++) {
        betList.options[i].value = i; // Update the value with the new index
    }

    // Update the localStorage for betList
    localStorage.setItem('savedBets', JSON.stringify(savedBets));


}

// Function to remove selected item from betCache
function removeSelectedCacheBet() {
    let betCache = document.getElementById('betCache');
    let selectedIndex = betCache.selectedIndex;

    if (selectedIndex === -1) {
        alert("Please select an item to remove.");
        return;
    }

    let savedCache = JSON.parse(localStorage.getItem('betCache')) || [];

    // Remove the selected item from the cache
    savedCache.splice(selectedIndex, 1);

    // Remove the item from the list
    betCache.remove(selectedIndex);

    // Update the localStorage for betCache
    localStorage.setItem('betCache', JSON.stringify(savedCache));


}


function placeBet(betArray) {

    console.log("betArray: ",betArray);

   clearBet();
   removeChips();

    mulitiplier = 1;

    if (betArray.size > 0) {


        bet = [];
        numbersBet = [];
        currentBet = 0;
        bankValue = previousBankValue;



        // Step 1: Convert the map values to an array
        const valuesArray = Array.from(betArray.values());

        // Step 2: Sum the `amt` using reduce
        var totalBetsOnTable = valuesArray.reduce((acc, currentValue) => {
            return acc + currentValue[0]; // currentValue[0] is the `amt`
        }, 0); // Initialize accumulator to 0

        totalBetsOnTable = totalBetsOnTable * mulitiplier;


        // Setting the bank values	
        bankValue = bankValue - totalBetsOnTable;
        currentBet = totalBetsOnTable;



        
        document.getElementById('bankSpan').innerText = '' + bankValue.toLocaleString("en-GB") + '';
        document.getElementById('betSpan').innerText = '' + currentBet.toLocaleString("en-GB") + '';

        betArray.forEach((values, key) => {

            var amt = values[0] * mulitiplier;
          
            var type = values[1];
            var odds = values[2];


            // Assuming key is something like "1, 2, 3, 4, 5, 6" and you're matching it against the data-values attribute
            var element = document.querySelector(`[data-values="${key}"]`);

            if (element && amt > 0) {


                // Add the chip to the element first
                if (!element.querySelector('.chip')) {
                    let chipColour = (amt < 5) ? 'red' : ((amt < 10) ? 'blue' : ((amt < 100) ? 'orange' : 'gold'));
                    let chip = document.createElement('div');
                    chip.setAttribute('class', 'chip ' + chipColour);
                    let chipSpan = document.createElement('span');
                    chipSpan.id = '4_bet_location_'+global_chip_span_id_counter;
                    global_chip_id.push(chipSpan.id);
                    global_chip_span_id_counter +=1;
                    chipSpan.setAttribute('class', 'chipSpan');
                    chipSpan.innerText = amt;
     
                    chip.append(chipSpan);
                    element.append(chip);
                }

                setReBet(element, key, type, odds, amt);
            }
        });
    }
    everyBetClick();

}
