let selected_numbersUp = 3;
let neighbors_count = 2;
let highlight_my_numbers = false;

let numbersUpHighlights = [];
let numbersUp_array_highlight = new Array(40).fill(0);
let numbersUp_array_clicked = new Array(40).fill(0);

function numbersUp_Update() {
    let content = numbersUp_onceBuild();
    numbersUp_Panel.innerHTML = '';
    numbersUp_Panel.appendChild(content);
    clearSecondRowHighlights();


}

function createDropdown() {
    let dropdown = document.createElement('select');
    dropdown.id = 'numbersUp_selected';

    for (let i = 1; i <= 37; i++) {
        let option = document.createElement('option');
        option.value = i;
        option.innerText = i;

        if (i === parseInt(selected_numbersUp)) {
            option.selected = true;
        }

        dropdown.appendChild(option);
    }

dropdown.addEventListener('change', function (event) {
    selected_numbersUp = parseInt(event.target.value);

    // 1. Get recent unique numbers
    const allSpins = [...numbers];
    const recentUniqueNumbers = getRecentUniqueNumbers(allSpins, selected_numbersUp);

    // 2. Recount frequencies
    const frequencies = countFrequencies(allSpins);

    // 3. Loop through top row and update
    for (let num = 0; num <= 36; num++) {
        const cell = document.getElementById(`numbersup_freq_${num}`);
        if (!cell) continue;

        // ✅ Update frequency text
        cell.textContent = frequencies[num] || '';

        // ✅ Clear all highlights first
        cell.style.backgroundColor = '';

        // ✅ Then highlight if in recent selection
        if (recentUniqueNumbers.includes(num)) {
            cell.style.backgroundColor = 'yellow';
        }
    }
});



    return dropdown;
}

function numbersUp_onceBuild() {
    sliderUnhighlight();
    let container = document.createElement('div');
    container.id = 'numbersUp-once-contents';
    container.style.marginLeft = '25px';
    container.style.marginBottom = '15px';

    let allSpins = [...numbers];
    let frequencies = countFrequencies(allSpins);
    let recentUniqueNumbers = getRecentUniqueNumbers(allSpins, parseInt(selected_numbersUp));

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

    const toggleLabel = document.createElement('label');
    toggleLabel.textContent = 'Highlight Recent';
    toggleContainer.appendChild(toggleLabel);

    const toggleSlider = document.createElement('input');
    toggleSlider.type = 'checkbox';
    toggleSlider.checked = highlight_my_numbers;
    toggleContainer.appendChild(toggleSlider);
    toggleSlider.addEventListener('change', () => {
        highlight_my_numbers = toggleSlider.checked;
        sliderUnhighlight();
        if (highlight_my_numbers) {
            sliderHighlight(recentUniqueNumbers);
        }
    });

    container.appendChild(toggleContainer);

    if (toggleSlider.checked) {
        sliderHighlight(recentUniqueNumbers);
    }

    let allNumbers = [...wheel0];

    let numberRow = document.createElement('div');
    numberRow.style.display = 'flex';
    let onceAllRow = document.createElement('div');
    onceAllRow.style.display = 'flex';

    allNumbers.forEach(num => {
        let [numberCell, onceAllCell] = numbersUp_createCells(num, frequencies[num] || '', recentUniqueNumbers);
        numberRow.appendChild(numberCell);
        onceAllCell.id = `numbersup_freq_${num}`;
        onceAllRow.appendChild(onceAllCell);
    });

    let dropdown = createDropdown();
    onceAllRow.appendChild(dropdown);


    // Neighbor input + Clear button
const inputContainer = document.createElement('div');
inputContainer.style.display = 'flex';
inputContainer.style.gap = '10px';
inputContainer.style.margin = '10px 0';

const neighborInput = document.createElement('input');
neighborInput.type = 'number';
neighborInput.placeholder = '2';
neighborInput.value = neighbors_count;
neighborInput.style.width = '60px';
neighborInput.style.padding = '5px';
neighborInput.id = 'numbersUp_neighbor_input';

neighborInput.addEventListener('input', () => {
    updateSelectedNumbersUp();
    //clearAllNeighbors();
});



const clearButton = document.createElement('button');
clearButton.textContent = 'Clear All';
clearButton.style.padding = '5px 10px';
clearButton.addEventListener('click', () => {
    clearAllNeighbors();
});

inputContainer.appendChild(neighborInput);
inputContainer.appendChild(clearButton);
container.appendChild(inputContainer);

    container.appendChild(onceAllRow);
    container.appendChild(numberRow);

    
// ✅ Reapply clicked highlights after DOM rebuild
for (let num = 0; num <= 36; num++) {
    if (numbersUp_array_clicked[num] === 1) {
        highlightNeighbors(num, parseInt(neighbors_count), true);
    }
}

    return container;
}

function updateSelectedNumbersUp() {
    neighbors_count = parseInt(document.getElementById('numbersUp_neighbor_input').value) || 2;
    
}

function countFrequencies(allSpins) {
    const frequencies = {};
    allSpins.forEach(spin => {
        frequencies[spin] = (frequencies[spin] || 0) + 1;
    });
    return frequencies;
}

function getRecentUniqueNumbers(allSpins, count) {
    const recentUniqueNumbers = new Set();
    for (let i = allSpins.length - 1; i >= 0 && recentUniqueNumbers.size < count; i--) {
        recentUniqueNumbers.add(allSpins[i]);
    }
    return Array.from(recentUniqueNumbers);
}

function clearSecondRowHighlights() {
    for (let num = 0; num <= 36; num++) {
        numbersUp_array_clicked[num] = 0;
        numbersUp_array_highlight[num] = 0;

        const numBox = document.getElementById(`numbersup_${num}`);
        if (!numBox) continue;

        // Reset background color
        if (num === 0) {
            numBox.style.backgroundColor = 'rgb(146, 196, 150)';
        } else if (numRed.includes(num)) {
            numBox.style.backgroundColor = 'rgb(221, 82, 82)';
        } else if (numBlack.includes(num)) {
            numBox.style.backgroundColor = 'rgb(68, 60, 60)';
        }

        numBox.style.color = 'white';
    }

    numbersUpHighlights = [];
}


function highlightNeighbors(num, count, addHighlight) {
    let highlighted = [];
    let wheelIndex = wheelnumbersAC.indexOf(num);
    for (let i = -count; i <= count; i++) {
        let neighborIndex = (wheelIndex + i + 37) % 37;
        let target = wheelnumbersAC[neighborIndex];
        let cell = document.querySelector(`#numbersup_${target}`);
        if (!cell) continue;
        highlighted.push(target);

        if (addHighlight) {
            if (numbersUp_array_clicked[target] === 1 || i === 0) {
                cell.style.backgroundColor = 'rgb(113, 214, 253)';
                cell.style.color = 'black';
            } else {
                cell.style.backgroundColor = 'yellow';
                cell.style.color = 'black';
            }
        } else {
            if (numbersUp_array_highlight[target] <= 0 && numbersUp_array_clicked[target] === 0) {
                cell.style.backgroundColor = numRed.includes(target)
                    ? 'rgb(221, 82, 82)'
                    : numBlack.includes(target)
                        ? 'rgb(68, 60, 60)'
                        : 'rgb(146, 196, 150)';
                cell.style.color = 'white';
            } else if (numbersUp_array_highlight[target] > 0 && numbersUp_array_clicked[target] === 0) {
                cell.style.backgroundColor = 'yellow';
            }
        }
    }
    return highlighted;
}


function toggleNeighborHighlight_OLD(numbers) {
    const center = numbers[Math.floor(numbers.length / 2)];
    const index = numbersUpHighlights.indexOf(center);

    if (index !== -1) {
        numbersUp_array_clicked[center] = 0;
        numbers.forEach(x => numbersUp_array_highlight[x]--);
        numbersUpHighlights.splice(index, 1);
        highlightNeighbors(center, parseInt(selected_numbersUp), false);
    } else {
        numbersUp_array_clicked[center] = 1;
        numbers.forEach(x => numbersUp_array_highlight[x]++);
        numbersUpHighlights.push(center);
        highlightNeighbors(center, parseInt(selected_numbersUp), true);
    }
}

function toggleNeighborHighlight(numbers) {
    const center = numbers[Math.floor(numbers.length / 2)];
    const index = numbersUpHighlights.indexOf(center);

    if (index !== -1) {

    // UNHIGHLIGHTING
    numbersUp_array_clicked[center] = 0;
    numbers.forEach(x => numbersUp_array_highlight[x]--);
    numbersUpHighlights.splice(index, 1);
    highlightNeighbors(center, neighbors_count, false);

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

        if (div) {
            if (numbersUp_array_highlight[item] <= 0) {
                removeAllNeighborHighlightsFromElement(div);
            }

            const betType = item === 0 ? 'zero' : 'inside_whole';

            console.log("REMOVED BET IN TOGGKE ",item);
            console.log("Bet before ",bet);
            removeBet(div, item, betType, 35);
            console.log("Bet after ",bet);

            // ⬇️ INSERT THIS BLOCK HERE
            if (!div.classList.contains('neighbors-highlights')) {
                let loopCount = 0;
                const maxLoops = 100;

                let betEntry = bet.find(b => b.numbers === item.toString() && b.type === betType);

                while (betEntry && betEntry.amt > 0 && loopCount < maxLoops) {
                    removeBet(div, item, betType, 35);
                    betEntry = bet.find(b => b.numbers === item.toString() && b.type === betType);
                    loopCount++;
                }

                if (loopCount >= maxLoops) {
                    console.warn(`Stopped removing ${betType} bet for ${item} after ${maxLoops} attempts`);
                }
            }
        }
    });


    } else {
        console.log("THE ELSE FUNCTION");
        numbersUp_array_clicked[center] = 1;
        numbers.forEach(x => numbersUp_array_highlight[x]++);
        numbersUpHighlights.push(center);
        highlightNeighbors(center, parseInt(neighbors_count), true);
    }
    
}



function numbersUp_createCells(num, frequency, recentUniqueNumbers) {
    const numberCell = document.createElement('div');
    const onceAllCell = document.createElement('div');

    numberCell.innerText = num;
    onceAllCell.innerText = frequency;

    numberCell.id = `numbersup_${num}`;

    [numberCell, onceAllCell].forEach(cell => {
        cell.style.width = '32px';
        cell.style.height = '25px';
        cell.style.display = 'flex';
        cell.style.justifyContent = 'center';
        cell.style.alignItems = 'center';
        cell.style.border = '1px solid black';
    });

    numberCell.style.color = 'white';
    onceAllCell.style.color = 'black';

    if (numRed.includes(num)) {
        numberCell.style.backgroundColor = 'rgb(221, 82, 82)';
    } else if (numBlack.includes(num)) {
        numberCell.style.backgroundColor = 'rgb(68, 60, 60)';
    } else if (num === 0) {
        numberCell.style.backgroundColor = 'rgb(146, 196, 150)';
    }


    numberCell.addEventListener('mouseover', () => {
    updateSelectedNumbersUp();  // updates neighbors_count from input
    if (numbersUp_array_clicked[num] === 0) {
        highlightNeighbors(num, neighbors_count, true);
    }
});

// ✅ Mouseout - remove highlights if not clicked
numberCell.addEventListener('mouseout', () => {
    if (numbersUp_array_clicked[num] === 0) {
        highlightNeighbors(num, neighbors_count, false);
    }
});

// ✅ Click - toggle lock/unlock highlight state
numberCell.addEventListener('click', () => {
    const neighbors = highlightNeighbors(num, neighbors_count, true);  // get neighbors in wheel order
    toggleNeighborHighlight(neighbors);  // lock or unlock

      neighbors.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.click(); // simulates placing a bet
    });
removeBetsForUnhighlightedNumbersUp();


});
/*
    numberCell.addEventListener('mouseover', () => {
        updateSelectedNumbersUp();
        if (numbersUp_array_clicked[num] === 0) {
            highlightNeighbors(num, parseInt(neighbors_count), true);
        }
    });

    numberCell.addEventListener('mouseout', () => {
        if (numbersUp_array_clicked[num] === 0) {
            highlightNeighbors(num, parseInt(neighbors_count), false);
        }
    });


    numberCell.addEventListener('click', () => {
    const neighbors = highlightNeighbors(num, parseInt(neighbors_count), true);
    toggleNeighborHighlight(neighbors);

    neighbors.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.click(); // simulates placing a bet
    });
removeBetsForUnhighlightedNumbersUp();
});
*/

    if (recentUniqueNumbers.includes(num)) {
        onceAllCell.style.backgroundColor = 'yellow';
    }

    return [numberCell, onceAllCell];
}

function removeBetsForUnhighlightedNumbersUp() {
    for (let num = 0; num <= 36; num++) {
        const numBox = document.getElementById(`numbersup_${num}`);
        if (!numBox) continue;

        const bg = numBox.style.backgroundColor.trim();
        console.log("BACKGROND ",bg);
        // Adjust these conditions if your highlight colors are different
        const isHighlighted = (bg === 'yellow' || bg === 'rgb(113, 214, 253)');

        if (!isHighlighted) {
            const betDiv = num === 0
                ? document.querySelector(`div[data-values="zero_${num}"]`)
                : document.querySelector(`div[data-values="${num}"]`);

            const betType = num === 0 ? 'zero' : 'inside_whole';

            if (betDiv) {
                let loopCount = 0;
                const maxLoops = 100;
                let betEntry = bet.find(b => b.numbers === num.toString() && b.type === betType);

                while (betEntry && betEntry.amt > 0 && loopCount < maxLoops) {
                    removeBet(betDiv, num, betType, 35);
                    betEntry = bet.find(b => b.numbers === num.toString() && b.type === betType);
                    loopCount++;
                }

                if (loopCount >= maxLoops) {
                    console.warn(`Stopped removing ${betType} bet for ${num} after ${maxLoops} attempts`);
                }
            }
        }
    }
}
function clearAllNeighbors() {
    for (let num = 0; num <= 36; num++) {
        const numBox = document.getElementById(`numbersup_${num}`);
        if (!numBox) continue;

        // Reset highlight arrays
        numbersUp_array_highlight[num] = 0;
        numbersUp_array_clicked[num] = 0;

        // Reset color
        if (num === 0) {
            numBox.style.backgroundColor = 'rgb(146, 196, 150)';
        } else if (numRed.includes(num)) {
            numBox.style.backgroundColor = 'rgb(221, 82, 82)';
        } else if (numBlack.includes(num)) {
            numBox.style.backgroundColor = 'rgb(68, 60, 60)';
        }

        numBox.style.color = 'white';

        // Remove all matching bets
        const betDiv = num === 0
            ? document.querySelector(`div[data-values="zero_${num}"]`)
            : document.querySelector(`div[data-values="${num}"]`);
        const betType = num === 0 ? 'zero' : 'inside_whole';

        if (betDiv) {
            let loopCount = 0;
            const maxLoops = 100;
            let betEntry = bet.find(b => b.numbers === num.toString() && b.type === betType);

            while (betEntry && betEntry.amt > 0 && loopCount < maxLoops) {
                removeBet(betDiv, num, betType, 35);
                betEntry = bet.find(b => b.numbers === num.toString() && b.type === betType);
                loopCount++;
            }

            if (loopCount >= maxLoops) {
                console.warn(`Stopped removing ${betType} bet for ${num} after ${maxLoops} attempts`);
            }
        }
    }

    numbersUpHighlights = [];
}

