function addBet() {
    // Get the number of current ParlayCalcRow elements
    const betCount = document.querySelectorAll('.bets_container > .row').length + 1;

    // Create the new HTML element
    const newBetDiv = document.createElement('div');
    newBetDiv.classList.add('row');
    newBetDiv.innerHTML = `
        <div class="ParlayCalcRow">
            <div class="row">
                <div class="label_box">
                    <label for="us-parlay">
                        <b>Bet ${betCount}</b>
                    </label>
                </div>
            </div>
            <div class="row">
                <div class="input_box">
                    <input id="bet_${betCount}" class="parlayInput" placeholder="eg -110" onblur="calculate_parlay();" type="text">
                </div>
            </div>
        </div>
        <div class="ParlayCalcRow">
        </div>
    `;

    // Append the new element to the bets_container
    document.querySelector('.bets_container').appendChild(newBetDiv);
    addKeydownEventListeners();
}

function calculate_parlay() {
    let parlayOdds_field = document.getElementById('payoutOdds');
    let payout_field = document.getElementById('payout');
    let betAmount_field = document.getElementById('wager');
    var betAmount = betAmount_field.value;//wager


    //validate betAmount value
    var oddsPattern = /^\d{1,4}$/;
    if (!oddsPattern.test(betAmount)) {
        showError('Please enter a valid Bet Amount, needs to be a number. (e.g., 100, 200, 670.5).');
        return;
    }
    else {
        clearError();
    }

    let payoutData = calculate_payout(betAmount);

    let impliedProbabilitytext = `${payoutData.combinedParlayOdds >= 0 ? '+' : ''}${Math.round(payoutData.combinedParlayOdds)}`;

    payout_field.value = '$' + payoutData.profit;
    parlayOdds_field.value = impliedProbabilitytext;
}

function calculate_payout(betAmount) {
    // Initialize 
    let multiplyRaw = 1;
    let odds = [];

    // Get all input elements inside the bets_container
    const betInputs = document.querySelectorAll('.bets_container input[id^="bet_"]');

    // Loop through each input and add its value to the sum
    betInputs.forEach(input => {
        // Convert the value to a number and add to sum
        if (!isNaN(input.value)) {
            odds.push(input.value);
        }
    });

    let payoutData = calculateParlayPayoutData(betAmount, odds);
    return payoutData;
}

function calculateParlayPayoutData(betAmount, odds) {
    const decimalOdds = odds.map(convertMoneylineToDecimal);
    const combinedParlayOdds = decimalOdds.reduce((acc, odd) => acc * odd, 1);
    const payout = betAmount * combinedParlayOdds;
    const profit = payout - betAmount;
    return { combinedParlayOdds: Math.floor((combinedParlayOdds - 1) * 100), payout: payout.toFixed(2), profit: profit.toFixed(2) };
}

function convertMoneylineToDecimal(moneyline) {
    if (moneyline < 0) {
        return 1 + (100 / -moneyline);
    } else {
        return 1 + (moneyline / 100);
    }
}

function validateOdds(input) {

    const inputValue = input.value.trim();
    var oddsPattern = /^[-+]{0,1}\d{1,4}$/;
    var errorPresent = false;


    if (inputValue === '-' || inputValue === '+') {
        //Will fail the test but we jump this evaluation to avoid trigger the error when just typing the american odds
        return;
    }

    if (inputValue === '') {
        clearError();
        return;
    }

    if (!oddsPattern.test(inputValue)) {
        showError('Please enter a valid American odds value (e.g., -200, +150).');
        errorPresent = true;
    }
    else {
        clearError();
    }

    return errorPresent;
}

function showError(message) {
    // Select the error field div
    const errorFieldDiv = document.querySelector('.covers-Calculators-errorField');

    // Add the 'show' class to the error field div
    errorFieldDiv.classList.add('show');

    // Select the direct child span element
    const errorMessageSpan = errorFieldDiv.querySelector('span');

    // Change the content of the span element
    errorMessageSpan.textContent = message;
}

function clearError() {
    // Select the error field div
    const errorFieldDiv = document.querySelector('.covers-Calculators-errorField');

    // Remove the 'show' class to the error field div
    errorFieldDiv.classList.remove('show');

    // Select the direct child span element
    const errorMessageSpan = errorFieldDiv.querySelector('span');

    // Change the content of the span element
    errorMessageSpan.textContent = '';
}

function addKeydownEventListeners() {
    const parlayInputs = document.querySelectorAll('.parlayInput');

    parlayInputs.forEach(input => {
        input.addEventListener('keyup', function (event) {
            validateOdds(input);
        });
    });
}

function resetParlayCalculator(calculatorID) {
    let calculator = document.getElementById(calculatorID);
    let parlayOdds_field = document.getElementById('payoutOdds');
    let payout_field = document.getElementById('payout');
    let betAmount_field = document.getElementById('wager');

    calculator.querySelector('.bets_container').innerHTML = "";
    payout_field.value = '$0.00';
    parlayOdds_field.value = '+100';
    betAmount_field.value = '10';
    addBet();
}

// Select all trigger elements
var triggers = document.querySelectorAll('.popover__trigger');

// Add a click event listener to the document
document.addEventListener('click', function (event) {
    // Loop through each trigger element
    triggers.forEach(function (trigger) {
        // Check if the clicked element is a trigger
        if (event.target === trigger) {
            // Find the parent popover element
            var popover = trigger.closest('.poppover');
            // Toggle the "--active" class on the parent popover element
            if (popover) {
                popover.classList.toggle('--active');
            }
        }
    });
});

// INIT
addKeydownEventListeners();