let button_autoButton = null;
let isToggledOn_autoButton = false;
let countdownInterval_autoButton = null;
let countdownTime_autoButton = 15;
let turn_off_overlay_orange_button = 3000;

function startGame() {

	AutoBet.init();
	// Get spins from live casino


	// Document items
	let document_cursor_message_box = createCursorMessageElement();
	document.body.appendChild(document_cursor_message_box);

	// Button Bar
	addButtonsToButtonBar();

	if(showAPI == true)
	{
		load_api();

	}
	
	
	// Roulette Table Container
	let roulette_history_board = buildNumberHistory();
	let roulette_wheel = buildWheel();
	let roulette_betting_board = buildBettingBoard();
	let roulette_number_pad = numberPad();
	let roulette_message = numberPadMessage();
	let roulette_win_alert = winAlert();
	let container = document.createElement('div');
	let alertwindow = wheelAlertWindow();
	let triggerAlertWindowButton = toggleButtonTriggerWindow();
    button_autoButton = toggleAutoPlayButton();

	container.setAttribute('id', 'container');
	storedColor = localStorage.getItem("userColor");
	if (storedColor) {

        container.style.backgroundColor = storedColor;

    }
	const apiNumbersButton = document.createElement('button');
	const AINumbersButton = document.createElement('button');
	if(showAPI == true)
		{
		// API
		apiNumbersButton.innerText = 'Live';
		apiNumbersButton.classList.add('api-button-bet-list');
		apiNumbersButton.setAttribute('id', 'api-numbers-button');
		api_button_on_click_event(apiNumbersButton);

				// API
		AINumbersButton.innerText = 'AI';
		AINumbersButton.classList.add('ai-api-button-bet-list');
		AINumbersButton.setAttribute('id', 'ai-api-numbers-button');
		ai_button_click_event(AINumbersButton);
		
		

		}


	container.appendChild(roulette_history_board);
	container.appendChild(roulette_wheel);
	container.appendChild(roulette_betting_board);
	container.appendChild(roulette_number_pad);
	container.appendChild(roulette_message);
	container.appendChild(roulette_win_alert);
	container.appendChild(alertwindow);
	container.appendChild(triggerAlertWindowButton);
	container.appendChild(button_autoButton);
	if(showAPI == true)
		{
			container.appendChild(apiNumbersButton);
			container.appendChild(AINumbersButton);
		}
	
	rouletteBoard.appendChild(container);

	wheel = document.getElementsByClassName('wheel')[0];
	ballTrack = document.getElementsByClassName('ballTrack')[0];

	// Bottom Container 1
	let bottomContainer1_trigger_options = triggerOptions();

	bottomContainer1.appendChild(bottomContainer1_trigger_options);

	// Bottom Container 2
	let bottomContainer2_tabs_navigation = createTabbedNavigation();

	bottomContainer2.appendChild(bottomContainer2_tabs_navigation);
	populateTabs();

	// Bottom Container 3
	let toggleDragButton = createToggleButton('dragg');
	dragButtonContainer.appendChild(toggleDragButton);
	
	videoPopup();

	//appendFooter();

	misses(); // set session variable
	getMissesHighScores(); // set Record variable

	updateBorderVisibility();


	loadCacheFromLocalStorage();

	let cachSpinButton = document.getElementById('cach-bet-spin-button');
	cachSpinButton.onclick = quickSpin;

		// Initialize the draggable div's position on page load
		//loadPosition_edge3alert();
	//hoverOverSessionProfit();

	loadHistoryFromStorage();

	casinoNumbersButton.addEventListener('click', () => {
		
		changeCasino();
		toggleVisibility(casinoNumbersButton_panel);
	});

	session_user_amount_popup = session_user_amount;
	numbersUp_Update();
	const neigh = neighborBuild();
	//document.body.appendChild(neigh);

}





function changeCasino()
{
	load_api(casinoNumbersButton_panel);

}

function playSpinSound() {
    var sound = document.getElementById('spinSound');
    sound.play();
}

function everyBetClick(){
	show_bets();

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////   AUTO PLAY BUTTON
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



let spinIndex = 0;
let casinoSpins = [];

let lastSpinNumber = null;
let isWaitingForNewSpin = false;
let lastSpinSettledAt = null; // track latest timestamp

async function spinLatestNumber() {
	if (useRandomNumber) {
		const randomNumber = Math.floor(Math.random() * 37);
		numberPadSpin(randomNumber);
		return;
	}

	try {
		const response = await fetch(selectedCasinoSource);
		const data = await response.json();
		const latestResult = data?.[0];

		if (latestResult) {
			const { number } = latestResult.data.result.outcome;
			const settledAt = latestResult.data.settledAt;

			if (!isNaN(number) && number >= 0 && number <= 36) {
				// Get or create the set for this casino
const normalizedKey = selectedCasinoSource.replace(/spin_/, 'spin_50_');

if (!seenTimestampsByCasino.has(normalizedKey)) {
  seenTimestampsByCasino.set(normalizedKey, new Set());
}
const seenSet = seenTimestampsByCasino.get(normalizedKey);

				if (!seenSet.has(settledAt)) {
					seenSet.add(settledAt);
					console.log("✅ New spin:", number, "from", selectedCasinoSource);
					numberPadSpin(number);
				} else {
					console.log("⏳ No new spin yet for", selectedCasinoSource);
				}
			} else {
				console.warn("Invalid number from API:", number);
			}
		}
	} catch (error) {
		console.error("Failed to fetch spin:", error);
	}
}

function toggleAutoPlayButton(useSharedButton = true) {
	const button = document.createElement('button');
	button.id = `countdownBtn`;
	button.textContent = `Auto Spin`;

	button.addEventListener('click', () => {
		if (!isToggledOn_autoButton) {
			createCasinoSelectionPopup(() => {
				isToggledOn_autoButton = true;
				button.classList.remove('running');
				waitForNewSpinAndStartCountdown();
			});
		} else {
			isToggledOn_autoButton = false;
			clearInterval(countdownInterval_autoButton);
			button.textContent = 'Auto Spin';
			button.classList.remove('running');
		}
	});

	if (useSharedButton) {
		button_autoButton = button;
	}

	return button;
}








function startCountdown_random() {
	let timeLeft = AUTO_SPIN_DELAY_RANDOM;
	button_autoButton.textContent = `${timeLeft}s`;

	countdownInterval_autoButton = setInterval(() => {
		timeLeft--;
		button_autoButton.textContent = `${timeLeft}s`;

		if (timeLeft <= 0) {
			clearInterval(countdownInterval_autoButton);
			button_autoButton.classList.add('running');

			spin(); // this starts the spin animation and triggers timer_turn_off_overlay()

			// Wait for spin to fully finish before deciding what to do next
			setTimeout(() => {
				button_autoButton.classList.remove('running');

				if (isToggledOn_autoButton) {
					startCountdown_random(); // start a new countdown cycle
				} else {
					button_autoButton.textContent = 'Start';
				}
			}, turn_off_overlay); // Wait for overlay delay before starting next round
		}
	}, 1000);
}
async function startCountdown() {
	let timeLeft = AUTO_SPIN_DELAY_CASINO;
	button_autoButton.textContent = `${timeLeft}s`;

	countdownInterval_autoButton = setInterval(() => {
		timeLeft--;
		button_autoButton.textContent = `${timeLeft}s`;

		if (timeLeft <= 0) {
			clearInterval(countdownInterval_autoButton);
			button_autoButton.classList.add('running');

			setTimeout(async () => {
				button_autoButton.classList.remove('running');

				if (savedSpinNumber !== null) {
	if (useRandomNumber) {
		turn_off_overlay = 3000;
		await spin(); // local spin with random number
	} else {
		await numberPadSpinAsync(savedSpinNumber); // API spin
	}
	savedSpinNumber = null;
}

				if (isToggledOn_autoButton) {
					waitForNewSpinAndStartCountdown();
				} else {
					button_autoButton.textContent = 'Start';
				}
			}, turn_off_overlay_orange_button);
		}
	}, 1000);
}

function numberPadSpinAsync(n) {
	return new Promise(resolve => {
		numberPadSpin(n);
		setTimeout(resolve, turn_off_overlay); // wait for overlay to finish
	});
}

let savedSpinNumber = null;

async function waitForNewSpinAndStartCountdown() {
	isWaitingForNewSpin = true;

	if (button_autoButton) {
		button_autoButton.textContent = 'Place Bets';

	}

	if (useRandomNumber) {
		const randomNumber = Math.floor(Math.random() * 37);
		savedSpinNumber = randomNumber;
		isWaitingForNewSpin = false;
		turn_off_overlay_orange_button = 10000;
		startCountdown_random();
		return;
	}

	while (isWaitingForNewSpin) {
		try {
			const response = await fetch(selectedCasinoSource);
			const data = await response.json();
			console.log("Parsed API Data:", data);

			if (Array.isArray(data) && data.length > 0) {
				const latestResult = data[0];
				const { number } = latestResult.data.result.outcome;
				const settledAt = latestResult.data.settledAt;

				if (!isNaN(number) && number >= 0 && number <= 36) {
					// Get or initialize Set for this casino
const normalizedKey = selectedCasinoSource.replace(/spin_/, 'spin_50_');

if (!seenTimestampsByCasino.has(normalizedKey)) {
  seenTimestampsByCasino.set(normalizedKey, new Set());
}
const seenSet = seenTimestampsByCasino.get(normalizedKey);

					if (!seenSet.has(settledAt)) {
						seenSet.add(settledAt);
						savedSpinNumber = number;
						console.log("✅ Detected new spin:", number);
						isWaitingForNewSpin = false;
						turn_off_overlay = 3000;
						startCountdown();
						return;
					}
				}
			} else {
				console.warn("⚠️ API returned no usable spin data.");
			}
		} catch (error) {
			console.error("Error checking for new spin:", error);
		}

		await new Promise(resolve => setTimeout(resolve, 1000));
	}
}




let selectedCasinoSource = 'spin_casino_1.php'; // default
let useRandomNumber = false;

function createCasinoSelectionPopup(callback) {
	const popup = document.createElement('div');
	popup.id = 'casino-popup';
	popup.style.position = 'fixed';
	popup.style.top = '50%';
	popup.style.left = '50%';
	popup.style.transform = 'translate(-50%, -50%)';
	popup.style.background = 'white';
	popup.style.padding = '20px';
	popup.style.border = '2px solid black';
	popup.style.zIndex = '9999';

	const title = document.createElement('h3');
	title.textContent = 'Select Casino or Random';
	popup.appendChild(title);

	const list = [
		{ name: 'Xxxtreme Lightning Roulette', file: 'spin_xxxtreme_roulette.php' },
		{ name: 'Lightning Roulette', file: 'spin_lightening_roulette.php' },
		{ name: 'Auto Roulette', file: 'spin_auto_roulette.php' },
		{ name: 'Immersive Roulette', file: 'spin_immersive_roulette.php' },
		// Add more options here if needed
		{ name: 'Use Random Number', file: null }
	];

	list.forEach(item => {
		const btn = document.createElement('button');
		btn.textContent = item.name;
		btn.style.display = 'block';
		btn.style.margin = '10px 0';

		btn.addEventListener('click', () => {
			if (item.file) {
				selectedCasinoSource = item.file;
				useRandomNumber = false;
			} else {
				useRandomNumber = true;
			}
			document.body.removeChild(popup);

			if (typeof callback === 'function') {
				callback(); // Start countdown after selection
			}
		});

		popup.appendChild(btn);
	});

	const link = document.createElement('a');
	link.href = 'spins.php';
	link.target = '_blank';
	link.textContent = 'View Raw Spins';
	link.style.display = 'block';
	link.style.marginTop = '20px';
	link.style.fontSize = '14px';
	link.style.color = '#007bff';
	link.style.textDecoration = 'underline';

	popup.appendChild(link);



	// --- Delay Configuration Inputs ---
const delayLabel = document.createElement('h4');
delayLabel.textContent = 'Configure Auto Spin Delay (in seconds)';
delayLabel.style.marginTop = '20px';
popup.appendChild(delayLabel);

// Random delay input
const randomDelayWrapper = document.createElement('div');
randomDelayWrapper.style.marginBottom = '10px';
const randomDelayLabel = document.createElement('label');
randomDelayLabel.textContent = 'Random Number Delay: ';
const randomDelayInput = document.createElement('input');
randomDelayInput.type = 'number';
randomDelayInput.min = 1;
randomDelayInput.max = 60;
randomDelayInput.value = AUTO_SPIN_DELAY_RANDOM;
randomDelayInput.style.marginLeft = '5px';

randomDelayInput.addEventListener('change', () => {
	AUTO_SPIN_DELAY_RANDOM = parseInt(randomDelayInput.value) || 10;
	localStorage.setItem('AUTO_SPIN_DELAY_RANDOM', AUTO_SPIN_DELAY_RANDOM);
});
randomDelayWrapper.appendChild(randomDelayLabel);
randomDelayWrapper.appendChild(randomDelayInput);
popup.appendChild(randomDelayWrapper);

// Casino delay input
const casinoDelayWrapper = document.createElement('div');
casinoDelayWrapper.style.marginBottom = '10px';
const casinoDelayLabel = document.createElement('label');
casinoDelayLabel.textContent = 'Casino Delay: ';
const casinoDelayInput = document.createElement('input');
casinoDelayInput.type = 'number';
casinoDelayInput.min = 1;
casinoDelayInput.max = 60;
casinoDelayInput.value = AUTO_SPIN_DELAY_CASINO;
casinoDelayInput.style.marginLeft = '5px';

casinoDelayInput.addEventListener('change', () => {
	AUTO_SPIN_DELAY_CASINO = parseInt(casinoDelayInput.value) || 15;
	localStorage.setItem('AUTO_SPIN_DELAY_CASINO', AUTO_SPIN_DELAY_CASINO);
});
casinoDelayWrapper.appendChild(casinoDelayLabel);
casinoDelayWrapper.appendChild(casinoDelayInput);
popup.appendChild(casinoDelayWrapper);

const closeButton = document.createElement('button');
closeButton.textContent = 'Close';
closeButton.style.marginTop = '20px';
closeButton.style.display = 'block';
closeButton.style.width = '100%';
closeButton.style.padding = '10px';
closeButton.style.backgroundColor = '#ccc';
closeButton.style.border = '1px solid #999';
closeButton.style.cursor = 'pointer';

closeButton.addEventListener('click', () => {
	document.body.removeChild(popup);
});

popup.appendChild(closeButton);

	document.body.appendChild(popup);
}


function hoverOverSessionProfit()
{
	// Dummy array for testing (replace with your actual data)
let session_user_amount_array = [0, 5, 10, 6, 14, 8];

// Create the button
const profitChartButton = document.createElement('button');
profitChartButton.textContent = "Show Profit Chart";
profitChartButton.style.marginLeft = '10px';
sessionProfitContainer.appendChild(profitChartButton);

// Create the popup container (but DO NOT add <canvas> yet)
const chartPopup = document.createElement('div');
chartPopup.id = 'chart-popup';
chartPopup.style.position = 'absolute';
chartPopup.style.display = 'none';
chartPopup.style.backgroundColor = '#fff';
chartPopup.style.border = '1px solid #ccc';
chartPopup.style.padding = '10px';
chartPopup.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)';
chartPopup.style.zIndex = 1000;
document.body.appendChild(chartPopup);

// Toggle state
let chartVisible = false;

// Click to toggle chart
profitChartButton.addEventListener('click', () => {
    if (chartVisible) {
        chartPopup.style.display = 'none';
        chartPopup.innerHTML = ''; // Clear canvas content
        chartVisible = false;
        return;
    }

    // Position chart popup above the button
    const rect = profitChartButton.getBoundingClientRect();
    chartPopup.style.left = `${rect.left + window.scrollX}px`;
    chartPopup.style.top = `${rect.top + window.scrollY - 170}px`;
    chartPopup.style.display = 'block';
    chartVisible = true;

    // Inject fresh canvas into popup
    chartPopup.innerHTML = '<canvas id="sessionChart" width="300" height="150"></canvas>';
    const ctx = document.getElementById('sessionChart').getContext('2d');

    // Destroy previous chart if exists
    if (window.sessionChart) {
        window.sessionChart.destroy();
    }

    // Only draw chart if there is data
    if (session_user_amount_array.length > 0) {
        window.sessionChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: session_user_amount_array.map((_, i) => i + 1),
                datasets: [{
                    label: 'Session Profit',
                    data: session_user_amount_array,
                    borderColor: 'green',
                    backgroundColor: 'rgba(0, 128, 0, 0.1)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.2
                }]
            },
            options: {
                responsive: false,
                animation: false,
                plugins: {
                    legend: { display: false }
                },
                scales: {
                    x: { display: false },
                    y: { display: true }
                }
            }
        });
    } else {
        chartPopup.innerHTML = '<p>No data to show</p>';
    }
});

// Optional: clicking the chart also closes it
chartPopup.addEventListener('click', () => {
    chartPopup.style.display = 'none';
    chartPopup.innerHTML = '';
    chartVisible = false;
});

}

