// Create the popup container


  // Function to fetch data for all APIs
  const fetchAllRouletteData = async () => {
    const results = {};
  
    for (const [key, url] of Object.entries(apis)) {
      try {
        const response = await fetch(url);
        if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
        const data = await response.json();
        results[key] = data.recentNumbers.join(', ');
      } catch (error) {
        results[key] = `Error: ${error.message}`;
      }
    }
  
    return results;
  };

const createPopupAPI = () => {
    // Check if popup exists
    let popup = document.getElementById('popup-container');
    if (!popup) {
      popup = document.createElement('div');
      popup.id = 'popup-container';
      popup.style.position = 'fixed';
      popup.style.top = '50%';
      popup.style.left = '50%';
      popup.style.transform = 'translate(-50%, -50%)';
      popup.style.background = '#fff';
      popup.style.border = '1px solid #ccc';
      popup.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.2)';
      popup.style.padding = '20px';
      popup.style.zIndex = '1000';
      popup.style.display = 'none';
  
      const closeButton = document.createElement('button');
      closeButton.textContent = 'Close';
      closeButton.style.marginBottom = '10px';
      closeButton.addEventListener('click', () => {
        popup.style.display = 'none';
      });
      popup.appendChild(closeButton);
  
      const content = document.createElement('div');
      content.id = 'popup-content';
      popup.appendChild(content);
  
      document.body.appendChild(popup);
    }
    return popup;
  };
  
  const showPopupAPI = (data) => {
    const popup = createPopupAPI();
    const content = document.getElementById('popup-content');
    content.innerHTML = ''; // Clear previous content
    content.innerHTML = data;
    popup.style.display = 'block';
  };
  
  // Generate the content dynamically
  const createDynamicPopupAPI = () => {
    const contentContainer = document.createElement('div');
    const apiSections = document.querySelectorAll('.api-section');

    apiSections.forEach((section, index) => {
        const title = section.querySelector('h2').textContent;
        const data = section.querySelector('.roulette-data').innerHTML;

        const sectionDiv = document.createElement('div');
        sectionDiv.innerHTML = `
            <h2>${title} <button class="add-button" data-index="${index}">Add</button></h2>
            <div>${data}</div>
        `;
        contentContainer.appendChild(sectionDiv);
    });

    // Attach event listeners to "Add" buttons
    contentContainer.querySelectorAll('.add-button').forEach((btn) => {
        btn.addEventListener('click', (e) => {
            const index = e.target.dataset.index;
            console.log(`Add button clicked for section ${index}`);
        });
    });

    return contentContainer;
};

function applyAPI(key) {

    
	var textarea = document.getElementById(`textbox-${key}`);

	var value = textarea.value;

	value = processBulkNumbers_api(value);

	value.forEach(n => {
        pushHistory(n);
	});
}

function makeDraggableAPI(element) {
   
  let isDragging = false;
  let offsetX, offsetY;

  const onMouseDown = (event) => {
      // Prevent dragging when clicking inside a text box or input
      if (event.target.tagName === 'TEXTAREA' || event.target.tagName === 'INPUT') return;

      isDragging = true;
      offsetX = event.clientX - element.getBoundingClientRect().left;
      offsetY = event.clientY - element.getBoundingClientRect().top;
      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
  };

  const onMouseMove = (event) => {
      if (!isDragging) return;
      element.style.left = `${event.clientX - offsetX}px`;
      element.style.top = `${event.clientY - offsetY}px`;
  };

  const onMouseUp = () => {
      isDragging = false;
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
  };

  element.addEventListener('mousedown', onMouseDown);
}


// Function to create the popup
function api_button_on_click_event_OLD(displayDivButton) {
  displayDivButton.addEventListener('click', async () => {
      // Check if the panel already exists
      if (document.getElementById('bulkPanelContainer')) return;

      // Fetch data dynamically
      const data = await fetchAllRouletteData();

      // Create the popup container
      const panelContainer = document.createElement('div');
      panelContainer.id = 'bulkPanelContainer';
      panelContainer.style.position = 'fixed';
      panelContainer.style.top = '10%';
      panelContainer.style.left = '10%';
      panelContainer.style.width = '630px';
      panelContainer.style.height = '500px';
      panelContainer.style.backgroundColor = '#f2fcff';
      panelContainer.style.border = '1px solid #ccc';
      panelContainer.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.2)';
      panelContainer.style.overflow = 'auto';
      panelContainer.style.padding = '20px';
      panelContainer.style.zIndex = '1000';

      // Populate the popup with data
      const content = document.createElement('div');
      content.innerHTML = `<h1>Live Roulette Results</h1>`;
      
      for (const [key, numbers] of Object.entries(data)) {
          const section = document.createElement('div');
          section.style.marginBottom = '20px';

          // Title
          const title = document.createElement('h2');
          title.textContent = key.replace(/-/g, ' ');

          // Textbox for data
          const textbox = document.createElement('textarea');
          textbox.value = numbers;
          textbox.id = `textbox-${key}`;
          textbox.style.width = '100%';
          textbox.style.height = '80px';
          textbox.style.marginTop = '10px';

          // Button to log data
          const logButton = document.createElement('button');
          logButton.textContent = 'Add Numbers to Tool';
          logButton.style.marginTop = '10px';
          logButton.addEventListener('click', () => {
      applyAPI(key);
          });

          // Append elements to section
          section.appendChild(title);
          section.appendChild(textbox);
          section.appendChild(logButton);

          // Append section to content
          content.appendChild(section);
      }

      panelContainer.appendChild(content);

      // Create a close button
      const closeButton = document.createElement('button');
      closeButton.innerText = 'Close';
      closeButton.style.position = 'absolute';
      closeButton.style.top = '10px';
      closeButton.style.right = '10px';
      closeButton.style.padding = '5px 10px';
      closeButton.style.backgroundColor = '#f44336';
      closeButton.style.color = '#fff';
      closeButton.style.border = 'none';
      closeButton.style.cursor = 'pointer';
      closeButton.style.borderRadius = '3px';

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

      // Append close button to the popup
      panelContainer.appendChild(closeButton);

      // Append popup to the body
      document.body.appendChild(panelContainer);
  makeDraggableAPI(panelContainer);
  });
}


function api_button_on_click_event_old2(displayDivButton) {
  displayDivButton.addEventListener('click', async () => {
      if (document.getElementById('bulkPanelContainer')) return;

      const data = await fetchAllRouletteData();

      const panelContainer = document.createElement('div');
      panelContainer.id = 'bulkPanelContainer';
      panelContainer.style.position = 'fixed';
      panelContainer.style.top = '10%';
      panelContainer.style.left = '10%';
      panelContainer.style.width = '630px';
      panelContainer.style.height = '500px';
      panelContainer.style.backgroundColor = '#f2fcff';
      panelContainer.style.border = '1px solid #ccc';
      panelContainer.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.2)';
      panelContainer.style.overflow = 'auto';
      panelContainer.style.padding = '20px';
      panelContainer.style.zIndex = '1000';

      const content = document.createElement('div');
      content.innerHTML = `<h1>Live Roulette Results</h1>`;

      for (const [key, numbers] of Object.entries(data)) {
          const section = document.createElement('div');
          section.style.marginBottom = '20px';

          const title = document.createElement('h2');
          title.textContent = key.replace(/-/g, ' ');

          const message = document.createElement('p');
          message.textContent = 'Press the "Add Numbers to Tool" button to add all the numbers, or manually add numbers with the keypad on the right side of the roulette board.';
          //message.style.fontStyle = 'italic'; // Optional styling
          message.style.color = '#555'; // Optional styling

          const textbox = document.createElement('textarea');
          textbox.value = numbers;
          textbox.id = `textbox-${key}`;
          textbox.style.width = '100%';
          textbox.style.height = '80px';
          textbox.style.marginTop = '10px';

          const logButton = document.createElement('button');
          logButton.textContent = 'Add Numbers to Tool';
          logButton.style.marginTop = '10px';
          logButton.addEventListener('click', () => {
              applyAPI(key);
          });

          section.appendChild(title);

          section.appendChild(message);
          section.appendChild(textbox);
          section.appendChild(logButton);
          content.appendChild(section);
      }

      // Add a button to refresh the data
      const refreshButton = document.createElement('button');
      refreshButton.innerText = 'Refresh Data';
      refreshButton.style.margin = '10px 0';
      refreshButton.style.display = 'block';
      refreshButton.addEventListener('click', async () => {
          const updatedData = await fetchAllRouletteData();
          for (const [key, numbers] of Object.entries(updatedData)) {
              const textbox = document.getElementById(`textbox-${key}`);
              if (textbox) {
                  textbox.value = numbers;
              }
          }
      });

      content.insertBefore(refreshButton, content.firstChild);

      panelContainer.appendChild(content);

      const closeButton = document.createElement('button');
      closeButton.innerText = 'Close';
      closeButton.style.position = 'absolute';
      closeButton.style.top = '10px';
      closeButton.style.right = '10px';
      closeButton.style.padding = '5px 10px';
      closeButton.style.backgroundColor = '#f44336';
      closeButton.style.color = '#fff';
      closeButton.style.border = 'none';
      closeButton.style.cursor = 'pointer';
      closeButton.style.borderRadius = '3px';

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

      panelContainer.appendChild(closeButton);
      document.body.appendChild(panelContainer);

      makeDraggableAPI(panelContainer);
  });
}

function api_button_on_click_event_old3(displayDivButton) {
  displayDivButton.addEventListener('click', async () => {
      if (document.getElementById('bulkPanelContainer')) return;

      const data = await fetchAllRouletteData();

      const panelContainer = document.createElement('div');
      panelContainer.id = 'bulkPanelContainer';
      panelContainer.style.position = 'fixed';
      panelContainer.style.top = '10%';
      panelContainer.style.left = '10%';
      panelContainer.style.width = '630px';
      panelContainer.style.height = '500px';
      panelContainer.style.backgroundColor = '#f2fcff';
      panelContainer.style.border = '1px solid #ccc';
      panelContainer.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.2)';
      panelContainer.style.overflow = 'auto';
      panelContainer.style.padding = '20px';
      panelContainer.style.zIndex = '1000';

      const content = document.createElement('div');
      content.innerHTML = `<h1>Live Roulette Results</h1>`;

      for (const [key, numbers] of Object.entries(data)) {
          const section = document.createElement('div');
          section.style.marginBottom = '20px';

          // Create a container for the title and refresh button
          const titleContainer = document.createElement('div');
          titleContainer.style.display = 'flex';
          titleContainer.style.justifyContent = 'space-between';
          titleContainer.style.alignItems = 'center';

          const title = document.createElement('h2');
          title.textContent = key.replace(/-/g, ' ');

          // Add a refresh button for this entry
          const refreshEntryButton = document.createElement('button');
          refreshEntryButton.textContent = 'Refresh';
          refreshEntryButton.style.marginLeft = '10px';
          refreshEntryButton.addEventListener('click', async () => {
              try {
                  const response = await fetch(apis[key]);
                  if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
                  const updatedData = await response.json();
                  const updatedNumbers = updatedData.recentNumbers.join(', ');
                  const textbox = document.getElementById(`textbox-${key}`);
                  if (textbox) {
                      textbox.value = updatedNumbers;
                  }
              } catch (error) {
                  console.error(`Failed to refresh data for ${key}:`, error);
              }
          });

          // Append title and button to title container
          titleContainer.appendChild(title);
          titleContainer.appendChild(refreshEntryButton);

          const message = document.createElement('p');
          message.textContent =
              'Press the "Add Numbers to Tool" button to add all the numbers, or manually add numbers with the keypad on the right side of the roulette board.';
          message.style.color = '#555';

          const textbox = document.createElement('textarea');
          textbox.value = numbers;
          textbox.id = `textbox-${key}`;
          textbox.style.width = '100%';
          textbox.style.height = '80px';
          textbox.style.marginTop = '10px';

          const logButton = document.createElement('button');
          logButton.textContent = 'Add Numbers to Tool';
          logButton.style.marginTop = '10px';
          logButton.addEventListener('click', () => {
              applyAPI(key);
          });

          section.appendChild(titleContainer); // Append title container with title and button
          section.appendChild(message);
          section.appendChild(textbox);
          section.appendChild(logButton);
          content.appendChild(section);
      }

      panelContainer.appendChild(content);

      const closeButton = document.createElement('button');
      closeButton.innerText = 'Close';
      closeButton.style.position = 'absolute';
      closeButton.style.top = '10px';
      closeButton.style.right = '10px';
      closeButton.style.padding = '5px 10px';
      closeButton.style.backgroundColor = '#f44336';
      closeButton.style.color = '#fff';
      closeButton.style.border = 'none';
      closeButton.style.cursor = 'pointer';
      closeButton.style.borderRadius = '3px';

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

      panelContainer.appendChild(closeButton);
      document.body.appendChild(panelContainer);

      makeDraggableAPI(panelContainer);
  });
}

function api_button_on_click_event(displayDivButton) {
  displayDivButton.addEventListener('click', () => {
      if (document.getElementById('bulkPanelContainer')) return;

      const panelContainer = document.createElement('div');
      panelContainer.id = 'bulkPanelContainer';
      panelContainer.style.position = 'fixed';
      panelContainer.style.top = '10%';
      panelContainer.style.left = '10%';
      panelContainer.style.width = '630px';
      panelContainer.style.height = '500px';
      panelContainer.style.backgroundColor = '#f2fcff';
      panelContainer.style.border = '1px solid #ccc';
      panelContainer.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.2)';
      panelContainer.style.overflow = 'auto';
      panelContainer.style.padding = '20px';
      panelContainer.style.zIndex = '1000';

      const content = document.createElement('div');
      content.innerHTML = `<h1>Live Roulette Results</h1>`;


      

      // Display titles without fetching all data
      for (const key of Object.keys(apis)) {
          const section = document.createElement('div');
          section.style.marginBottom = '20px';

          // Create a container for the title and refresh button
          const titleContainer = document.createElement('div');
          titleContainer.style.display = 'flex';
          titleContainer.style.justifyContent = 'space-between';
          titleContainer.style.alignItems = 'center';

          const title = document.createElement('h2');
          title.textContent = key.replace(/-/g, ' ');

          // Add a refresh button for this entry
          const refreshEntryButton = document.createElement('button');
          refreshEntryButton.textContent = 'Refresh';
          refreshEntryButton.style.marginLeft = '10px';
          refreshEntryButton.addEventListener('click', async () => {
              try {
                  const response = await fetch(apis[key]);
                  if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
                  const updatedData = await response.json();
                  const updatedNumbers = updatedData.recentNumbers.join(', ');
                  const textbox = document.getElementById(`textbox-${key}`);
                  if (textbox) {
                      textbox.value = updatedNumbers;
                  }
              } catch (error) {
                  console.error(`Failed to refresh data for ${key}:`, error);
              }
          });

          // Append title and button to title container
          titleContainer.appendChild(title);
          titleContainer.appendChild(refreshEntryButton);

          // Create an empty textbox for fetched data
          const textbox = document.createElement('textarea');
          textbox.id = `textbox-${key}`;
          textbox.style.width = '100%';
          textbox.style.height = '80px';
          textbox.style.marginTop = '10px';
          textbox.placeholder = 'Click Refresh to load data';

          const logButton = document.createElement('button');
          logButton.textContent = 'Add All Numbers to the Tool';
          logButton.style.marginTop = '10px';
          logButton.addEventListener('click', () => {
              applyAPI(key);
          });
          const manualAddText = document.createElement('span');
          manualAddText.textContent = 'Add all numbers once, \nthen manually add numbers with the keypad on the right side of the roulette board.';
          manualAddText.style.display = 'block'; // Ensure the text appears below the button
          manualAddText.style.marginTop = '5px';

          section.appendChild(titleContainer); // Append title container with title and button
          section.appendChild(textbox); // Append the empty textbox
          section.appendChild(logButton); // Append the add button
          section.appendChild(manualAddText);
       


          content.appendChild(section);
      }

      panelContainer.appendChild(content);

      const closeButton = document.createElement('button');
      closeButton.innerText = 'Close';
      closeButton.style.position = 'absolute';
      closeButton.style.top = '10px';
      closeButton.style.right = '10px';
      closeButton.style.padding = '5px 10px';
      closeButton.style.backgroundColor = '#f44336';
      closeButton.style.color = '#fff';
      closeButton.style.border = 'none';
      closeButton.style.cursor = 'pointer';
      closeButton.style.borderRadius = '3px';

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

      panelContainer.appendChild(closeButton);
      document.body.appendChild(panelContainer);

      makeDraggableAPI(panelContainer);
  });
}

function createApiCasinoPanel() {
  if (document.getElementById('bulkPanelContainer')) return null;

  const panelContainer = document.createElement('div');
  panelContainer.id = 'bulkPanelContainer';
  panelContainer.style.position = 'fixed';
  panelContainer.style.top = '10%';
  panelContainer.style.left = '10%';
  panelContainer.style.width = '630px';
  panelContainer.style.height = '500px';
  panelContainer.style.backgroundColor = '#f2fcff';
  panelContainer.style.border = '1px solid #ccc';
  panelContainer.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.2)';
  panelContainer.style.overflow = 'auto';
  panelContainer.style.padding = '20px';
  panelContainer.style.zIndex = '1000';

  const content = document.createElement('div');
  content.innerHTML = `<h1>Live Roulette Results</h1>`;

  for (const key of Object.keys(apis)) {
    const section = document.createElement('div');
    section.style.marginBottom = '20px';

    const titleContainer = document.createElement('div');
    titleContainer.style.display = 'flex';
    titleContainer.style.justifyContent = 'space-between';
    titleContainer.style.alignItems = 'center';

    const title = document.createElement('h2');
    title.textContent = key.replace(/-/g, ' ');

    const refreshEntryButton = document.createElement('button');
    refreshEntryButton.textContent = 'Refresh';
    refreshEntryButton.style.marginLeft = '10px';
    refreshEntryButton.addEventListener('click', async () => {
      try {
        const response = await fetch(apis[key]);
        if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
        const updatedData = await response.json();
        const updatedNumbers = updatedData.recentNumbers.join(', ');
        const textbox = document.getElementById(`textbox-${key}`);
        if (textbox) {
          textbox.value = updatedNumbers;
        }
      } catch (error) {
        console.error(`Failed to refresh data for ${key}:`, error);
      }
    });

    titleContainer.appendChild(title);
    titleContainer.appendChild(refreshEntryButton);

    const textbox = document.createElement('textarea');
    textbox.id = `textbox-${key}`;
    textbox.style.width = '100%';
    textbox.style.height = '80px';
    textbox.style.marginTop = '10px';
    textbox.placeholder = 'Click Refresh to load data';

    const logButton = document.createElement('button');
    logButton.textContent = 'Add All Numbers to the Tool';
    logButton.style.marginTop = '10px';
    logButton.addEventListener('click', () => {
      applyAPI(key);
    });

    const manualAddText = document.createElement('span');
    manualAddText.textContent = 'Add all numbers once, \nthen manually add numbers with the keypad on the right side of the roulette board.';
    manualAddText.style.display = 'block';
    manualAddText.style.marginTop = '5px';

    section.appendChild(titleContainer);
    section.appendChild(textbox);
    section.appendChild(logButton);
    section.appendChild(manualAddText);

    content.appendChild(section);
  }

  panelContainer.appendChild(content);

  const closeButton = document.createElement('button');
  closeButton.innerText = 'Close';
  closeButton.style.position = 'absolute';
  closeButton.style.top = '10px';
  closeButton.style.right = '10px';
  closeButton.style.padding = '5px 10px';
  closeButton.style.backgroundColor = '#f44336';
  closeButton.style.color = '#fff';
  closeButton.style.border = 'none';
  closeButton.style.cursor = 'pointer';
  closeButton.style.borderRadius = '3px';

  closeButton.addEventListener('click', () => {
    panelContainer.remove();
  });

  panelContainer.appendChild(closeButton);

  makeDraggableAPI(panelContainer);
  return panelContainer;
}

function buildApiFormPanel() {
  const panelContainer = document.createElement('div');
  panelContainer.id = 'bulkPanelContainer';
  panelContainer.style.width = '100%';
  panelContainer.style.backgroundColor = '#f2fcff';
  panelContainer.style.border = '1px solid #ccc';
  panelContainer.style.padding = '20px';
  panelContainer.style.boxSizing = 'border-box';

  const content = document.createElement('div');
  content.innerHTML = `<h1>Live Roulette Results</h1>`;

  for (const key of Object.keys(apis)) {
    const section = document.createElement('div');
    section.style.marginBottom = '20px';

    const titleContainer = document.createElement('div');
    titleContainer.style.display = 'flex';
    titleContainer.style.justifyContent = 'space-between';
    titleContainer.style.alignItems = 'center';

    const title = document.createElement('h2');
    title.textContent = key.replace(/-/g, ' ');

    const refreshEntryButton = document.createElement('button');
    refreshEntryButton.textContent = 'Refresh';
    refreshEntryButton.style.marginLeft = '10px';
    refreshEntryButton.addEventListener('click', async () => {
      try {
        const response = await fetch(apis[key]);
        if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
        const updatedData = await response.json();
        const updatedNumbers = updatedData.recentNumbers.join(', ');
        const textbox = document.getElementById(`textbox-${key}`);
        if (textbox) {
          textbox.value = updatedNumbers;
        }
      } catch (error) {
        console.error(`Failed to refresh data for ${key}:`, error);
      }
    });

    titleContainer.appendChild(title);
    titleContainer.appendChild(refreshEntryButton);

    const textbox = document.createElement('textarea');
    textbox.id = `textbox-${key}`;
    textbox.style.width = '100%';
    textbox.style.height = '80px';
    textbox.style.marginTop = '10px';
    textbox.placeholder = 'Click Refresh to load data';

    const logButton = document.createElement('button');
    logButton.textContent = 'Add All Numbers to the Tool';
    logButton.style.marginTop = '10px';
    logButton.addEventListener('click', () => {
      applyAPI(key);
    });

    const manualAddText = document.createElement('span');
    manualAddText.textContent = 'Add all numbers once, \nthen manually add numbers with the keypad on the right side of the roulette board.';
    manualAddText.style.display = 'block';
    manualAddText.style.marginTop = '5px';

    section.appendChild(titleContainer);
    section.appendChild(textbox);
    section.appendChild(logButton);
    section.appendChild(manualAddText);

    content.appendChild(section);
  }

  panelContainer.appendChild(content);
  return panelContainer;
}
function buildCasinoFetcherPanel() {
  const container = document.createElement('div');
  container.style.backgroundColor = 'white';
  container.style.padding = '20px';
  container.style.border = '1px solid #ccc';
  container.style.boxSizing = 'border-box';

  const headerContainer = document.createElement('div');
  headerContainer.style.display = 'flex';
  headerContainer.style.justifyContent = 'space-between';
  headerContainer.style.alignItems = 'center';
  headerContainer.style.marginBottom = '10px';

  const howToLink = document.createElement('div');
  howToLink.textContent = 'After selecting casino, Click the fetch button then Hold the Spin All Numbers button down until all numbers have been added Be patient please. Use the autospin button below for more options';
  howToLink.style.fontSize = '35px';
  howToLink.style.color = '#555';
  howToLink.style.maxWidth = '800px';
  howToLink.style.lineHeight = '1.2';
  headerContainer.appendChild(howToLink);
  container.appendChild(headerContainer);

  const liveLink = document.createElement('a');
  liveLink.href = 'https://gamble-galaxy.com/spins.php';
  liveLink.target = '_blank';
  liveLink.textContent = 'Show Live Numbers';
  liveLink.style.display = 'block';
  liveLink.style.marginTop = '20px';
  liveLink.style.fontSize = '35px'; // Make the link text bigger
  container.appendChild(liveLink);

  const title = document.createElement('h1');
  title.innerText = 'Live Casino Number Fetcher';
  container.appendChild(title);

  const dropdown = document.createElement('select');
  dropdown.style.width = '100%';
  dropdown.style.marginBottom = '10px';
  dropdown.style.padding = '5px';
  dropdown.style.fontSize = '35px';
  dropdown.style.height = '85px'; 

  const defaultOption = document.createElement('option');
  defaultOption.value = '';
  defaultOption.textContent = 'Select Casino';
  defaultOption.selected = true;
  dropdown.appendChild(defaultOption);

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

  const dropdownContainer = document.createElement('div');
  dropdownContainer.appendChild(dropdown);
  container.appendChild(dropdownContainer);

const textbox = document.createElement('textarea');
textbox.style.width = '100%';
textbox.style.height = '120px';
textbox.style.fontSize = '35px';
textbox.placeholder = 'Click Fetch to load numbers';

// Optional: give it a unique class
textbox.className = 'ai-textarea-placeholder';
container.appendChild(textbox);

// Add a CSS rule for placeholder styling
const style = document.createElement('style');
style.textContent = `
  .ai-textarea-placeholder::placeholder {
    font-size: 35px;
  }
`;
document.head.appendChild(style);


  let seenTimestamps = new Set();
  let fetchInterval = null;

  async function fetchNumbersFromSelectedFile() {
    if (!dropdown.value) return;
    try {
      const file = dropdown.value;
      const response = await fetch(file);
      if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
      const data = await response.json();
      const newNumbers = [];
      for (const entry of data) {
        const ts = entry.data?.settledAt;
        const number = entry.data?.result?.outcome?.number;
        if (ts && !seenTimestamps.has(ts) && typeof number === 'number') {
          seenTimestamps.add(ts);
          newNumbers.push(number);
        }
      }
      if (newNumbers.length > 0) {
        const existingNumbers = textbox.value
          .split(',')
          .map(n => n.trim())
          .filter(n => n !== '')
          .map(n => parseInt(n, 10));
        const updatedNumbers = newNumbers.concat(existingNumbers);
        textbox.value = updatedNumbers.join(', ');
      }
    } catch (err) {
      console.error('Fetch error:', err);
    }
  }

  dropdown.addEventListener('change', () => {
    textbox.value = '';
    if (fetchInterval) {
      clearInterval(fetchInterval);
      fetchInterval = null;
    }
    seenTimestamps.clear();
  });









const fetchButton = document.createElement('button');
fetchButton.textContent = 'Fetch Numbers from Casino';
fetchButton.style.marginTop = '15px';
fetchButton.style.marginLeft = '6px';
fetchButton.style.fontSize = '35px';  // bigger text
fetchButton.style.height = '85px';    // taller button
fetchButton.style.width = '98%';
fetchButton.addEventListener('click', () => {
  if (!dropdown.value) {
    alert('Please select a casino from the dropdown first.');
    return;
  }
  fetchNumbersFromSelectedFile();
  if (!fetchInterval) {
    fetchInterval = setInterval(fetchNumbersFromSelectedFile, 15000);
  }
});
container.appendChild(fetchButton);



const addOneButton = document.createElement('button');
addOneButton.textContent = 'Spin One Number';
addOneButton.style.marginTop = '15px';
addOneButton.style.marginLeft = '6px';
addOneButton.style.fontSize = '35px';  // bigger text
addOneButton.style.height = '85px';    // taller button
addOneButton.style.width = '98%'; 
addOneButton.addEventListener('click', async () => {
  const values = textbox.value.split(',').map(v => v.trim()).filter(v => v !== '');
  if (values.length > 0) {
    const last = parseInt(values.pop());
    if (!isNaN(last)) pushHistory(last);
    textbox.value = values.join(', ');
  }
});
container.appendChild(addOneButton);


const addAllButton = document.createElement('button');
addAllButton.innerHTML = 'Spin All Numbers<br><small>(hold 3 secs)</small>';
addAllButton.style.marginTop = '15px';
addAllButton.style.marginLeft = '6px';
addAllButton.style.fontSize = '50px';  // bigger text
addAllButton.style.height = '130px';    // taller button
addAllButton.style.width = '98%';   
addAllButton.style.position = 'relative';
addAllButton.style.overflow = 'hidden';
container.appendChild(addAllButton);
















  const progressOverlay = document.createElement('div');
  progressOverlay.style.position = 'absolute';
  progressOverlay.style.top = '0';
  progressOverlay.style.left = '0';
  progressOverlay.style.height = '100%';
  progressOverlay.style.width = '0%';
  progressOverlay.style.backgroundColor = 'hsl(59, 92.90%, 55.90%)';
  addAllButton.appendChild(progressOverlay);
  container.appendChild(addAllButton);

  let holdProgress = 0;
  let holdInterval = null;
  const holdDuration = 2000;
  const tickRate = 50;


function startHoldAction() {
  holdProgress = 0;
  progressOverlay.style.width = '0%';

  holdInterval = setInterval(() => {
    holdProgress += tickRate;
    const percent = Math.min((holdProgress / holdDuration) * 100, 100);
    progressOverlay.style.width = percent + '%';

    if (holdProgress >= holdDuration) {
      clearInterval(holdInterval);
      progressOverlay.style.width = '100%';

      const values = textbox.value.split(',').map(v => v.trim()).filter(v => v !== '');
      for (const value of values.reverse()) {
        const number = parseInt(value);
        if (!isNaN(number)) pushHistory(number);
      }
      textbox.value = '';

      setTimeout(() => {
        progressOverlay.style.width = '0%';
      }, 500);



    }
  }, tickRate);
}

function cancelHoldAction() {
  clearInterval(holdInterval);
  progressOverlay.style.width = '0%';
}

// ✅ Support desktop
addAllButton.addEventListener('mousedown', startHoldAction);
['mouseup', 'mouseleave'].forEach(evt =>
  addAllButton.addEventListener(evt, cancelHoldAction)
);

// ✅ Support mobile
addAllButton.addEventListener('touchstart', (e) => {
  e.preventDefault(); // important!
  startHoldAction();
});
['touchend', 'touchcancel'].forEach(evt =>
  addAllButton.addEventListener(evt, cancelHoldAction)
);


  

  const spacer = document.createElement('div');
  spacer.style.marginTop = '20px';
  container.appendChild(spacer);

  const importRow = document.createElement('div');
  importRow.style.display = 'flex';
  importRow.style.gap = '10px';
  container.appendChild(importRow);

  const importButton = document.createElement('button');
  importButton.textContent = 'Import Numbers from Text File';
  importButton.style.flex = '1';
    importButton.style.fontSize = '35px';
  importButton.style.height = '100px';
  importRow.appendChild(importButton);

  const reverseButton = document.createElement('button');
  reverseButton.textContent = 'Reverse Numbers in Textbox';
  reverseButton.style.flex = '1';
    reverseButton.style.fontSize = '35px';
  reverseButton.style.height = '100px';
  importRow.appendChild(reverseButton);

  const fileInput = document.createElement('input');
  fileInput.type = 'file';
  fileInput.accept = '.txt';
  fileInput.style.display = 'none';
  document.body.appendChild(fileInput);

  importButton.addEventListener('click', () => fileInput.click());

  fileInput.addEventListener('change', () => {
    const file = fileInput.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = function (e) {
      const content = e.target.result;
      const numbers = content
        .split(/[^0-9]+/)
        .map(n => parseInt(n, 10))
        .filter(n => !isNaN(n) && n >= 0 && n <= 38);
      textbox.value = numbers.join(', ');
    };
    if (fetchInterval) {
      clearInterval(fetchInterval);
      fetchInterval = null;
    }
    dropdown.selectedIndex = 0;
    reader.readAsText(file);
  });

  reverseButton.addEventListener('click', () => {
    const reversed = textbox.value
      .split(',')
      .map(n => n.trim())
      .filter(n => n !== '')
      .reverse();
    textbox.value = reversed.join(', ');
  });

  return container;
}

