<?php 
    if (isset($block['data']['isExample']) && $block['data']['isExample']) {
        echo '<img src="' . esc_url( $block['data']['preview_image'] ) . '"style="max-width:100%; min-width:100%" alt="Preview" />';
        return;
    }
    global $rdgb;
    $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();

    $block_styles = [];
    $block_classes = ['rdg-parlay-calculator'];
    $block_title = $rdgb->settings->getBlock(BLOCK_RDG_PARLAY_CALCULATOR);

    if (!empty($block['backgroundColor'])) {
        $block_classes[] = 'has-background';
        $block_classes[] = 'has-'.$block['backgroundColor'].'-background-color';
    }

    if (!empty($block['style']['color']['background'])) {
        $block_styles[] = 'background-color: '.$block['style']['color']['background'].';';
    }

    $titles = get_field('titles');
    $position_block = $rdgb->helpers->getBlocksSpaces(get_fields());

    $plugin_url = plugin_dir_url(__FILE__);

    $delete_icon = $plugin_url . 'assets/images/delete.svg';
    $add_icon = $plugin_url . 'assets/images/add.svg';
?>

<div class="rdg-blocks">
    <div class="<?php echo esc_attr(join(' ', $block_classes)); ?>" style="<?php echo $position_block . esc_attr(join(' ', $block_styles)); ?>">
        <div class="calculator-container">
            <div class="form-left">
                <div class="top-wrapper">
                    <div class="odds">
                        <label for="oddsType" class="form-label">Odds Type</label>
                        <div class="custom-select">
                            <select id="oddsType">
                                <option value="american">American Odds</option>
                                <option value="decimal">Decimal Odds</option>
                                <option value="fractional">Fractional Odds</option>
                            </select>
                        </div>
                    </div>
                    <div id="betsContainer">
                        <label class="form-label">Add Bet</label>
                        <input type="text"class="bet"/>
                    </div>
                    <button type="button" id="addBetBtn">Add Bet <img src="<?= esc_url($add_icon); ?>" alt="" srcset=""></button>
                </div>
                <div class="bottom-wrapper">
                    <div class="bets-wrapper">
                        <p class="form-label">Your bets</p>
                        <div class="bets-tags"></div>
                    </div>
                    <div class="bet-amount">
                        <label for="betAmount" class="form-label">Bet Amount ($)</label>
                        <input type="number" class="bet" min="1"  />
                        <p class="eg-text">E.g. 100</p>
                    </div>
                </div>
            </div>
            <div class="form-right">
                <div class="calculator-results">
                    <div class="to-win">
                        <p class="form-label">To win</p>
                        <p id="toWinAmount">$0.00</p> 
                    </div>
                    <div class="payout">
                        <p class="form-label">Payout</p>
                        <p id="payoutAmount">$0.00</p> 
                    </div>
                </div>
                <div class="buttons">
                    <button type="button" id="calculateBtn">Calculate</button>
                    <button type="button" id="resetBtn">Reset</button>
                </div>
            </div>
        </div>

        <script>
            document.addEventListener("DOMContentLoaded", function () {
            const addBetBtn = document.getElementById("addBetBtn");
            const betInput = document.querySelector("#betsContainer input");
            const betsTagsContainer = document.querySelector(".bets-tags");
            const oddsTypeSelect = document.getElementById("oddsType");
            const betAmountInput = document.querySelector(".bet-amount input");
            const toWinText = document.getElementById("toWinAmount");
            const payoutText = document.getElementById("payoutAmount");

            const emptyMessage = document.createElement("p");
            emptyMessage.textContent = "Try adding some bets.";
            emptyMessage.style.color = "#888";
            emptyMessage.style.fontStyle = "italic";
            betsTagsContainer.appendChild(emptyMessage);

            function updateEmptyMessage() {
                if (betsTagsContainer.querySelectorAll(".bet-tag").length === 0) {
                    emptyMessage.style.display = "block";
                } else {
                    emptyMessage.style.display = "none";
                }
            }

            const egText = document.createElement("p");
            egText.classList.add("eg-text");
            document.getElementById("betsContainer").appendChild(egText);

            function updateExampleText() {
                const oddsType = oddsTypeSelect.value;

                if (oddsType === "american") {
                    egText.textContent = "E.g. -110";
                } else if (oddsType === "decimal") {
                    egText.textContent = "E.g. 2.0";
                } else if (oddsType === "fractional") {
                    egText.textContent = "E.g. 1/1";
                } else {
                    egText.textContent = "";
                }
            }

            updateExampleText(); 

            oddsTypeSelect.addEventListener("change", updateExampleText);

            function isValidOdd(value, type) {
                if (type === "american") {
                    return /^[-+]?\d+$/.test(value.trim());
                } else if (type === "fractional") {
                    return /^\d+\/\d+$/.test(value.trim());
                } else if (type === "decimal") {
                    return /^\d+(\.\d+)?$/.test(value.trim()) && parseFloat(value) > 1;
                }
                return false;
            }

            function convertToDecimal(odd, type) {
                if (type === "american") {
                    const num = parseFloat(odd);
                    return num > 0 ? num / 100 + 1 : 100 / Math.abs(num) + 1;
                } else if (type === "fractional") {
                    const [num, denom] = odd.split("/").map(Number);
                    return num / denom + 1;
                } else if (type === "decimal") {
                    return parseFloat(odd);
                }
            }

            function createBetTag(value, type) {
                const betTag = document.createElement("div");
                betTag.classList.add("bet-tag");
                betTag.setAttribute("data-odds-type", type); 
                betTag.setAttribute("data-odds-value", value); 

                betTag.innerHTML = `
                ${value}
                <img src="<?= esc_url($delete_icon); ?>" alt="Delete" class="delete-icon">
            `;

                betTag.querySelector(".delete-icon").addEventListener("click", function () {
                    betTag.remove();
                    updateEmptyMessage();
                });

                betsTagsContainer.appendChild(betTag);
                updateEmptyMessage();
            }

            addBetBtn.addEventListener("click", function () {
                const value = betInput.value.trim();
                const oddsType = oddsTypeSelect.value;

                if (!isValidOdd(value, oddsType)) {
                    betInput.setCustomValidity("Please enter a valid bet according to the odds type.");
                    betInput.reportValidity();
                    return;
                } else {
                    betInput.setCustomValidity("");
                }

                createBetTag(value, oddsType);
                betInput.value = "";
            });

            const calculateBtn = document.getElementById("calculateBtn");
            calculateBtn.addEventListener("click", function () {
                const betTags = document.querySelectorAll(".bet-tag");
                let totalOdds = 1;

                betTags.forEach((tag) => {
                    const value = tag.getAttribute("data-odds-value");
                    const type = tag.getAttribute("data-odds-type");
                    const decimalOdd = convertToDecimal(value, type);
                    totalOdds *= decimalOdd;
                });

                const betAmount = parseFloat(betAmountInput.value);
                if (isNaN(betAmount) || betAmount <= 0 || betTags.length === 0) {
                    toWinText.textContent = "$0.00";
                    payoutText.textContent = "$0.00";
                    return;
                }

                const payout = betAmount * totalOdds;
                const toWin = payout - betAmount;

                toWinText.textContent = `$${toWin.toFixed(2)}`;
                payoutText.textContent = `$${payout.toFixed(2)}`;
            });

            const resetBtn = document.getElementById("resetBtn");
            resetBtn.addEventListener("click", function () {
                betsTagsContainer.innerHTML = ""; 
                betsTagsContainer.appendChild(emptyMessage); 
                updateEmptyMessage();
                betAmountInput.value = "";
                toWinText.textContent = "$0.00";
                payoutText.textContent = "$0.00";
            });

            updateEmptyMessage(); 
        });
        </script>
    </div>
</div>
