

// 5000 means the event happens after 5 seconds.
let turn_on_overlay = 5000;
let turn_off_overlay = 10000;
const startNumber = Math.floor(Math.random() * 37);

const initialDegree = calculateDegreeForNumber(startNumber);
let currentDegree = calculateDegreeForNumber(startNumber);

/*
function calculateDegreeForNumber(number) {
    return number * 9.73;  // Adjust this factor as per wheel segmentation
}*/

function resetGame() {
	bankValue = 1000;
	currentBet = 0;
	wager = 5;
	lastBets = [];
	bet = [];
	numbersBet = [];
	previousNumbers = [];
	document.getElementById('betting_board').remove();
	document.getElementById('notification').remove();
	buildBettingBoard();
	session_user_amount = 0;
	console.log("reset session ",session_user_amount);
	let user_session_profit = document.getElementById('session-profit-box')
	if(user_session_profit)
	{
		user_session_profit.value = 0;
	}
	everyBetClick();
	
}

function undo() {


	numberHistory.pop();
	numbers.pop();


	if (numbers.length > 0) {
		showNumberUp(numbers[numbers.length - 1]);
	}
	else {
		showNumberUp("x");
	}
	popHistory();

	showHistoryBoard();



	document.getElementById('spins').innerText = numbers.length;


	end_of_undo_tasks();

}



function timer_turn_on_overlay() {
    
    setTimeout(function () {
       
        const bettingBoard = document.getElementById('betting_board');
       bettingBoard.style.pointerEvents = 'none';
        bettingBoard.style.opacity = '0.5';
    }, turn_on_overlay);
}


function timer_turn_off_overlay(winningSpin, callback) {
	setTimeout(function () {
		const quickSpinButton = document.getElementById("quick-spin-button");
		quickSpinButton.disabled = false;
		quickSpinButton.style.opacity = '1.0';

		const bettingBoard = document.getElementById('betting_board');
		bettingBoard.style.pointerEvents = 'auto';
		bettingBoard.style.opacity = '1.0';

		if (bouncyDozenBetPlaced) global_win_loss = 0;
		if (bouncyDozenBetPlaced_bounceRow) global_win_loss_bounceRow = 0;

		if (numbersBet.includes(winningSpin)) {
			let winValue = 0, betOnWins = 0, betOnLosses = 0, profit = 0;

			for (let i = 0; i < bet.length; i++) {
				let numArray = bet[i].numbers.split(',').map(Number);

				if (numArray.includes(winningSpin)) {
					bankValue += (bet[i].odds * bet[i].amt) + bet[i].amt;
					winValue += (bet[i].odds * bet[i].amt);
					betOnWins += bet[i].amt;
					session_user_amount += (bet[i].odds * bet[i].amt) + bet[i].amt;
					
					
					
				} else {
					betOnLosses += bet[i].amt;
				}

				if (bouncyDozenBetPlaced && checkIfEqualToDozen(numArray) && numArray.includes(winningSpin)) {
					global_win_loss = 1;
				}
				if (bouncyDozenBetPlaced_bounceRow && checkIfEqualToRows(numArray) && numArray.includes(winningSpin)) {
					global_win_loss_bounceRow = 1;
				}
			}

			profit = winValue - betOnLosses;
			system_win_loss = 2;
			win(profit, winValue);
		} else if (bet.length > 0) {
			system_win_loss = 2;
			if (bouncyDozenBetPlaced) global_win_loss = 0;
			if (bouncyDozenBetPlaced_bounceRow) global_win_loss_bounceRow = 0;
		}

		end_of_spin_tasks();
		showNumberUp(winningSpin);

		const number_sound = document.getElementById(`play_number_${winningSpin}`);
		if (number_sound) number_sound.play();

		if (typeof callback === 'function') {
			callback(); // ✅ Let the caller know we're done
		}
		 if (document.getElementById('autoBetPanel') && window.AutoBet?.onSpinResolved) {
  window.AutoBet.onSpinResolved();
}

	}, turn_off_overlay);
}


function buildWheel() {
	let wheel = document.createElement('div');
	wheel.setAttribute('class', 'wheel');

	let outerRim = document.createElement('div');
	outerRim.setAttribute('class', 'outerRim');
	wheel.append(outerRim);

	let numbers = [0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26];
	for (i = 0; i < numbers.length; i++) {
		let a = i + 1;
		let spanClass = (numbers[i] < 10) ? 'single' : 'double';
		let sect = document.createElement('div');
		sect.setAttribute('id', 'sect' + a);
		sect.setAttribute('class', 'sect');
		let span = document.createElement('span');
		span.setAttribute('class', spanClass);
		span.innerText = numbers[i];
		sect.append(span);
		let block = document.createElement('div');
		block.setAttribute('class', 'block');
		sect.append(block);
		wheel.append(sect);
	}

	let pocketsRim = document.createElement('div');
	pocketsRim.setAttribute('class', 'pocketsRim');
	wheel.append(pocketsRim);

	let ballTrack = document.createElement('div');
	ballTrack.setAttribute('class', 'ballTrack');
	let ball = document.createElement('div');
	ball.setAttribute('class', 'ball');

	// Set Ball at a random spot
// Set the starting number and calculate the degree
// Set the starting number and calculate the initial degree
		

		// Define and apply initial rotation to start the ball at the starting number
		ballTrack.style.transform = `rotate(-${initialDegree}deg)`;

		// Define the keyframe for stopping the ball later on (optional setup if you need it)
		let style = document.createElement('style');
		style.type = 'text/css';
		style.innerText = `
		@keyframes ballStop {
			from { transform: rotate(${initialDegree}deg); }
			to { transform: rotate(-${initialDegree}deg); }
		}
		`;
		document.head.appendChild(style);

		// Apply the stop animation to the ball track
		ballTrack.style.animation = 'ballStop 2s linear forwards';

	ballTrack.append(ball);
	

	wheel.append(ballTrack);

	let pockets = document.createElement('div');
	pockets.setAttribute('class', 'pockets');
	wheel.append(pockets);

	let cone = document.createElement('div');
	cone.setAttribute('class', 'cone');
	wheel.append(cone);

	let turret = document.createElement('div');
	turret.setAttribute('class', 'turret');
	wheel.append(turret);

	let turretHandle = document.createElement('div');
	turretHandle.setAttribute('class', 'turretHandle');
	let thendOne = document.createElement('div');
	thendOne.setAttribute('class', 'thendOne');
	turretHandle.append(thendOne);
	let thendTwo = document.createElement('div');
	thendTwo.setAttribute('class', 'thendTwo');
	turretHandle.append(thendTwo);
	wheel.append(turretHandle);


	return wheel;
}
function wheelAlertWindow() {
	let container = document.createElement('div');
	container.id = 'item-alert-container-on-table';
	container.className = `wheel-alert-window`;
	container.style.display = 'none';
	const header = document.createElement('div');
	const scrollableDiv = document.createElement('div');

	// Set class names
	header.className = 'header-bet-list';
	scrollableDiv.className = 'scrollable-div-bet-list';
	scrollableDiv.id = 'trigger-items-list';

	// Set header text
	header.textContent = 'Trigger Bet List';

	// Append header to container
	container.appendChild(header);

	// Create bet items and append to scrollable div
	const betItem = document.createElement('div');
	betItem.className = 'bet-item-bet-list';
	scrollableDiv.appendChild(betItem);

	// Append scrollable div to container
	container.appendChild(scrollableDiv);

	return container;
}
function toggleButtonTriggerWindow() {
	// Button
	let button = document.createElement('button');
	button.className = `bulk-button-bet-list`;
	button.textContent = `Toggle Alert List`;

	button.addEventListener('click', () => {
		const itemAlertContainer = document.getElementById('item-alert-container-on-table');
		if (itemAlertContainer.style.display === 'none' || itemAlertContainer.style.display === '') {
			itemAlertContainer.style.display = 'block';
			button.classList.add('active');
		} else {
			itemAlertContainer.style.display = 'none';
			button.classList.remove('active');
		}
	});

	return button;
}
function buildBettingBoard() {

	let bettingBoard = document.createElement('div');
	bettingBoard.setAttribute('id', 'betting_board');

	let wl = document.createElement('div');
	wl.setAttribute('class', 'winning_lines');

	// Lines
	var wlttb = document.createElement('div');
	wlttb.setAttribute('id', 'wlttb_top');
	wlttb.dataset.values = 'wlttb_top';
	wlttb.setAttribute('class', 'wlttb');
	for (i = 0; i < 11; i++) {
		let j = i;
		var ttbbetblock = document.createElement('div');
		ttbbetblock.setAttribute('class', 'ttbbetblock');
		var numA = (1 + (3 * j));
		var numB = (2 + (3 * j));
		var numC = (3 + (3 * j));
		var numD = (4 + (3 * j));
		var numE = (5 + (3 * j));
		var numF = (6 + (3 * j));
		let num = numA + ', ' + numB + ', ' + numC + ', ' + numD + ', ' + numE + ', ' + numF;
		var objType = 'double_street';
		ttbbetblock.dataset.values = num;
		ttbbetblock.onclick = function () {

			setBet(this, num, objType, 5);
			everyBetClick();


		};
		ttbbetblock.oncontextmenu = function (e) {
			e.preventDefault();
			removeBet(this, num, objType, 5);
			everyBetClick();

		};
		wlttb.append(ttbbetblock);
	}
	wl.append(wlttb);

	// Streets and Splits
	for (c = 1; c < 4; c++) {
		let d = c;
		var wlttb = document.createElement('div');
		wlttb.setAttribute('id', 'wlttb_' + c);
		wlttb.dataset.values = 'wlttb_' + c;
		wlttb.setAttribute('class', 'wlttb');


		for (i = 0; i < 12; i++) {
			let j = i;
			var ttbbetblock = document.createElement('div');
			ttbbetblock.setAttribute('class', 'ttbbetblock');


			// ## Split
			if (d == 1 || d == 2) {
				var numA = ((2 - (d - 1)) + (3 * j));
				var numB = ((3 - (d - 1)) + (3 * j));
				var num = numA + ', ' + numB;
				ttbbetblock.dataset.values = num;
			}
			else {
				var numA = (1 + (3 * j));
				var numB = (2 + (3 * j));
				var numC = (3 + (3 * j));
				var num = numA + ', ' + numB + ', ' + numC;
				ttbbetblock.dataset.values = num;
			}

			ttbbetblock.onclick = function () {
				if (d == 1 || d == 2) {
					var numA = ((2 - (d - 1)) + (3 * j));
					var numB = ((3 - (d - 1)) + (3 * j));
					var num = numA + ', ' + numB;
					//ttbbetblock.dataset.values = num;
				}
				else {
					var numA = (1 + (3 * j));
					var numB = (2 + (3 * j));
					var numC = (3 + (3 * j));
					var num = numA + ', ' + numB + ', ' + numC;
					//ttbbetblock.dataset.values = num;
				}
				var objType = (d == 3) ? 'street' : 'split';
				var odd = (d == 3) ? 11 : 17;
				setBet(this, num, objType, odd);
				everyBetClick();

			};
			ttbbetblock.oncontextmenu = function (e) {
				e.preventDefault();
				if (d == 1 || d == 2) {
					var numA = ((2 - (d - 1)) + (3 * j));
					var numB = ((3 - (d - 1)) + (3 * j));
					var num = numA + ', ' + numB;
				}
				else {
					var numA = (1 + (3 * j));
					var numB = (2 + (3 * j));
					var numC = (3 + (3 * j));
					var num = numA + ', ' + numB + ', ' + numC;
				}
				var objType = (d == 3) ? 'street' : 'split';
				var odd = (d == 3) ? 11 : 17;
				removeBet(this, num, objType, odd);
				everyBetClick();
			};
			wlttb.append(ttbbetblock);
		}
		wl.append(wlttb);
	}

	for (c = 1; c < 12; c++) {
		let d = c;
		var wlrtl = document.createElement('div');
		wlrtl.setAttribute('id', 'wlrtl_' + c);
		wlrtl.dataset.values = 'wlrtl_' + c;
		wlrtl.setAttribute('class', 'wlrtl');
		for (i = 1; i < 4; i++) {
			let j = i;
			var rtlbb = document.createElement('div');
			rtlbb.setAttribute('class', 'rtlbb' + i);
			var numA = (3 + (3 * (d - 1))) - (j - 1);
			var numB = (6 + (3 * (d - 1))) - (j - 1);
			let num = numA + ', ' + numB;
			rtlbb.dataset.values = num;
			rtlbb.onclick = function () {
				setBet(this, num, 'split', 17);
				everyBetClick();

			};
			rtlbb.oncontextmenu = function (e) {
				e.preventDefault();
				removeBet(this, num, 'split', 17);
				everyBetClick();
			};
			wlrtl.append(rtlbb);
		}
		wl.append(wlrtl);
	}

	for (c = 1; c < 3; c++) {
		var wlcb = document.createElement('div');
		wlcb.setAttribute('id', 'wlcb_' + c);
		wlcb.dataset.values = 'wlcb_' + c;
		wlcb.setAttribute('class', 'wlcb');
		for (i = 1; i < 12; i++) {
			let count = (c == 1) ? i : i + 11;
			var cbbb = document.createElement('div');
			cbbb.setAttribute('id', 'cbbb_' + count);
			cbbb.dataset.values = 'cbbb_' + count;
			cbbb.setAttribute('class', 'cbbb');
			var numA = '2';
			var numB = '3';
			var numC = '5';
			var numD = '6';
			let num = (count >= 1 && count < 12) ? (parseInt(numA) + ((count - 1) * 3)) + ', ' + (parseInt(numB) + ((count - 1) * 3)) + ', ' + (parseInt(numC) + ((count - 1) * 3)) + ', ' + (parseInt(numD) + ((count - 1) * 3)) : ((parseInt(numA) - 1) + ((count - 12) * 3)) + ', ' + ((parseInt(numB) - 1) + ((count - 12) * 3)) + ', ' + ((parseInt(numC) - 1) + ((count - 12) * 3)) + ', ' + ((parseInt(numD) - 1) + ((count - 12) * 3));

			cbbb.dataset.values = num;


			var objType = 'corner_bet';
			cbbb.onclick = function () {
				setBet(this, num, objType, 8);
				everyBetClick();

			};
			cbbb.oncontextmenu = function (e) {
				e.preventDefault();
				removeBet(this, num, objType, 8);
				everyBetClick();
			};
			wlcb.append(cbbb);
		}
		wl.append(wlcb);
	}

	bettingBoard.append(wl);

	let bbtop = document.createElement('div');
	bbtop.setAttribute('class', 'bbtop');
	let bbtopBlocks = ['1 to 18', '19 to 36'];
	for (i = 0; i < bbtopBlocks.length; i++) {
		let f = i;
		var bbtoptwo = document.createElement('div');
		bbtoptwo.setAttribute('class', 'bbtoptwo');
		if (f == 0) { bbtoptwo.setAttribute('id', '1to18'); bbtoptwo.dataset.values = '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18'; }
		if (f == 1) { bbtoptwo.setAttribute('id', '19to36'); bbtoptwo.dataset.values = '19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36'; }
		let num = (f == 0) ? '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18' : '19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36';
		var objType = (f == 0) ? 'outside_low' : 'outside_high';
		bbtoptwo.onclick = function () {
			setBet(this, num, objType, 1);
			everyBetClick();

		};
		bbtoptwo.oncontextmenu = function (e) {
			e.preventDefault();
			removeBet(this, num, objType, 1);
			everyBetClick();
		};
		bbtoptwo.innerText = bbtopBlocks[i];
		bbtop.append(bbtoptwo);
	}
	bettingBoard.append(bbtop);

	let numberBoard = document.createElement('div');
	numberBoard.setAttribute('class', 'number_board');

	let zero = document.createElement('div');
	zero.setAttribute('class', 'number_0');
	zero.setAttribute('id', 'zero_0');
	zero.dataset.values = 'zero_0';
	var objType = 'zero';
	var odds = 35;
	//zero.dataset.values = 0;
	zero.onclick = function () {
	    var objType = 'zero';
		var odds = 35;
		setBet(this, '0', objType, odds);
		everyBetClick();

	};
	zero.oncontextmenu = function (e) {
		e.preventDefault();
	    var objType = 'zero';
		var odds = 35;
		removeBet(this, '0', objType, odds);
		everyBetClick();
	};
	let nbnz = document.createElement('div');
	nbnz.setAttribute('class', 'nbn');
	nbnz.innerText = '0';
	nbnz.dataset.values = 0;

	var innerDiv1 = document.createElement('div');
	innerDiv1.dataset.values = `zdiv1` + 0;
	nbnz.appendChild(innerDiv1);

	var innerDiv2 = document.createElement('div');
	innerDiv2.dataset.values = `zdiv2` + 0;
	nbnz.appendChild(innerDiv2);

	var innerDiv3 = document.createElement('div');
	innerDiv3.dataset.values = `zdiv3` + 0;
	nbnz.appendChild(innerDiv3);

	var innerDiv4 = document.createElement('div');
	innerDiv4.dataset.values = `zdiv4` + 0;
	nbnz.appendChild(innerDiv4);

	zero.append(nbnz);
	numberBoard.append(zero);
	
		//----------------------------------------
	// START: Zero 0-1-2
	//----------------------------------------
	let basket_0_1_2 = document.createElement('div');
	basket_0_1_2.setAttribute('class', 'basket-0-1-2');
	basket_0_1_2.setAttribute('id', 'basket_id_0_1_2');
	basket_0_1_2.dataset.values = '0,1,2';

	//zero.dataset.values = 0;
	basket_0_1_2.onclick = function () {
		var objType = 'basket_t_0_1_2';
		var odds = 11;
		setBet(this, '0,1,2', objType, odds);
		everyBetClick();

	};
	basket_0_1_2.oncontextmenu = function (e) {
		e.preventDefault();
		var objType = 'basket_t_0_1_2';
		var odds = 11;
		removeBet(this, '0,1,2', objType, odds);
		everyBetClick();
	};
	numberBoard.append(basket_0_1_2);
	
	//----------------------------------------
	// END: Zero 0-1-2
	//----------------------------------------

		//----------------------------------------
	// START: Zero 0-2-3 split-0-1
	//----------------------------------------
	let basket_0_2_3 = document.createElement('div');
	basket_0_2_3.setAttribute('class', 'basket-0-2-3');
	basket_0_2_3.setAttribute('id', 'basket_id_0_2_3');
	basket_0_2_3.dataset.values = '0,2,3';
	var objType = 'basket';
	var odds = 11;
	//zero.dataset.values = 0;
	basket_0_2_3.onclick = function () {
		var objType = 'basket_t_0_2_3';
		var odds = 11;
		setBet(this, '0,2,3', objType, odds);
		everyBetClick();

	};
	basket_0_2_3.oncontextmenu = function (e) {
		e.preventDefault();
		var objType = 'basket_t_0_2_3';
		var odds = 11;
		removeBet(this, '0,2,3', objType, odds);
		everyBetClick();
	};
	numberBoard.append(basket_0_2_3);
	
	//----------------------------------------
	// END: Zero 0-1-2-3
	//----------------------------------------

	//----------------------------------------
	// START: Zero 0-1-2-3
	//----------------------------------------
	let basket = document.createElement('div');
	basket.setAttribute('class', 'basket');
	basket.setAttribute('id', 'basket_id');
	basket.dataset.values = '0,1,2,3';

	//zero.dataset.values = 0;
	basket.onclick = function () {
		var objType = 'basket';
		var odds = 8;
		setBet(this, '0,1,2,3', objType, odds);
		everyBetClick();

	};
	basket.oncontextmenu = function (e) {
		e.preventDefault();
		var objType = 'basket';
		var odds = 8;
		removeBet(this, '0,1,2,3', objType, odds);
		everyBetClick();
	};
	numberBoard.append(basket);
	
	//----------------------------------------
	// END: Zero 0-1-2-3
	//----------------------------------------


	//----------------------------------------
	// START: split-0-1
	//----------------------------------------
	let split_0_1 = document.createElement('div');
	split_0_1.setAttribute('class', 'split-0-1');
	split_0_1.setAttribute('id', 'split_0_1');
	split_0_1.dataset.values = '0, 1';
	var objType = 'split';
	var odds = 17;
	//zero.dataset.values = 0;
	split_0_1.onclick = function () {
		var objType = 'split';
		var odds = 17;
		setBet(this, '0, 1', objType, odds);
		everyBetClick();

	};
	split_0_1.oncontextmenu = function (e) {
		e.preventDefault();
		var objType = 'split';
		var odds = 17;
		removeBet(this, '0, 1', objType, odds);
		everyBetClick();
	};
	numberBoard.append(split_0_1);
	
	//----------------------------------------
	// END:  split-0-1
	//----------------------------------------


	//----------------------------------------
	// START: split-0-2
	//----------------------------------------
	let split_0_2 = document.createElement('div');
	split_0_2.setAttribute('class', 'split-0-2');
	split_0_2.setAttribute('id', 'split_0_2');
	split_0_2.dataset.values = '0, 2';
	var objType = 'split';
	var odds = 17;
	//zero.dataset.values = 0;
	split_0_2.onclick = function () {
		var objType = 'split';
		var odds = 17;
		setBet(this, '0, 2', objType, odds);
		everyBetClick();

	};
	split_0_2.oncontextmenu = function (e) {
		e.preventDefault();
		var objType = 'split';
		var odds = 17;
		removeBet(this, '0, 2', objType, odds);
		everyBetClick();
	};
	numberBoard.append(split_0_2);
	
	//----------------------------------------
	// END:  split-0-3
	//----------------------------------------

	
	//----------------------------------------
	// START: split-0-3
	//----------------------------------------
	let split_0_3 = document.createElement('div');
	split_0_3.setAttribute('class', 'split-0-3');
	split_0_3.setAttribute('id', 'split_0_3');
	split_0_3.dataset.values = '0, 1';
	var objType = 'split';
	var odds = 17;
	//zero.dataset.values = 0;
	split_0_3.onclick = function () {
		var objType = 'split';
		var odds = 17;
		setBet(this, '0, 3', objType, odds);
		everyBetClick();

	};
	split_0_3.oncontextmenu = function (e) {
		e.preventDefault();
		var objType = 'split';
		var odds = 17;
		removeBet(this, '0, 3', objType, odds);
		everyBetClick();
	};
	numberBoard.append(split_0_3);
	
	//----------------------------------------
	// END:  split-0-1
	//----------------------------------------



	
	var numberBlocks = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, '2 to 1', 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, '2 to 1', 1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, '2 to 1'];
	var redBlocks = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36];
	for (i = 0; i < numberBlocks.length; i++) {
		let a = i;
		var nbClass = (numberBlocks[i] == '2 to 1') ? 'tt1_block' : 'number_block';
		var colourClass = (redBlocks.includes(numberBlocks[i])) ? ' redNum' : ((nbClass == 'number_block') ? ' blackNum' : '');
		var numberBlock = document.createElement('div');
		numberBlock.setAttribute('class', nbClass + colourClass);
		numberBlock.dataset.values = numberBlocks[i];
		if (i == 12) { numberBlock.setAttribute('id', 'row3'); numberBlock.dataset.values = '3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36'; }
		if (i == 25) { numberBlock.setAttribute('id', 'row2'); numberBlock.dataset.values = '2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35'; }
		if (i == 38) { numberBlock.setAttribute('id', 'row1'); numberBlock.dataset.values = '1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34'; }

		numberBlock.onclick = function () {
			if (numberBlocks[a] != '2 to 1') {
				setBet(this, '' + numberBlocks[a] + '', 'inside_whole', 35);
				everyBetClick();

			} else {
				num = (a == 12) ? '3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36' : ((a == 25) ? '2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35' : '1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34');
				setBet(this, num, 'outside_column', 2);
				everyBetClick();

			}
		};
		numberBlock.oncontextmenu = function (e) {
			e.preventDefault();
			if (numberBlocks[a] != '2 to 1') {
				removeBet(this, '' + numberBlocks[a] + '', 'inside_whole', 35);
			} else {
				num = (a == 12) ? '3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36' : ((a == 25) ? '2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35' : '1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34');
				removeBet(this, num, 'outside_column', 2);
			}
		};
		var nbn = document.createElement('div');
		nbn.setAttribute('class', 'nbn');
		nbn.innerText = numberBlocks[i];
		nbn.dataset.values = numberBlocks[i];

		var innerDiv1 = document.createElement('div');
		innerDiv1.dataset.values = `div1` + numberBlocks[i];
		nbn.appendChild(innerDiv1);

		var innerDiv2 = document.createElement('div');
		innerDiv2.dataset.values = `div2` + numberBlocks[i];
		nbn.appendChild(innerDiv2);

		var innerDiv3 = document.createElement('div');
		innerDiv3.dataset.values = `div3` + numberBlocks[i];
		nbn.appendChild(innerDiv3);

		var innerDiv4 = document.createElement('div');
		innerDiv4.dataset.values = `div4` + numberBlocks[i];
		nbn.appendChild(innerDiv4);

		numberBlock.append(nbn);
		numberBoard.append(numberBlock);
	}
	bettingBoard.append(numberBoard);

	let bo3Board = document.createElement('div');
	bo3Board.setAttribute('class', 'bo3_board');
	let bo3Blocks = ['1 to 12', '13 to 24', '25 to 36'];
	for (i = 0; i < bo3Blocks.length; i++) {
		let b = i;
		var bo3Block = document.createElement('div');
		bo3Block.setAttribute('class', 'bo3_block');
		if (i == 0) { bo3Block.setAttribute('id', 'dozen1'); bo3Block.dataset.values = '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12'; }
		if (i == 1) { bo3Block.setAttribute('id', 'dozen2'); bo3Block.dataset.values = '13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24'; }
		if (i == 2) { bo3Block.setAttribute('id', 'dozen3'); bo3Block.dataset.values = '25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36'; }

		bo3Block.onclick = function () {
			num = (b == 0) ? '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12' : ((b == 1) ? '13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24' : '25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36');
			setBet(this, num, 'outside_dozen', 2);
			everyBetClick();

		};
		bo3Block.oncontextmenu = function (e) {
			e.preventDefault();
			num = (b == 0) ? '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12' : ((b == 1) ? '13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24' : '25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36');
			removeBet(this, num, 'outside_dozen', 2);
			everyBetClick();
		};
		bo3Block.innerText = bo3Blocks[i];
		bo3Board.append(bo3Block);
	}
	bettingBoard.append(bo3Board);

	let otoBoard = document.createElement('div');
	otoBoard.setAttribute('class', 'oto_board');
	let otoBlocks = ['EVEN', 'RED', 'BLACK', 'ODD'];
	for (i = 0; i < otoBlocks.length; i++) {
		let d = i;
		//var colourClass = (otoBlocks[i] == 'RED') ? ' redNum' : ((otoBlocks[i] == 'BLACK') ? ' blackNum' : '');
		var colourClass = '';
		var otoBlock = document.createElement('div');
		otoBlock.setAttribute('class', 'oto_block' + colourClass);
		if (i == 0) { otoBlock.setAttribute('id', 'outsideEven'); otoBlock.dataset.values = '2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36'; }
		if (i == 1) { otoBlock.setAttribute('id', 'outsideRed'); otoBlock.dataset.values = '1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36'; }
		if (i == 2) { otoBlock.setAttribute('id', 'outsideBlack'); otoBlock.dataset.values = '2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35'; }
		if (i == 3) { otoBlock.setAttribute('id', 'outsideOdd'); otoBlock.dataset.values = '1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35'; }
		otoBlock.onclick = function () {
			num = (d == 0) ? '2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36' : ((d == 1) ? '1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36' : ((d == 2) ? '2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35' : '1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35'));
			setBet(this, num, 'outside_oerb', 1);
			everyBetClick();

		};
		otoBlock.oncontextmenu = function (e) {
			num = (d == 0) ? '2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36' : ((d == 1) ? '1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36' : ((d == 2) ? '2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35' : '1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35'));
			e.preventDefault();
			removeBet(this, num, 'outside_oerb', 1);
			everyBetClick();
		};
		otoBlock.innerText = otoBlocks[i];
		otoBoard.append(otoBlock);
	}
	bettingBoard.append(otoBoard);

let chipDeck = document.createElement('div');
chipDeck.setAttribute('class', 'chipDeck');
let chipValues = [1, 5, 10, 100, 'clear'];
let firstChip;  // To store the first chip (chip unit 1)

for (let i = 0; i < chipValues.length; i++) {
	let cvi = i;
	let chipColour = (i == 0) ? 'red cdChipActive' : ((i == 1) ? 'blue' : ((i == 2) ? 'orange' : ((i == 3) ? 'gold' : 'clearBet')));
	let chip = document.createElement('div');
	chip.setAttribute('class', 'cdChip ' + chipColour);
	let chipSpan = document.createElement('span');
	chipSpan.id = '2_chip_span_id_' + global_chip_span_id_counter;
	chipSpan.setAttribute('class', 'cdChipSpan');
	chipSpan.innerText = chipValues[i];
	chip.append(chipSpan);
	chipDeck.append(chip);

	if (i === 0) {
		firstChip = chip;  // Store the chip with value 1
	}

	chip.onclick = function () {
		if (cvi !== 4) {
			let cdChipActive = document.getElementsByClassName('cdChipActive');
			for (let j = 0; j < cdChipActive.length; j++) {
				cdChipActive[j].classList.remove('cdChipActive');
			}
			let curClass = this.getAttribute('class');
			if (!curClass.includes('cdChipActive')) {
				this.setAttribute('class', curClass + ' cdChipActive');
			}
			wager = parseInt(chip.childNodes[0].innerText);
		} else {
			bankValue = bankValue + currentBet;
			session_user_amount = session_user_amount + currentBet;
			

			
			currentBet = 0;
			document.getElementById('bankSpan').innerText = '' + bankValue.toLocaleString("en-GB") + '';
			document.getElementById('betSpan').innerText = '' + currentBet.toLocaleString("en-GB") + '';
			global_chip_id.push(document.getElementById('betSpan').id);
			global_chip_amt.push(wager);
			clearBet();
			removeChips();
		}
	};
}

chipDeck.addEventListener('contextmenu', function (e) {
	e.preventDefault();
});






	bettingBoard.append(chipDeck);


	// Automatically trigger selection of the first chip (chip unit 1)
if (firstChip) {
	firstChip.click();  // Simulate a click to select chip unit 1
}

	let bankContainer = document.createElement('div');
	bankContainer.setAttribute('class', 'bankContainer');


	var id = 'bankroll-button-id';
	var draggableDiv = changeBankRollPopup(id);
	bankContainer.addEventListener('click', function (event) {


		draggableDiv.style.display = 'block';
		var mouseX = event.clientX;
		var mouseY = event.clientY;
		draggableDiv.style.left = mouseX + 'px';
		draggableDiv.style.top = mouseY + 'px';
	});



	let bank = document.createElement('div');
	bank.setAttribute('class', 'bank');
	let bankSpan = document.createElement('span');
	bankSpan.setAttribute('id', 'bankSpan');
	bankSpan.innerText = '' + bankValue.toLocaleString("en-GB") + '';
	bank.append(bankSpan);
	bankContainer.append(bank);


	let bet = document.createElement('div');
	bet.setAttribute('class', 'bet');
	let betSpan = document.createElement('span');
	betSpan.setAttribute('id', 'betSpan');
	betSpan.innerText = '' + currentBet.toLocaleString("en-GB") + '';
	bet.append(betSpan);
	bankContainer.append(bet);
	bettingBoard.append(bankContainer);

	var resetButton = document.createElement("button");
	resetButton.id = 'resetButton';
	resetButton.className = 'button-55';
	resetButton.innerHTML = "Reset All";
	resetButton.addEventListener("click", function () {
		resetHistoryCache();
		location.reload();
		everyBetClick();
	});
	bettingBoard.append(resetButton);

	var clearButton = document.createElement("button");
	clearButton.id = 'clearSpinsButton';
	clearButton.className = 'button-55';
	clearButton.innerHTML = "Clear Spins";
	clearButton.addEventListener("click", function () {
		numbers = [];
		numberHistory = [];
		tableChart = [];
		masterEdgeChart = [];
		undo();
		everyBetClick();
	});
	//bettingBoard.append(clearButton);




	/*	let pnBlock = document.createElement('div');
		pnBlock.setAttribute('class', 'pnBlock');
		let pnContent = document.createElement('div');
		pnContent.setAttribute('id', 'pnContent');
		pnContent.onwheel = function(e){
			e.preventDefault();
			pnContent.scrollLeft += e.deltaY;
		};
		pnBlock.append(pnContent);	
		bettingBoard.append(pnBlock);
	*/
	let button = document.createElement('button');
	button.className = 'button-55';
	button.setAttribute('role', 'button');
	button.setAttribute('id', 'quick-spin-button');
	button.innerText = 'Quick Spin';

	
	button.addEventListener('click', () => {
  button.disabled = true;

  quickSpin(); // call your function

  setTimeout(() => {
    button.disabled = false;
  }, 500); // 1 second delay
});

	let buttonRebet = document.createElement('button');
	buttonRebet.className = 'button-55';
	buttonRebet.setAttribute('role', 'button');
	buttonRebet.setAttribute('id', 'rebet-spin-button');
	buttonRebet.innerText = 'Rebet';
	buttonRebet.addEventListener("click", function (event) {
		event.preventDefault();
		rebet();
		rebetMultiplier = 2;
		everyBetClick();
	});

	let buttonRebet2 = document.createElement('button');
	buttonRebet2.className = 'button-55';
	buttonRebet2.setAttribute('role', 'button');
	buttonRebet2.setAttribute('id', 'double-spin-button');
	buttonRebet2.innerText = '2x';
	buttonRebet2.addEventListener("click", function (event) {
		bet_double();
		everyBetClick();
	});

	
//-----------------------------------------------------------------------------
// PLUS MINUS BUTTONS
//-----------------------------------------------------------------------------
const rebetButtonWrapper = document.createElement('div');
rebetButtonWrapper.className = 'button-rebet-wrapper';

// Create a container for the rebet buttons
const rebetButtonContainer = document.createElement('div');
rebetButtonContainer.className = 'button-rebet-container';

// Create the "Add" button
let buttonRebetAdd = document.createElement('button');
buttonRebetAdd.className = 'button-rebet-plus';
buttonRebetAdd.setAttribute('role', 'button');
buttonRebetAdd.setAttribute('id', 'rebet-spin-button-add');
buttonRebetAdd.innerText = '+';
buttonRebetAdd.addEventListener("click", function (event) {
    
	bet_add();
	everyBetClick();
});

// Create the "Minus" button
let buttonRebetMinus = document.createElement('button');
buttonRebetMinus.className = 'button-rebet-minus';
buttonRebetMinus.setAttribute('role', 'button');
buttonRebetMinus.setAttribute('id', 'rebet-spin-button-minus');
buttonRebetMinus.innerText = '-';
buttonRebetMinus.addEventListener("click", function (event) {
	bet_minus();
	everyBetClick();
});

// Append the buttons to the container
rebetButtonContainer.appendChild(buttonRebetAdd);
rebetButtonContainer.appendChild(buttonRebetMinus);

// Append the container to the wrapper
rebetButtonWrapper.appendChild(rebetButtonContainer);


	bettingBoard.append(button);
	if (showRebetButton) {
		bettingBoard.append(buttonRebet);
		bettingBoard.append(buttonRebet2);
		bettingBoard.append(rebetButtonWrapper);



	}
	

	let showBetList = document.createElement('button');
	showBetList.className = 'button-55';
	showBetList.setAttribute('role', 'button');
	showBetList.setAttribute('id', 'show-bet-list-button');
	showBetList.innerText = 'Show Bet List';
	showBetList.addEventListener("click", function (event) {
		event.preventDefault();
		if(betHistory) betHistory.classList.remove('hidden');
		everyBetClick();
	});
	bettingBoard.append(showBetList);

	let spinButtonSpinNumbers = spinButtonSpins();
	bettingBoard.append(spinButtonSpinNumbers);






	return bettingBoard;
}

function clearBet() {
	
	
	lastBets = JSON.parse(JSON.stringify(bet));
	bet = [];
	numbersBet = [];
	redo_lastThis = [];
	redo_amount = [];
	redo_target = [];
	redo_odds = [];
	redo_wager = [];
	everyBetClick();

}

function setBet(e, n, t, o) {

	redo_amount.push(n);
	redo_target.push(t);
	redo_odds.push(o);
	redo_wager.push(wager);


	lastWager = wager;
	wager = (bankValue < wager) ? bankValue : wager;
	if (wager > 0) {

		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);
		}
		bankValue = bankValue - wager;

		session_user_amount = session_user_amount - wager;


		currentBet = currentBet + wager;
		document.getElementById('bankSpan').innerText = '' + bankValue.toLocaleString("en-GB") + '';
		document.getElementById('betSpan').innerText = '' + currentBet.toLocaleString("en-GB") + '';
		for (i = 0; i < bet.length; i++) {
			if (bet[i].numbers == n && bet[i].type == t) {
				bet[i].amt = bet[i].amt + wager;
				let chipColour = (bet[i].amt < 5) ? 'red' : ((bet[i].amt < 10) ? 'blue' : ((bet[i].amt < 100) ? 'orange' : 'gold'));
				e.querySelector('.chip').style.cssText = '';
				e.querySelector('.chip').setAttribute('class', 'chip ' + chipColour);
				let chipSpan = e.querySelector('.chipSpan');
				chipSpan.innerText = bet[i].amt;
				zzzsetBet(e, bet[bet.length - 1]);
				everyBetClick();
				return;
			}
		}
		var obj = {
			amt: wager,
			type: t,
			odds: o,
			numbers: n
		};
		bet.push(obj);



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

		if (!e.querySelector('.chip')) {
			let chipColour = (wager < 5) ? 'red' : ((wager < 10) ? 'blue' : ((wager < 100) ? 'orange' : 'gold'));
			let chip = document.createElement('div');
			chip.setAttribute('class', 'chip ' + chipColour);
			let chipSpan = document.createElement('span');
			chipSpan.setAttribute('class', 'chipSpan');
			chipSpan.innerText = wager;
			chip.append(chipSpan);
			e.append(chip);
		}
	}

	zzzsetBet(e, bet[bet.length - 1]);
	everyBetClick();

	let clone_e = e.cloneNode(true);
	current_bets = JSON.parse(JSON.stringify(bet));
redo_lastThis.push(clone_e);
}

function spin() {
	return new Promise((resolve) => {
		randomNumberCount += 1;
		rebetMultiplier = 2;
		setOldBet();

		let winAlertContainer = document.getElementById('winAlertContainerId');
		winAlertContainer.innerHTML = '';

		if (redo_lastThis.length > 0) {
			rebet_lastThis = [];
			rebet_amount = [];
			rebet_target = [];
			rebet_odds = [];
			rebet_wager = [];

			for (let x = 0; x < redo_lastThis.length; x++) {
				rebet_lastThis.push(redo_lastThis[x]);
				rebet_amount.push(redo_amount[x]);
				rebet_target.push(redo_target[x]);
				rebet_odds.push(redo_odds[x]);
				rebet_wager.push(redo_wager[x]);
			}
		}

		redo_lastThis = [];
		redo_amount = [];
		redo_target = [];
		redo_odds = [];
		redo_wager = [];

		let winningSpin = Math.floor(Math.random() * 37);
		numberHistory.push(winningSpin);
		numbers.push(winningSpin);

		document.getElementById("quick-spin-button").disabled = true;
		document.getElementById("quick-spin-button").style.opacity = '0.5';

		spinWheel(winningSpin);
		timer_turn_on_overlay();

		// Wrap timer_turn_off_overlay with a callback to know when it’s done
		timer_turn_off_overlay(winningSpin, resolve);
	});
}

function numberPadSpin(n, runCalls = true) {
	global_win_loss = 3;
	global_win_loss_bounceRow = 3;
	simulation_win_loss = false;


	rebetMultiplier = 2;
	setOldBet();
	showNumberUp(n);
	let winAlertContainer = document.getElementById('winAlertContainerId');
	winAlertContainer.innerHTML = '';

	if (redo_lastThis.length > 0) {
		rebet_lastThis = [];
		rebet_amount = [];
		rebet_target = [];
		rebet_odds = [];

		for (var x = 0; x < redo_lastThis.length; x++) {
			rebet_lastThis.push(redo_lastThis[x]);
			rebet_amount.push(redo_amount[x]);
			rebet_target.push(redo_target[x]);
			rebet_odds.push(redo_odds[x]);
			rebet_wager.push(redo_wager[x]);
		}

	}

	redo_lastThis = [];
	redo_amount = [];
	redo_target = [];
	redo_odds = [];
	redo_wager = [];

	var winningSpin = parseInt(n);
	numberHistory.push(winningSpin);
	numbers.push(winningSpin);



	if (bouncyDozenBetPlaced) global_win_loss = 0;
	if (bouncyDozenBetPlaced_bounceRow) global_win_loss_bounceRow = 0;



	if (numbersBet.includes(winningSpin)) {

		let winValue = 0;
		let betOnWins = 0;
		let betOnLosses = 0;
		let profit = 0;
		for (i = 0; i < bet.length; i++) {
			var numArray = bet[i].numbers.split(',').map(Number);

			if (numArray.includes(winningSpin)) {
				bankValue = (bankValue + (bet[i].odds * bet[i].amt) + bet[i].amt);
				session_user_amount = (session_user_amount + (bet[i].odds * bet[i].amt) + bet[i].amt);
			
		
				winValue = winValue + (bet[i].odds * bet[i].amt);
				betOnWins = betOnWins + bet[i].amt;
			}
			else {
				betOnLosses = betOnLosses + bet[i].amt;
			}


			if (bouncyDozenBetPlaced && checkIfEqualToDozen(numArray) && numArray.includes(winningSpin)) {
				global_win_loss = 1;





			}

			if (bouncyDozenBetPlaced_bounceRow && checkIfEqualToRows(numArray) && numArray.includes(winningSpin)) {


				global_win_loss_bounceRow = 1;
			}



		}

		profit = winValue - betOnLosses;
		system_win_loss = 2;
		win(profit, winValue);

	}
	else {
		system_win_loss = 2;
		if (bet.length > 0) {
			if (bouncyDozenBetPlaced) {
				global_win_loss = 0;

			}
			if (bouncyDozenBetPlaced_bounceRow) {
				global_win_loss_bounceRow = 0;

			}


		}
	}
	end_of_spin_tasks();






}
function quickSpin() {


	// Use document.getElementById to grab the input element by its ID
	var inputValue = document.getElementById('number-input').value;


	// Parse the input value to an integer to ensure it is in the correct format
	var intValue = parseInt(inputValue, 10);

	// Check if the parsed integer is less than 1 or NaN and correct it to 1 if necessary
	if (isNaN(intValue) || intValue < 1) {
		intValue = 1;
	}

	// Check if the parsed integer is less than 1, more than 2000, or NaN and correct accordingly
	if (isNaN(intValue) || intValue < 1) {
		intValue = 1;
	} else if (intValue > 500) {
		intValue = 500;
	}

	// Update the textbox value to the corrected intValue
	document.getElementById('number-input').value = 1;

	for (var x = 0; x < intValue; x++) {
		var winningSpin = Math.floor(Math.random() * 37);
		randomNumberCount += 1;
		numberPadSpin(winningSpin, false);
	}



}

function win(profit, winValue) {

	system_win_loss = 1;
	let winAlertContainer = document.getElementById('winAlertContainerId');

	if (winAlertContainer) {
		winAlertContainer.innerHTML = '';

		
		if (winValue > 0) {
			winAlertContainer.innerText = 'Won: ' + profit;
			simulation_win_loss = true;
		}

	}

}

function removeBet(e, n, t, o) {


	numbersBet.pop();
	const index = redo_lastThis.findIndex(element => element === e);



	wager = (wager == 0) ? 100 : wager;
	for (i = 0; i < bet.length; i++) {
		if (bet[i].numbers == n && bet[i].type == t) {
			if (bet[i].amt != 0) {
				wager = (bet[i].amt > wager) ? wager : bet[i].amt;
				bet[i].amt = bet[i].amt - wager;
				bankValue = bankValue + wager;
				session_user_amount = session_user_amount + wager;
				
				currentBet = currentBet - wager;
				document.getElementById('bankSpan').innerText = '' + bankValue.toLocaleString("en-GB") + '';
				document.getElementById('betSpan').innerText = '' + currentBet.toLocaleString("en-GB") + '';
				if (bet[i].amt == 0) {
					e.querySelector('.chip').style.cssText = 'display:none';
				} else {
					let chipColour = (bet[i].amt < 5) ? 'red' : ((bet[i].amt < 10) ? 'blue' : ((bet[i].amt < 100) ? 'orange' : 'gold'));
					e.querySelector('.chip').setAttribute('class', 'chip ' + chipColour);
					let chipSpan = e.querySelector('.chipSpan');
					chipSpan.innerText = bet[i].amt;
				}
			}
		}
	}

	if (currentBet == 0 && container.querySelector('.spinBtn')) {
		document.getElementsByClassName('spinBtn')[0].remove();
	}


	if (index !== -1) {
		redo_lastThis[index] = e;
	}
	zzzsetBet(e, bet[bet.length - 1]);
everyBetClick();
	updateStats();
}

function spinWheel(winningSpin) {


	var sound = document.getElementById('spinSound');
	if(sound)
	{
		sound.play();
	}
    const extraRotations = 5; // Number of full spins before stopping

    // Calculate start and end degrees based on the layout
    const startDegree = calculateDegreeForNumber(winningSpin);
    const winningDegree = calculateDegreeForNumber(winningSpin);



    // Calculate the exact clockwise rotation distance
    let rotationDelta = winningDegree - startDegree;
    if (rotationDelta < 0) {
        rotationDelta += 360; // Ensure positive rotation for clockwise movement
    }

    // Final target degree with extra rotations added
    const endDegree = startDegree + rotationDelta + extraRotations * 360;

    // Create a unique animation name for this spin
    const animationName = `spinWheelAnimation_${startNumber}_${winningSpin}`;
    const styleSheet = document.styleSheets[0];

    // Remove any previous keyframes with the same name
    Array.from(styleSheet.cssRules).forEach((rule, index) => {
        if (rule.name === animationName) {
            styleSheet.deleteRule(index);
        }
    });

    // Define keyframes for smooth deceleration to the winning spin
    const keyframes = `
        @keyframes ${animationName} {
            0% { transform: rotate(-${startDegree}deg); }
            70% { transform: rotate(-${endDegree - 45}deg); } /* Fast spin for the first 70% */
            90% { transform: rotate(-${endDegree - 15}deg); } /* Slow down close to end */
            100% { transform: rotate(-${endDegree}deg); } /* Stop at winningSpin */
        }
    `;
    styleSheet.insertRule(keyframes, styleSheet.cssRules.length);

    // Apply the animation to the ballTrack
    ballTrack.style.animation = `${animationName} 10s ease-out forwards`;

    // Update currentDegree for the next spin
    currentDegree = endDegree % 360;  // Keep within the 0-360 range

}

// Helper function to calculate the degree based on the number position on the wheel
function calculateDegreeForNumber(number) {
    // Explicit degree mapping for each position on a single-zero roulette wheel
	
    const numberDegrees_clockwise = {
        0: 0,
        32: 9.73,
        15: 19.46,
        19: 29.19,
        4: 38.92,
        21: 48.65,
        2: 58.38,
        25: 68.11,
        17: 77.84,
        34: 87.57,
        6: 97.3,
        27: 107.03,
        13: 116.76,
        36: 126.49,
        11: 136.22,
        30: 145.95,
        8: 155.68,
        23: 165.41,
        10: 175.14,
        5: 184.87,
        24: 194.6,
        16: 204.33,
        33: 214.06,
        1: 223.79,
        20: 233.52,
        14: 243.25,
        31: 252.98,
        9: 262.71,
        22: 272.44,
        18: 282.17,
        29: 291.9,
        7: 301.63,
        28: 311.36,
        12: 321.09,
        35: 330.82,
        3: 340.55,
        26: 350.28,
    };

	const numberDegrees = {
		0: 0,
		32: 350.27,
		15: 340.54,
		19: 330.81,
		4: 321.08,
		21: 311.35,
		2: 301.62,
		25: 291.89,
		17: 282.16,
		34: 272.43,
		6: 262.7,
		27: 252.97,
		13: 243.24,
		36: 233.51,
		11: 223.78,
		30: 214.05,
		8: 204.32,
		23: 194.59,
		10: 184.86,
		5: 175.13,
		24: 165.4,
		16: 155.67,
		33: 145.94,
		1: 136.21,
		20: 126.48,
		14: 116.75,
		31: 107.02,
		9: 97.29,
		22: 87.56,
		18: 77.83,
		29: 68.1,
		7: 58.37,
		28: 48.64,
		12: 38.91,
		35: 29.18,
		3: 19.45,
		26: 9.72
	};
    const degree = numberDegrees[number];
    if (degree === undefined) throw new Error("Invalid roulette number");

    return degree;
}



function removeChips() {
	var chips = document.getElementsByClassName('chip');
	if (chips.length > 0) {
		for (i = 0; i < chips.length; i++) {
			chips[i].remove();
		}
		removeChips();
	}
}


function changeBankroll(popup) {
	var bankrollInput = document.getElementById('bankrollInput');
	if (bankrollInput) {
		bankrollInput = bankrollInput.value;
		bankrollInput = ensureInputValue(bankrollInput, 1000);
		bankValue = bankrollInput;
		/*
		session_user_amount = 0;
				let user_session_profit = document.getElementById('session-profit-box')
		if(user_session_profit)
		{
			user_session_profit.value = session_user_amount;
		}
			*/
	}
	let bankSpan = document.getElementById('bankSpan');
	if (bankSpan) {
		bankSpan.innerHTML = bankValue;
		orginalBankValue = bankValue;
	}

	changeStartingBankroll();


}
function changeBankRollPopup(id) {
	var inputBox = document.createElement('input');
	style_textbox_container(inputBox);
	inputBox.type = 'text';
	inputBox.id = 'bankrollInput';
	inputBox.style.width = '300px';
	inputBox.style.marginTop = '20px';
	inputBox.placeholder = 'Enter bankroll amount';

	var changeButton = document.createElement('button');
	changeButton.innerText = 'Change Bankroll';
	changeButton.style.width = '300px';
	changeButton.style.height = 'auto';
	changeButton.style.fontSize = '20px';
	changeButton.style.marginTop = '20px';
	changeButton.style.marginBottom = '20px';
	changeButton.onclick = function () {
		changeBankroll(draggableDiv);
		draggableDiv.style.display = 'none';  // Hide the popup
	};

	var draggableDiv = document.createElement('div');
	draggableDiv.id = 'draggable_div_' + id;
	draggableDiv.style.display = 'none';
	draggableDiv.style.width = '340px';
	draggableDiv.style.height = '150px';
	draggableDiv.style.background = '#ebf6f7';
	draggableDiv.style.position = 'fixed'; // Use fixed position for the popup to appear at the cursor location
	draggableDiv.style.padding = '10px';
	draggableDiv.style.boxSizing = 'border-box';
	draggableDiv.style.border = '1px solid #ddd';
	draggableDiv.style.borderRadius = '5px';
	draggableDiv.style.zIndex = '1000';

	draggableDiv.appendChild(inputBox);
	draggableDiv.appendChild(document.createElement('br'));
	draggableDiv.appendChild(changeButton);

	var closeButton = document.createElement('div');
	closeButton.textContent = 'X';
	closeButton.style.cursor = 'pointer';
	closeButton.style.position = 'absolute';
	closeButton.style.top = '5px';
	closeButton.style.right = '5px';
	closeButton.style.fontWeight = 'bold';
	closeButton.onclick = function () {
		draggableDiv.style.display = 'none';
	};

	draggableDiv.appendChild(closeButton);

	document.body.appendChild(draggableDiv);

	draggableDiv.addEventListener('mousedown', function (e) {
		if (e.target !== inputBox) { // Check if the target is not the input box
			var isDragging = true;
			var offsetX = e.clientX - draggableDiv.getBoundingClientRect().left;
			var offsetY = e.clientY - draggableDiv.getBoundingClientRect().top;

			function mouseMoveHandler(e) {
				if (isDragging) {
					draggableDiv.style.left = (e.clientX - offsetX) + 'px';
					draggableDiv.style.top = (e.clientY - offsetY) + 'px';
				}
			}

			function mouseUpHandler() {
				isDragging = false;
				window.removeEventListener('mousemove', mouseMoveHandler);
				window.removeEventListener('mouseup', mouseUpHandler);
			}

			window.addEventListener('mousemove', mouseMoveHandler);
			window.addEventListener('mouseup', mouseUpHandler);
		}
	});

	return draggableDiv; // Return the draggableDiv so it can be accessed outside the function
}


function arraysAreEqual(arr1, arr2) {

	if (arr1.length !== arr2.length) {
		return false; // Different lengths mean arrays are not equal
	}
	for (let i = 0; i < arr1.length; i++) {
		if (arr1[i] !== arr2[i]) {
			return false; // Return false if any element differs
		}
	}
	return true; // All elements are equal
}

function checkIfEqualToDozen(numberArray) {
	for (let i = 0; i < rouletteAttributes.dozens.length; i++) {
		if (arraysAreEqual(numberArray, rouletteAttributes.dozens[i])) {
			return true;
		}
	}
	return false;
}

function checkIfEqualToRows(numberArray) {

	for (let i = 0; i < rouletteAttributes.columns.length; i++) {
		if (arraysAreEqual(numberArray, rouletteAttributes.columns[i])) {
			return true;
		}
	}
	return false;
}