
let auto_play_zero_high = false;
let progression_play_zero_high = [];
let progression_play_zero_high_index = 0;
let zero_high_bet_ind_waiting = true;
let zero_high_bet_ind_placed = false;
let myBets = new Map();
let display_bet_only_zero_high = false;

const style_zero_high = document.createElement('style');
style_zero_high.textContent = `
.form-container_zero_high {
    display: block;
    width: 300px;
    margin-left: 20px; /* Align to the left */
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  }

  .form-group_zero_high {
    margin-bottom: 15px;
  }

  label_zero_high {
    font-weight: bold;
    margin-bottom: 5px;
    display: block;
  }

  input[type="text"].input_zero_high {
    width: 100%;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
  }

  button.button_zero_high {
    padding: 10px 15px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-weight: bold;
  }

  button.button_zero_high:hover {
    background-color: #45a049;
  }
`;
document.head.appendChild(style_zero_high);

// Function to populate 'button-bar-content'
function zero_high() {
    let buttonBarContent = document.getElementById('container-simulations');
    if(buttonBarContent)
    {
        auto_play_zero_high = false;
        progression_play_zero_high = [];
        let container = document.createElement('div');
        container.id = 'simulation-zero_high';
        container.style.marginLeft = '25px';
        container.style.marginBottom = '15px';



        // Simulations Button
        const simButton = document.createElement('button');
        simButton.id = 'sim-buttom-zero_high';
        simButton.textContent = "Back to simulations";
        simButton.style.padding = '5px';
        simButton.style.marginTop = '15px';
        simButton.style.marginRight = '5px';
        simButton.onclick = function() {
            buttonBarContent.innerHTML = '';
            let content = simulation_options();
            buttonBarContent.appendChild(content);
        };
        container.appendChild(simButton);

        // Color Changer
        let savedColor = localStorage.getItem(container.id+'-containerIdbackgroundColor');
        if (savedColor) {
            container.style.backgroundColor = savedColor;
        }
        let colorChangerQuickSpin = colorChanger(container.id);
        container.append(colorChangerQuickSpin);

        let title = document.createElement('h2');
        title.innerText = 'Zero High';
        title.style.marginBottom = '10px';
        title.style.color = '#333';
        

        /*******************************************************************
         * START: Help Div
         ******************************************************************/

        // Create the help button
        const button = document.createElement('button');
        button.id = 'help-button-zero_high';
        button.textContent = "How to";
        button.style.padding = '5px';
        button.style.marginRight = '5px';
        button.style.marginButton= '5px';
        button.style.marginTop= '10px';
        button.onclick = function() {
            const helpDiv = document.getElementById('help-div-zero_high');
            helpDiv.style.display = helpDiv.style.display === 'none' ? 'block' : 'none';
            
        };

        // Create the help div
        const helpDiv = document.createElement('div');
        helpDiv.id = 'help-div-zero_high';
        helpDiv.style.display = 'none'; // Initially hidden
        helpDiv.style.position = 'relative';
        helpDiv.style.width = '550px';
        helpDiv.style.padding = '15px';
        helpDiv.style.border = '1px solid #ccc';
        helpDiv.style.borderRadius = '8px';
        helpDiv.style.backgroundColor = '#f9f9f9';
        helpDiv.style.boxShadow = '0px 4px 8px rgba(0, 0, 0, 0.1)';
        helpDiv.style.marginTop = '5px';


        const helpParagraph = document.createElement('p');
        helpParagraph.innerHTML = `
        <h3>Zero High</h3>
          After a zero hits, start playing a progression on High. 
          'Run Test' will run the simulation showing only the 0 and progression parts. 
          Check the 'Auto play' to automatically make bets with that progression.
      
          <h3>The Observation</h3>
          This simulation is based on an observation that after a zero comes up, 
          the next number is either really high or really low.
      
          <br/>
          <a href="https://www.youtube.com/watch?v=bU7g470bVVg" target="_blank">
              What happens the spin after zero on roulette ???
          </a>
      
          <h2>The Test</h2>
          After a zero comes up, this simulation bets on high, using a progression.
      
          <h2>Tips</h2>
          Bet high and the first dozen for a more defensive bet. 
          Example: Bet 3 on High and 2 on the first dozen.
          
          Or 2 on highs and 1 on 1st dozen`;

        helpParagraph.style.fontSize = '24px';
        helpParagraph.style.color = '#555';
        helpParagraph.style.lineHeight = '1.5';

        // Append elements
        
    
        helpDiv.appendChild(helpParagraph);
        container.appendChild(button);
        container.appendChild(helpDiv);

        container.appendChild(title);
        
        let formContent = user_form_zero_high();
        container.appendChild(formContent);

        /*******************************************************************
         * END: Help Div
         ******************************************************************/
        buttonBarContent.innerHTML = '';
        buttonBarContent.appendChild(container); 
        }

    
}

function user_form_zero_high() {
  // Create container div
  const container = document.createElement('div');
  container.className = 'form-container_zero_high';


  // Retrieve saved form values from local storage
  const savedZeroType = localStorage.getItem('zeroType') || 'Zero';
  const savedProgression = localStorage.getItem('progression') || '1,2,3,4';
  const savedSpins = localStorage.getItem('spins') || '1000';

  // Radio button group for Zero/Double Zero
  const zeroGroup = document.createElement('div');
  zeroGroup.className = 'form-group_zero_high';

  const zeroLabel = document.createElement('label');
  zeroLabel.className = 'label_zero_high';
  zeroLabel.textContent = 'Choose Type: ';

  // Zero radio button
  const zeroRadio = document.createElement('input');
  zeroRadio.type = 'radio';
  zeroRadio.id = 'zero';
  zeroRadio.name = 'zero_type';
  zeroRadio.value = 'Zero';
  zeroRadio.checked = savedZeroType === 'Zero'; // Set Zero as default or saved value

  const zeroRadioLabel = document.createElement('label');
  zeroRadioLabel.setAttribute('for', 'zero');
  zeroRadioLabel.textContent = ' Zero ';

  // Double Zero radio button
  const doubleZeroRadio = document.createElement('input');
  doubleZeroRadio.type = 'radio';
  doubleZeroRadio.id = 'doubleZero';
  doubleZeroRadio.name = 'zero_type';
  doubleZeroRadio.value = 'Double Zero';
  doubleZeroRadio.checked = savedZeroType === 'Double Zero';

  const doubleZeroRadioLabel = document.createElement('label');
  doubleZeroRadioLabel.setAttribute('for', 'doubleZero');
  doubleZeroRadioLabel.textContent = ' Double Zero ';

  // Append radio buttons to the group
  zeroGroup.appendChild(zeroLabel);
  zeroGroup.appendChild(zeroRadio);
  zeroGroup.appendChild(zeroRadioLabel);
  zeroGroup.appendChild(doubleZeroRadio);
  zeroGroup.appendChild(doubleZeroRadioLabel);

  // Progression input group
  const progressionGroup = document.createElement('div');
  progressionGroup.className = 'form-group_zero_high';

  const progressionLabel = document.createElement('label');
  progressionLabel.className = 'label_zero_high';
  progressionLabel.setAttribute('for', 'progression_zero_high');
  progressionLabel.textContent = 'Progression (Separate by a comma ,)';

  const progressionInput = document.createElement('input');
  progressionInput.type = 'text';
  progressionInput.id = 'progression_zero_high';
  progressionInput.className = 'input_zero_high';
  progressionInput.placeholder = '1,2,3,4';
  progressionInput.value = savedProgression; // Set saved progression value
  progressionInput.addEventListener('blur', saveFormValues);

  progressionGroup.appendChild(progressionLabel);
  progressionGroup.appendChild(progressionInput);

  // Spins input group
  const spinsGroup = document.createElement('div');
  spinsGroup.className = 'form-group_zero_high';

  const spinsLabel = document.createElement('label');
  spinsLabel.className = 'label_zero_high';
  spinsLabel.setAttribute('for', 'spins_zero_high');
  spinsLabel.textContent = 'Spins';

  const spinsInput = document.createElement('input');
  spinsInput.type = 'text';
  spinsInput.id = 'spins_zero_high';
  spinsInput.className = 'input_zero_high';
  spinsInput.placeholder = '1000';
  spinsInput.value = savedSpins; // Set saved spins value

  spinsGroup.appendChild(spinsLabel);
  spinsGroup.appendChild(spinsInput);

  // Run Tests button
  const runTestsButton = document.createElement('button');
  runTestsButton.className = 'button_zero_high';
  runTestsButton.textContent = 'Run Tests';
  runTestsButton.onclick = function () {
    run_tests_zero_high();
      saveFormValues(); // Save form values to local storage when the button is clicked
      
  };
  const displayForm = document.createElement('div');
  displayForm.className = 'display_form_ddd';

  const display_bet_only = document.createElement('input');
  display_bet_only.type = 'checkbox';
  display_bet_only.id = 'display_bet_only_zero_high';
  display_bet_only.style.marginLeft = '10px';
  display_bet_only.onchange = function () {
    display_bet_only_zero_high = display_bet_only.checked;  
  };

  const display_bet_only_label = document.createElement('label');
  display_bet_only_label.setAttribute('for', 'display_bet_only_zero_high');
  display_bet_only_label.textContent = ' Display bets only ';


  displayForm.appendChild(runTestsButton);
  displayForm.appendChild(display_bet_only);
  displayForm.appendChild(display_bet_only_label);

    //************************************************************ */
  // Create the Auto Play checkbox group
  //************************************************************ */
  const autoPlayGroup = document.createElement('div');
  autoPlayGroup.className = 'form-group_zero_high';

  const autoPlayCheckbox = document.createElement('input');
  autoPlayCheckbox.type = 'checkbox';
  autoPlayCheckbox.id = 'autoPlay';
  autoPlayCheckbox.className = 'checkbox_zero_high';
  autoPlayCheckbox.onchange = function () {
      // Set or reset the global variable based on the checkbox state
      auto_play_zero_high = autoPlayCheckbox.checked;
      
      if(auto_play_zero_high)
      {
        progression_play_zero_high = get_progression_zero_high();
      }
      else
    {
      auto_play_zero_high == false;
      progression_play_zero_high = [];
    }
  };

  const autoPlayLabel = document.createElement('label');
  autoPlayLabel.setAttribute('for', 'autoPlay');
  autoPlayLabel.textContent = ' Auto Play';

// Append checkbox and label to the group and then to the container
  autoPlayGroup.appendChild(autoPlayCheckbox);
  autoPlayGroup.appendChild(autoPlayLabel);
//************************************************************ */

  //************************************************************ */
  // Div for table results.
  //************************************************************ */
  let content = document.createElement('div');
  content.id = 'content-zero_high';
//************************************************************ */

  // Append all elements to the container
  container.appendChild(autoPlayGroup);
  container.appendChild(zeroGroup);
  container.appendChild(progressionGroup);
  container.appendChild(spinsGroup);
  
  
  container.appendChild(displayForm);





  container.appendChild(content);

  // Save form values to local storage
  function saveFormValues() {
    const selectedZeroType = document.querySelector('input[name="zero_type"]:checked').value;
    localStorage.setItem('zeroType', selectedZeroType);
    localStorage.setItem('progression', progressionInput.value);
    if(spinsInput.value>100000) spinsInput.value = 100000;
    localStorage.setItem('spins', spinsInput.value);
  }

  return container;
}

function get_progression_zero_high()
{
  let progressionRaw = document.getElementById('progression_zero_high').value;
  if (isNaN(progressionRaw))
  {
    //progressionRaw = "1,2,3,4,5";
    document.getElementById('progression_zero_high').value = progressionRaw;
  }

  var cleanedProgressionRaw = progressionRaw.replace(/\s+/g, "").replace(/\./g, ",").replace(/[^0-9,]/g, "");
        
  let progression = cleanedProgressionRaw.split(',')
                  .map(number => parseInt(number, 10))
                  .filter(number => !isNaN(number));
                   
  return progression;
}

function get_spins_zero_high()
{
  const spinsInput = document.getElementById('spins_zero_high').value;

  let spins = parseInt(spinsInput, 10);
  
  if (isNaN(spins) || spins === 0) {
      spins = 1000; // Default value
      document.getElementById('spins_zero_high').value = spins;
  }
  if (spins > 20000) spins=20000;
  return spins;
}

function run_tests_zero_high() {
  
  //***************************************************************************
  // Get Form Values
  //***************************************************************************
  const progression = get_progression_zero_high();

  const spins = get_spins_zero_high();

  // Get selected radio button value
  const zeroType = document.querySelector('input[name="zero_type"]:checked').value;
  
  //***************************************************************************
  // Run Test
  //***************************************************************************

  let random_number = [];
  const range = zeroType === 'Zero' ? 37 : 38;
  
  for (let i = 0; i < spins; i++) {
      // Generate a random number between 1 and the specified range
      const randomNum = Math.floor(Math.random() * range) + 1;
      random_number.push(randomNum);
  }



  generate_chart(progression, random_number)
}

function generate_chart(progression, random_number) {
  // Create table
  const container = document.createElement('div');
  container.id = 'chart-zero-high';
  container.className = 'chart-container';

  const table = document.createElement('table');
  table.className = 'chart-table';

  // Create table header
  const headerRow = document.createElement('tr');
  const headers = ["Spin", "Number", "Bet", "Win/Loss", "Profit"];
  headers.forEach(headerText => {
      const th = document.createElement('th');
      th.textContent = headerText;
      headerRow.appendChild(th);
  });
  table.appendChild(headerRow);

  // Simulation Variables
  // Variables to track the last spin and profit
let lastSpin = null;
let profit = 0;
let betting = false;
let progressionIndex = 0;
let currentBet = 0;

// Run Simulation
random_number.forEach((spin, index) => {
    // Check if we should start betting
    if (!betting && (lastSpin === 37 || lastSpin === 38)) {
        betting = true;
        progressionIndex = 0; // Reset progression when betting starts
    }
    lastSpin = spin;

    // Initialize bet and win/loss
    let bet = 0;
    let winLoss = 0;

    // Betting logic
    if (betting) {
        currentBet = progression[progressionIndex];
        bet = currentBet;

        // Check if spin qualifies as a win HIGH
        if (spin >= 19 && spin < 37) {
            winLoss = bet; // Win
            profit += winLoss;
            betting = false; // Stop betting on win
            progressionIndex = 0; // Reset progression
        } else {
            winLoss = -bet; // Loss
            profit += winLoss;
            progressionIndex = progressionIndex += 1;
            if(progressionIndex > progression.length - 1)
            {
              progressionIndex = 0;
              betting = false; 
            }
            //Math.min(progressionIndex + 1, progression.length - 1); // Move to next progression
            
            
        }
    }

    // Only populate row if there's a bet or the spin is 37 or 38
    let showChart = true;
    if(display_bet_only_zero_high)
    {
      showChart = bet>0 || spin==37 || spin==38;
    }
    if (showChart) {
        const row = document.createElement('tr');

        // Populate row data
        const rowData = [
            index + 1,                    // Spin Number
            spin === 37 ? "0" : spin === 38 ? "00" : spin,                    // Number
            bet > 0 ? bet : "-",          // Bet
            winLoss > 0 ? `+${winLoss}` : winLoss < 0 ? `${winLoss}` : "-", // Win/Loss
            profit                        // Profit
        ];

        rowData.forEach(data => {
            const td = document.createElement('td');
            td.textContent = data;
            row.appendChild(td);
        });

        table.appendChild(row);
    }
});

  container.appendChild(table);

  let content = document.getElementById('content-zero_high');
  content.innerHTML = '';
  content.appendChild(container);

}
function undo_sim_zero_high()
{
  if(!auto_play_zero_high)
    {
      return;
    }

  progression_play_zero_high_index -= 1;
  if(progression_play_zero_high_index<0)
    {
      progression_play_zero_high_index = 0;
    } 
    else{
      myBets = new Map();
      place_bet_high(myBets, progression_play_zero_high[progression_play_zero_high_index]);
    }



}
function spin_sim_zero_high()
{

  if(auto_play_zero_high)
    {
      progression_play_zero_high = get_progression_zero_high();
    }
 

  if(auto_play_zero_high)
  {
    if(zero_high_bet_ind_waiting)
    {
      
      if(numbers.length>=2)
      {
        if(numbers[numbers.length - 1]==0 )
        {
          zero_high_bet_ind_waiting = false;
        }
      }
    }
  }

  // Check if won/loss and place bet or reset
  if(!zero_high_bet_ind_waiting && zero_high_bet_ind_placed)

  {
    
    // won - reset
    if(simulation_win_loss)
    {
      
      zero_high_bet_ind_placed = false;
      simulation_win_loss = false;
      zero_high_bet_ind_placed = false;
      zero_high_bet_ind_waiting = true;
      progression_play_zero_high_index = 0;
    }else // LOST
    {
    
      progression_play_zero_high_index += 1;

      

      if(progression_play_zero_high_index > progression_play_zero_high.length-1)
      {
        
        zero_high_bet_ind_placed = false;
        simulation_win_loss = false;
        zero_high_bet_ind_placed = false;
        zero_high_bet_ind_waiting = true;
        progression_play_zero_high_index = 0;
        myBets = new Map();


      }
      else{
        // Place Bet

        place_bet_high(myBets, progression_play_zero_high[progression_play_zero_high_index]);
      }
      


    }
  }

  // Place first bet
  if(!zero_high_bet_ind_waiting && !zero_high_bet_ind_placed)
  {


    place_bet_high(myBets, progression_play_zero_high[progression_play_zero_high_index]);
    zero_high_bet_ind_placed = true;
  }

}
