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
    let initialBet = parseFloat(initialBetStr);
    let initialOdds = initialOddsStr;
    let hedgeOdds = hedgeOddsStr;

    // Remove '+' sign if present in initialOdds
    if (initialOddsStr.startsWith('+')) {
        initialOdds = initialOddsStr.slice(1);        
    }

    initialOdds = parseFloat(initialOdds);

    // Remove '+' sign if present in hedgeOdds
    if (hedgeOddsStr.startsWith('+')) {
        hedgeOdds = hedgeOddsStr.slice(1);
    }
    hedgeOdds = parseFloat(hedgeOdds);

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

    // Calculate the hedge bet amount based on whether the hedge odds are positive or negative
    let hedgeBetAmount;
    //let hedgeOddsDecimal =  parseFloat(moneyLineToDecimal(hedgeOdds).toFixed(2));
    let hedgeOddsDecimal =  parseFloat(moneyLineToDecimal(hedgeOdds));
    let initialProfit  = calculateInitialOddsProfit(initialOdds, initialBet);
    console.log(initialProfit);
    
    //hedgeBetAmount = Math.round((initialProfit + initialBet) / hedgeOddsDecimal);
    hedgeBetAmount = (initialProfit + initialBet) / hedgeOddsDecimal;

    //hedgeBetAmount = roundUpToNearestTens(hedgeBetAmount);
    hedgeBetAmount = hedgeBetAmount;

    hedgeBetAmount = hedgeBetAmount.toFixed(2);

    // Hedge profit calculation
    const hedgeProfit = initialProfit - hedgeBetAmount;

    // Total payout if the initial bet wins
    const totalPayout = initialBet + parseFloat(hedgeBetAmount) + hedgeProfit;

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

function calculateInitialOddsProfit(initialOdds, initialBet){
    //let initialOddsDecimal  = moneyLineToDecimal(initialOdds).toFixed(2);
    let initialOddsDecimal  = moneyLineToDecimal(initialOdds);
    let rawResult = (initialOddsDecimal * initialBet) - initialBet;

    return parseFloat(rawResult.toFixed(2));
}

function roundUpToNearestTens(num) {
    return Math.ceil(num / 10) * 10;
}

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 moneyLineToDecimal(moneyline) {
    var result = 0;
    if (moneyline < 0) {
        result = 1 + (100 / -moneyline);
    } else {
        result = 1 + (moneyline / 100);
    }

    return parseFloat(result);
}

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