let currentHeight = 185;
function load_api() {

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


	casinoNumbersButton_panel.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";
	casinoNumbersButton_panel.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";
	casinoNumbersButton_panel.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
			casinoNumbersButton_panel.style.height = `${selectATableHeight}px`; // Apply height
			refreshButton.style.display = 'none'; // Hide the refresh button
			return; // Exit the function early
		}
	
		const apiUrl = apis.find(api => api.name === selectedKey).file;
try {
  const response = await fetch(apiUrl);
  if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
  const data = await response.json();
console.log("DATA ",data);
  const selectedTable = selectedKey;
const sortedData = data
  .filter(entry => entry.data?.settledAt && typeof entry.data?.result?.outcome?.number === 'number')
  .sort((a, b) => new Date(b.data.settledAt) - new Date(a.data.settledAt)); // newest first

const numbers = sortedData.map(entry => entry.data.result.outcome.number);
console.log("Final numbers shown:", numbers.length);
  casinoNumbersButton_panel.style.height = `${currentHeight}px`;
  casinoNumbersButton_panel.style.overflowY = "auto";
  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';
} 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);


	refreshButton.addEventListener('click', async () => {
	const selectedKey = dropdownapi.value;
	if (!selectedKey) return;

	const apiUrl = apis.find(api => api.name === selectedKey).file;

	try {
		const response = await fetch(apiUrl);
		if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
		const data = await response.json();
		console.log("DATA ",data);
const sortedData = data
  .filter(entry => entry.data?.settledAt && typeof entry.data?.result?.outcome?.number === 'number')
  .sort((a, b) => new Date(b.data.settledAt) - new Date(a.data.settledAt)); // newest first

const numbers = sortedData.map(entry => entry.data.result.outcome.number);
		casinoNumbersButton_panel.style.height = `${currentHeight}px`;
		casinoNumbersButton_panel.style.overflowY = "auto";
		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();
	} catch (error) {
		resultsDiv.innerHTML = `<span class="error-api">Error fetching data: ${error.message}</span>`;
	}
});

	// 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(casinoNumbersButton_panel, counterValue, selectAnyItemHeight, heightIncrement);
	casinoNumbersButton_panel.prepend(controlContainer);
	casinoNumbersButton_panel.appendChild(resultsContainer);

	// Adjust wrapping for contents
casinoNumbersButton_panel.style.whiteSpace = 'normal'; // Allow wrapping to the next line
casinoNumbersButton_panel.style.overflowY = 'hidden'; // Hide vertical scrollbar
casinoNumbersButton_panel.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');
			});
		}
	});

apis.forEach((api) => {
	const option = document.createElement('option');
	option.value = api.name;
	option.textContent = api.name;
	dropdownapi.appendChild(option);
});

	  
}

function api_control_container(casinoNumbersButton_panel, counterValue, defaultHeight, heightIncrement) {
	const controlContainer = document.createElement('div');
	controlContainer.style.display = 'flex';
	controlContainer.style.alignItems = 'center';
	controlContainer.style.marginBottom = '10px';
	controlContainer.style.marginLeft = '25px';
  
	// Create "Reset" button
	const resetButton = document.createElement('button');
	resetButton.textContent = 'Reset';
	resetButton.style.marginRight = '10px';
	resetButton.addEventListener('click', () => {
	  counterValue.value = 1; // Use object reference to modify the counterValue
	  updateCounter();
	  casinoNumbersButton_panel.style.height = `${defaultHeight}px`;
	});
  
	// Create "-" button
	const minusButton = document.createElement('button');
	minusButton.textContent = '-';
	minusButton.style.marginRight = '5px';
	minusButton.addEventListener('click', () => {
		if (counterValue.value > 1) {
			counterValue.value--;
			updateCounter();
			currentHeight = defaultHeight + (counterValue.value - 1) * heightIncrement; // Update current height
			casinoNumbersButton_panel.style.height = `${currentHeight}px`;

		}
	});
	// 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.addEventListener('click', () => {
		counterValue.value++;
		updateCounter();
		currentHeight = defaultHeight + (counterValue.value - 1) * heightIncrement; // Update current height

		casinoNumbersButton_panel.style.height = `${currentHeight}px`;
	});
	// Create "Max" button
	const maxButton = document.createElement('button');
	maxButton.textContent = 'Max';
	maxButton.style.marginLeft = '10px';
	maxButton.addEventListener('click', () => {
	  casinoNumbersButton_panel.style.height = 'auto';
	  casinoNumbersButton_panel.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';
	});
}