function calculate_hedging() {
    let initial_odds_field = document.getElementById('initial_odds');
    let bet_amount_field   = document.getElementById('bet_amount');
    let hedge_odds_field   = document.getElementById('hedge_odds');
    let hedge_amount_field = document.getElementById('hedge_amount');
    let hedge_total_payout_field = document.getElementById('hedgeTotalPayout');
    let hedge_profit_field = document.getElementById('hedgeProfit');
    var betAmount = bet_amount_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 hedgeCalcData = calculateHedgeBet(betAmount, initial_odds_field.value, hedge_odds_field.value);

    hedge_amount_field.value = hedgeCalcData.hedgeBetAmount;
    hedge_total_payout_field.value = '$' + hedgeCalcData.totalPayout;
    hedge_profit_field.value = '$' + hedgeCalcData.hedgeProfit;
}

function calculateHedgeBet(initialBetStr, initialOddsStr, hedgeOddsStr) {

    // Convert inputs to numbers
    const initialBet = parseFloat(initialBetStr);
    let initialOdds = initialOddsStr;
    let hedgeOdds = hedgeOddsStr;

    // Remove '+' sign if present in hedgeOdds and initialOdds

    if (initialOdds.startsWith('+')) {
        initialOdds = initialOdds.slice(1);
    }
    initialOdds = parseFloat(initialOdds);

    if (hedgeOdds.startsWith('+')) {
        hedgeOdds = hedgeOdds.slice(1);
    }
    hedgeOdds = parseFloat(hedgeOdds);

    // Calculate potential profit from the initial bet
    const potentialProfit = initialBet * (initialOdds / 100);

    // Total payout if the initial bet wins
    const totalPayout = initialBet + potentialProfit;

    // Calculate the hedge bet amount
    const hedgeBetAmount = totalPayout / ((Math.abs(hedgeOdds) / 100) + (hedgeOdds > 0 ? 1 : -1));

    // Hedge profit calculation
    const hedgeProfit = (totalPayout - hedgeBetAmount) - initialBet;

    return {
        hedgeBetAmount: (isNaN(hedgeBetAmount)? 0.00 : hedgeBetAmount.toFixed(2)),
        totalPayout: (isNaN(totalPayout)? 0.00 : totalPayout.toFixed(2)),
        hedgeProfit: (isNaN(hedgeProfit)? 0.00 : hedgeProfit.toFixed(2))
    };
}

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 resetHedgeCalculator(calculatorID) {
    let initial_odds_field = document.getElementById('initial_odds');
    let bet_amount_field   = document.getElementById('bet_amount');
    let hedge_odds_field   = document.getElementById('hedge_odds');
    let hedge_amount_field = document.getElementById('hedge_amount');
    let hedge_total_payout_field = document.getElementById('hedgeTotalPayout');
    let hedge_profit_field = document.getElementById('hedgeProfit');

    initial_odds_field.value = '10';
    bet_amount_field.value = '100';
    hedge_odds_field.value = '0';
    hedge_amount_field.value = '0';
    hedge_total_payout_field.value = '$0.00';
    hedge_profit_field.value = '$0.00';
}


function addKeydownEventListeners() {
    const hedgingInputs = document.querySelectorAll('.hedgingInput');

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

// 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();