let api_currentHeight = 197;
function load_api() {

	const counterValue = { value: 1 }; // Use an object to allow updates within the function
	const defaultHeight = 142; // Default height of the container
	const heightIncrement = 55; // Height increment per counter value
	const selectATableHeight = 142;
	const selectAnyItemHeight = 142;
	


	apiContainer.style.height = `${defaultHeight}px`; // Set initial height

	
	
	
	// Create the label
	const label = document.createElement('label');
	label.setAttribute('for', 'roulette-select-api');
	label.textContent = 'Select a Roulette Table:';
	label.classList.add('label-api');
	label.style.marginLeft = "25px";
	label.style.marginBottom = "2px";
	apiContainer.appendChild(label);

	// Create the dropdown
	const dropdownapi = document.createElement('select');
	dropdownapi.id = 'roulette-select-api';
	dropdownapi.innerHTML = '<option value="" selected>Choose a table</option>';
	dropdownapi.classList.add('dropdown-api');
	dropdownapi.style.marginBottom = "2px";
	apiContainer.appendChild(dropdownapi);

	


	dropdownapi.addEventListener('change', async (event) => {
		const selectedKey = event.target.value; // Get the selected API key
	
		if (!selectedKey) {
			// "Choose a table" was selected
			resultsDiv.innerHTML = ''; // Clear the numbers
			counterValue.value = 1; // Reset the counter to default
			apiContainer.style.height = `${selectATableHeight}px`; // Apply height
			refreshButton.style.display = 'none'; // Hide the refresh button
			return; // Exit the function early
		}
	
		// Handle other cases when a valid table is selected
		const apiUrl = apis[selectedKey];
		try {
			const response = await fetch(apiUrl);
			if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
			const data = await response.json();
	
			const numbers = data.recentNumbers.reverse(); // Assuming 'recentNumbers' is the API response format
			// Retain api_currentHeight instead of resetting
	
			apiContainer.style.height = `${api_currentHeight}px`;
			apiContainer.style.overflowY = "auto"; // Ensure vertical scrolling
			resultsDiv.innerHTML = numbers
				.map((number) => `
					<span 
						class="roulette-number-api ${getColorClass(number)}" 
						data-number="${number}">
						${number}
					</span>
				`)
				.join(' ');
			resultsDiv.innerHTML += `<span class="green-arrow">Oldest &nbsp;&nbsp;</span>`;
			change_ball_size();
			refreshButton.style.display = 'inline-block'; // Show refresh button
		} catch (error) {
			resultsDiv.innerHTML = `<span class="error-api">Error fetching data: ${error.message}</span>`;
		}
	});
	

	
	
	// Function to determine the color class based on the number
	function getColorClass(number) {
		const redNumbers = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36];
		const blackNumbers = [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35];
		if (number === 0) return 'green-api';
		if (redNumbers.includes(number)) return 'red-api';
		if (blackNumbers.includes(number)) return 'black-api';
		return '';
	}

	function getColorClassHover(number) {
		const redNumbers = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36];
		const blackNumbers = [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35];
	
		const num = parseInt(number, 10); // Convert to integer
		if (num === 0) return 'green-api-highlight';
		if (redNumbers.includes(num)) return 'red-api-highlight';
		if (blackNumbers.includes(num)) return 'black-api-highlight';
		return '';
	}

	// Create the results container
	const resultsContainer = document.createElement('div');
	resultsContainer.id = 'results-container-api';
	resultsContainer.classList.add('results-container-api');


	// Create the refresh button
	const refreshButton = document.createElement('button');
	refreshButton.id = 'refresh-button-api';
	refreshButton.textContent = 'Refresh';
	refreshButton.style.display = 'none'; // Initially hidden
	refreshButton.classList.add('refresh-button-api');
	resultsContainer.appendChild(refreshButton);

	// Create the results display div
	const resultsDiv = document.createElement('div');
	resultsDiv.id = 'roulette-results-api';
	resultsDiv.style.marginTop = '20px';
	resultsDiv.classList.add('roulette-results-api');
	resultsContainer.appendChild(resultsDiv);




  
	// Append control container
	const controlContainer = api_control_container(apiContainer, counterValue, selectAnyItemHeight, heightIncrement);
	apiContainer.prepend(controlContainer);
	apiContainer.appendChild(resultsContainer);

	// Adjust wrapping for contents
apiContainer.style.whiteSpace = 'normal'; // Allow wrapping to the next line
apiContainer.style.overflowY = 'hidden'; // Hide vertical scrollbar
apiContainer.style.overflowX = 'hidden'; // Hide horizontal scrollbar

	document.addEventListener('mouseover', (event) => {
		if (event.target.classList.contains('roulette-number-api')) {
			const hoveredNumber = event.target.getAttribute('data-number'); // Get the hovered number
			const allNumbers = document.querySelectorAll('.roulette-number-api'); // Select all number elements
	
			allNumbers.forEach((element) => {
				if (element.getAttribute('data-number') === hoveredNumber) {
					const highlightStyle = getColorClassHover(hoveredNumber);
					if (highlightStyle) {
						element.classList.add(highlightStyle); // Add highlight class if valid
					}
				}
			});
		}
	});
	
	document.addEventListener('mouseout', (event) => {
		if (event.target.classList.contains('roulette-number-api')) {
			const allNumbers = document.querySelectorAll('.roulette-number-api');
	
			allNumbers.forEach((element) => {
				element.classList.remove('green-api-highlight'); // Remove highlight class from all numbers
				element.classList.remove('red-api-highlight');
				element.classList.remove('black-api-highlight');
			});
		}
	});

    Object.keys(apis).forEach((key) => {
		const option = document.createElement('option');
		option.value = key;
		option.textContent = key;
		dropdownapi.appendChild(option);
	  });

	  
}

function api_control_container(apiContainer, counterValue, defaultHeight, heightIncrement) {
	const controlContainer = document.createElement('div');
	controlContainer.style.display = 'flex';
	controlContainer.style.alignItems = 'center';
	controlContainer.style.marginBottom = '10px';
	controlContainer.style.marginLeft = '25px';
  
	const apiNumbersButton = document.createElement('button');
	apiNumbersButton.innerText = 'Live';
	
	apiNumbersButton.classList.add('api-button-bet-list');
	apiNumbersButton.classList.add('api-button');
	apiNumbersButton.setAttribute('id', 'api-numbers-button');
	api_button_on_click_event(apiNumbersButton);
	controlContainer.appendChild(apiNumbersButton);

	// Create "Reset" button
	const resetButton = document.createElement('button');
	resetButton.textContent = 'Reset';
	resetButton.style.marginRight = '10px';
	resetButton.classList.add('api-button');
	resetButton.addEventListener('click', () => {
	  counterValue.value = 1; // Use object reference to modify the counterValue
	  updateCounter();
	  apiContainer.style.height = `${defaultHeight+heightIncrement}px`;
	});
  
	// Create "-" button
	const minusButton = document.createElement('button');
	minusButton.textContent = '-';
	minusButton.style.marginRight = '5px';
	minusButton.classList.add('api-button');
	minusButton.addEventListener('click', () => {
		if (counterValue.value > 1) {
			counterValue.value--;
			updateCounter();
			//console.log("MdefaultHeight: ", defaultHeight);
			//console.log("MheightIncrement: ", heightIncrement);
			//console.log("Mapi_currentHeight: ", api_currentHeight);
			api_currentHeight = defaultHeight + (counterValue.value - 1) * heightIncrement; // Update current height
			if (api_currentHeight<(defaultHeight+heightIncrement)) api_currentHeight = defaultHeight+heightIncrement;
			apiContainer.style.height = `${api_currentHeight}px`;
			//console.log("M--api_currentHeight: ", api_currentHeight);

		}
	});
	// Create counter display
	const counterDisplay = document.createElement('span');
	counterDisplay.textContent = counterValue.value;
	counterDisplay.style.margin = '0 10px';
	counterDisplay.style.fontWeight = 'bold';
  
	// Create "+" button
	const plusButton = document.createElement('button');
	plusButton.textContent = '+';
	plusButton.style.marginLeft = '5px';
	plusButton.classList.add('api-button');
	plusButton.addEventListener('click', () => {
		counterValue.value++;
		updateCounter();
		//console.log("defaultHeight: ", defaultHeight);
		//console.log("heightIncrement: ", heightIncrement);
		//console.log("api_currentHeight: ", api_currentHeight);
		api_currentHeight = defaultHeight + (counterValue.value) * heightIncrement; // Update current height
		//console.log("--api_currentHeight: ", api_currentHeight);

		apiContainer.style.height = `${api_currentHeight}px`;
	});
	// Create "Max" button
	const maxButton = document.createElement('button');
	maxButton.textContent = 'Max';
	maxButton.style.marginLeft = '10px';
	maxButton.classList.add('api-button');
	maxButton.addEventListener('click', () => {
	  apiContainer.style.height = 'auto';
	  apiContainer.style.overflowY = 'visible'; // Show all contents
	});
  
	// Function to update counter display
	function updateCounter() {
	  counterDisplay.textContent = counterValue.value;
	}
  
	// Append buttons to the control container
	controlContainer.appendChild(resetButton);
	controlContainer.appendChild(minusButton);
	controlContainer.appendChild(counterDisplay);
	controlContainer.appendChild(plusButton);
	controlContainer.appendChild(maxButton);
  
	return controlContainer;
  }

function change_ball_size()
{
	const numberElements = document.querySelectorAll('.roulette-number-api');
	numberElements.forEach((element) => {
		element.style.width = '39px';
		element.style.height = '30px';
		element.style.padding = '5px';
		element.style.fontSize = '12px';
		element.style.lineHeight = '30px';
	});
}