@using SicboSub.Web.Helpers;
@using SicboSub.Web.Language;
@{
    Layout = "_GameLayout";
    var packages = Context.Session.GetComplexData<List<SicboSub.Web.Models.PackageInfo>>("Packages");
    var isRegistered = Context.Session.GetComplexData<bool?>("isRegistered") ?? false;
    var msisdn = Context.Session.GetComplexData<string>("msisdn") ?? "";
}

@section Styles {
    <link rel="stylesheet" href="~/css/sicbo-popup.css" asp-append-version="true" />
}
<!-- Game User Info Header -->

<div class="home">
    <div class="image-2-parent">
        <img class="image" src="~/img/image-2.png" />
        <img class="image-2-icon" alt="" src="~/img/image-2.png" style="display:none;">
        
        <img class="frame-child" src="~/img/image-1.png" alt="Logo">

        <partial name="_GameMenu" />

        
    </div>
    @if (ViewData["IsAuthenticated"] is bool isAuth && isAuth)
    {
        <div class="frame-parent">
            <div class="medal-parent">
                <img class="hourglass-icon" src="~/img/021-medal-2.svg" alt="">
                <div class="ranking-coin">@Language.Rankingcoin</div>
                <a class="view-ranking-coin">@Language.ViewRankingCoin</a>
            </div>
            <div class="frame-group">
                <div class="frame-container">
                    <div class="my-play-parent">
                        <div class="my-play">@Language.Myplay</div>
                        <div class="frame-item">
                        </div>
                    </div>
                    <div class="sword-parent">
                        <img class="sword-icon" src="~/img/003-sword.svg" alt="">
                        <div id="betCoinVal" class="my-play">@String.Format("{0:n0}", ViewData["BetCoin"])</div>
                    </div>
                </div>
                <div class="frame-container">
                    <div class="my-coins-parent">
                        <div class="my-play">@Language.MyCoins</div>
                        <div class="frame-item">
                        </div>
                    </div>
                    <div class="sword-parent">
                        <img class="sword-icon" src="~/img/021-medal.svg" alt="">
                        <div id="winCoinVal" class="my-play">@String.Format("{0:n0}", ViewData["WinCoin"])</div>
                    </div>
                </div>
            </div>
        </div>
    
    <div class="frame-parent3">
        <div id="registerBtnContainer" class="rectangle-parent" style="cursor: pointer;" onclick="handleRegisterClick()">
            <div class="rectangle-div">
            </div>
            <!-- Register/Withdraw Button -->
            <div id="registerBtnLabel" class="button-label">@(isRegistered ? Language.Withdraw : Language.Register)</div>
        </div>
        <div class="rectangle-parent" style="cursor: pointer;" onclick="handleBuyMore()">
            <div class="rectangle-div">
            </div>
            <!-- Buy more Button -->
            <div class="button-label2">@Language.BuyMore</div>
        </div>

        <!-- PLAY BUTTON COMPLEX -->
        <div class="button-small" style="cursor: pointer;" onclick="handlePlay()">
            <div class="button-small-child"></div>
            <div class="button-small-item"></div>

            <img class="button-small-inner" src="~/img/rectangle-314.svg" alt="">
            <img class="rectangle-icon" src="~/img/rectangle-315.svg" alt="">
            <img class="button-small-child2" src="~/img/rectangle-316.svg" alt="">

            <img class="frame-icon" src="~/img/rectangle-315.svg" alt=""> <!-- subtract-2.svg inside? -->

            <img class="button-small-child3" src="~/img/rectangle-315.svg" alt="">
            <img class="button-small-child4" src="~/img/rectangle-317.svg" alt="">
            <img class="button-small-child5" src="~/img/image.svg" alt="">
            <img class="button-small-child6" src="~/img/rectangle-317.svg" alt="">

            <img class="vector-icon" src="~/img/Frame 1244831299.svg" alt="">
            <img class="vector-icon2" src="~/img/vector.svg" alt="">
            <img class="vector-icon3" src="~/img/Frame 1244831300.svg" alt="">
            <img class="vector-icon4" src="~/img/Frame 1244831300.svg" alt="">

            <div class="button-label3">@Language.Play</div>
        </div>
    </div>
    <!-- <img class="home-barpro-icon" alt=""> -->
    }
    <!-- Select Package Popup -->
    <div id="selectPackagePopup" class="popup-overlay" style="display: none;">
        <div class="popup-container">
            <!-- Header -->
            <div class="popup-header">
                <span class="popup-title">@Language.SelectPackage</span>
            </div>
            
            <!-- Close Button -->
            <button class="popup-close-btn" onclick="closePackagePopup()">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
                    <path d="M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7a1 1 0 0 0-1.41 1.41L10.59 12l-4.89 4.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 0 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4z"/>
                </svg>
            </button>
            
            <!-- Package Options -->
            <div class="package-list">
                @if (packages != null && packages.Any())
                {
                    var isFirst = true;
                    foreach (var pkg in packages)
                    {
                        var checkedAttr = isFirst ? "checked" : "";
                        isFirst = false;
                        <label class="package-option">
                            <input type="radio" name="package" value="@pkg.productName" data-price="@pkg.fee" data-coin="@pkg.numberSpin" @checkedAttr />
                            <span class="package-coins">@String.Format("{0:n0}", pkg.numberSpin) <span class="coins-text">@Language.Coins</span></span>
                            <span class="package-htg">@String.Format("{0:n0}", pkg.fee) <span class="htg-text">@Language.HTG</span></span>
                        </label>
                    }
                }
                else
                {
                     <div style="color:white;text-align:center;">No packages available</div>
                }
            </div>
            
            <!-- Action Buttons -->
            <div class="popup-actions">
                @* <button class="popup-btn cancel-btn" onclick="closePackagePopup()">@Language.Cancel</button> *@
                <button class="popup-btn next-btn" onclick="handlePackageNext()">@Language.Buynow</button>
            </div>
        </div>
    </div>

    <!-- Confirm Buy More Popup -->
    <div id="confirmBuyMorePopup" class="popup-overlay" style="display: none;">
        <div class="popup-container confirm-popup">
            <!-- Header -->
            <div class="popup-header">
                <span class="popup-title">@Language.ConfirmBuyMore</span>
            </div>
            
            <!-- Close Button -->
            <button class="popup-close-btn" onclick="closeConfirmPopup()">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
                    <path d="M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7a1 1 0 0 0-1.41 1.41L10.59 12l-4.89 4.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 0 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4z"/>
                </svg>
            </button>
            
            <!-- Confirm Content -->
            <div class="confirm-content">
                @* <p class="confirm-message">@Language.DoYouWantToBuy</p> *@
                <p class="confirm-coins"><span id="confirmCoinsAmount">100</span> <span class="coins-label">@Language.Coins</span>/ <span id="confirmPriceAmount">1</span> <span class="htg-label">@Language.HTG</span></p>
                @* <p class="confirm-price">Price <span id="confirmPriceAmount">1</span> <span class="htg-label">@Language.HTG</span></p> *@
            </div>
            
            <!-- Action Buttons -->
            <div class="popup-actions">
                @* <button class="popup-btn cancel-btn" onclick="closeConfirmPopup()">@Language.Cancel</button> *@
                <button class="popup-btn next-btn" onclick="handleConfirmBuy()">@Language.Confirm</button>
            </div>
        </div>
    </div>

    <!-- Register Popup -->
    <div id="registerPopup" class="popup-overlay" style="display: none;">
        <div class="popup-container register-popup">
            <!-- Close Button -->
            <button class="popup-close-btn" onclick="closeRegisterPopup()">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
                    <path d="M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7a1 1 0 0 0-1.41 1.41L10.59 12l-4.89 4.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 0 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4z"/>
                </svg>
            </button>
            
            <!-- Register Content -->
            <div class="register-content">
                <!-- Character Image (left side) -->
                <div class="register-character">
                    <img src="~/img/register-character.png" alt="Character" />
                </div>
                
                <!-- Right Side Content -->
                <div class="register-right">
                    <!-- Question Mark Icon -->
                    <div class="register-question-icon">
                        <img src="~/img/question-icon.png" alt="?" />
                    </div>
                    
                    <!-- Text Content -->
                    <div class="register-text">
                        @Html.Raw(Language.ConfirmDailyPackage)
                        @* @Language.ConfirmDailyPackage *@
                    </div>
                    
                    <!-- Confirm Button -->
                    <button class="popup-btn next-btn register-confirm-btn" onclick="handleRegisterConfirm()">@Language.Confirm</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Withdraw Popup -->
    <div id="withdrawPopup" class="popup-overlay" style="display: none;">
        <div class="popup-container withdraw-popup">
            <!-- Close Button -->
            <button class="popup-close-btn" onclick="closeWithdrawPopup()">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
                    <path d="M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7a1 1 0 0 0-1.41 1.41L10.59 12l-4.89 4.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 0 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4z"/>
                </svg>
            </button>
            
            <!-- Withdraw Content -->
            <div class="withdraw-content">
                <!-- Left Side - Account Info -->
                <div class="withdraw-left">
                    <div class="withdraw-phone">
                        <span class="withdraw-label">@Language.PhoneNumber</span>
                        <span class="withdraw-phone-number">@msisdn</span>
                    </div>
                    
                    <div class="withdraw-balance-badge">@Language.MainBalance</div>
                    
                    <div class="withdraw-info">
                        <span class="withdraw-info-label">@Language.TotalValueToday</span>
                        <span class="withdraw-info-value">100 @Language.HTG</span>
                    </div>
                    
                    <div class="withdraw-info">
                        <span class="withdraw-info-label">@Language.CoinAmount</span>
                        <span id="withdrawPopupCoinValue" class="withdraw-coin-amount">@String.Format("{0:n0}", ViewData["WinCoin"])</span>
                    </div>
                </div>
                
                <!-- Right Side - Withdraw Options -->
                <div class="withdraw-right">
                    <span class="withdraw-options-title">@Language.WithdrawValue</span>
                    
                    <div class="withdraw-options">
                        @{
                            var exchangeConfigs = Context.Session.GetComplexData<List<SicboSub.Web.Models.ExchangeConfigItem>>("ExchangeConfig");
                        }
                        
                        @if (exchangeConfigs != null && exchangeConfigs.Any())
                        {
                            bool isFirst = true;
                            foreach (var config in exchangeConfigs)
                            {
                                var checkedAttr = isFirst ? "checked" : "";
                                isFirst = false;
                                <label class="withdraw-option">
                                    <input type="radio" name="withdrawValue" value="@config.id" data-coins="@config.coinCost" data-money="@config.moneyReceived" @checkedAttr />
                                    <span class="withdraw-option-coins">@config.coinCost.ToString("N0") <span class="coins-text">@Language.Coins</span></span>
                                    <span class="withdraw-option-htg">@config.moneyReceived.ToString("N0") <span class="htg-text">@Language.HTG</span></span>
                                </label>
                            }
                        }
                        else
                        {
                            <div style="color:white;text-align:center;">
                               
                            </div>
                        }
                    </div>
                </div>
            </div>
            
            <!-- Withdraw Button -->
            <button class="withdraw-btn" onclick="handleWithdrawConfirm()">@Language.Withdraw</button>
        </div>
    </div>

    </div>

    <!-- Confirm Withdraw Popup -->
    <div id="confirmWithdrawPopup" class="popup-overlay" style="display: none;">
        <div class="popup-container confirm-popup">
            <!-- Header -->
            <div class="popup-header">
                <span class="popup-title">Confirm withdraw</span>
            </div>
            
            <!-- Close Button -->
            <button class="popup-close-btn" onclick="closeConfirmWithdrawPopup()">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
                    <path d="M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7a1 1 0 0 0-1.41 1.41L10.59 12l-4.89 4.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 0 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4z"/>
                </svg>
            </button>
            
            <!-- Confirm Content -->
            <div class="confirm-content">
                <p class="confirm-message">Do you want to withdraw?</p>
                <p class="withdraw-amount-display"><span id="withdrawAmountHtg" class="amount-highlight">0</span> @Language.HTG</p>
                
                <div class="withdraw-details">
                   <div class="detail-row">
                       <span class="detail-label">Fee</span>
                       <span class="detail-value"><span id="withdrawFeePoints">0</span> @Language.Coins</span>
                   </div>
                   <div class="detail-row">
                       <span class="detail-label">Balance</span>
                       <span class="detail-value"><span id="withdrawBalancePoints">0</span> @Language.Coins</span>
                   </div>
                </div>
            </div>
            
            <!-- Action Buttons -->
            <div class="popup-actions">
                <button class="popup-btn cancel-btn" onclick="closeConfirmWithdrawPopup()">@Language.Cancel</button>
                <button class="popup-btn next-btn" onclick="processWithdraw()">@Language.Confirm</button>
            </div>
        </div>
    </div>

    <!-- OTP Popup -->
    <div id="otpPopup" class="popup-overlay" style="display: none;">
        <div class="popup-container otp-popup">
            <div class="popup-header">
                <span class="popup-title">@Language.OTPVerification</span>
            </div>
             <button class="popup-close-btn" onclick="closeOtpPopup()">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
                    <path d="M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7a1 1 0 0 0-1.41 1.41L10.59 12l-4.89 4.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 0 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4z"/>
                </svg>
            </button>

            <div class="otp-content">
                <p>Please enter the OTP sent to your phone</p>
                <!-- 6 OTP Boxes -->
                <div class="otp-inputs" id="otpInputContainer">
                    <input type="text" class="otp-box" maxlength="1" data-index="0" />
                    <input type="text" class="otp-box" maxlength="1" data-index="1" />
                    <input type="text" class="otp-box" maxlength="1" data-index="2" />
                    <input type="text" class="otp-box" maxlength="1" data-index="3" />
                    <input type="text" class="otp-box" maxlength="1" data-index="4" />
                    <input type="text" class="otp-box" maxlength="1" data-index="5" />
                </div>
                <button class="popup-btn next-btn" onclick="verifyOtp()">@Language.Verify</button>
            </div>
        </div>
    </div>

    <!-- Message Popup (Success/Error) - Redesigned -->
    <div id="messagePopup" class="popup-overlay" style="display: none;">
        <div id="messagePopupContainer" class="message-popup-container-custom">
            <!-- Top Right Close Button (Red Circle) -->
            <button class="message-close-btn-custom" onclick="closeMessagePopup()">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="4" stroke-linecap="round" stroke-linejoin="round">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>

            <!-- Dice Decorations - Success -->
            <div id="diceSuccess" class="dice-set" style="display: none;">
                <img src="~/img/dice_success_1.png" alt="" class="message-dice-bottom-left" />
                <img src="~/img/dice_success_2.png" alt="" class="message-dice-bottom-right" />
                <img src="~/img/dice_success_1.png" alt="" class="message-dice-top-left" />
                <img src="~/img/dice_success_2.png" alt="" class="message-dice-top-right" />
            </div>
            
            <!-- Dice Decorations - Error -->
            <div id="diceError" class="dice-set" style="display: none;">
                <img src="~/img/xucto1.png" alt="" class="message-dice-bottom-left" />
                <img src="~/img/xucto2.png" alt="" class="message-dice-bottom-right" />
                <img src="~/img/xucto1.png" alt="" class="message-dice-top-left" />
                <img src="~/img/xucto2.png" alt="" class="message-dice-top-right" />
            </div>

            <!-- Content -->
            <div class="message-content-custom">
                <!-- Title -->
                <div id="messageTitleCustom" class="message-title-custom">@Language.StatusSuccessful</div>
                
                <!-- Message -->
                <div id="messageTextCustom" class="message-text-custom">
                    <!-- Message text injected via JS -->
                </div>

                <!-- Bottom Action Button -->

                <button id="messageActionBtn" class="message-action-btn-custom" onclick="closeMessagePopup()">@Language.PlayNow</button>
            </div>
        </div>
    </div>

    <!-- Exchange Success Popup (Redesigned) -->
    <div id="exchangeSuccessPopup" class="popup-overlay" style="display: none;">
        <div class="exchange-popup-container-custom">
            <!-- Top Right Close Button (Red Circle) -->
            <button class="exchange-close-btn-custom" onclick="closeExchangeSuccessPopup()">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="4" stroke-linecap="round" stroke-linejoin="round">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>

            <!-- Content -->
            <div class="exchange-success-content-custom">
                <!-- Title -->
                <div class="exchange-title-custom">@Language.Congratulations !</div>
                
                <!-- Message -->
                <div id="exchangeSuccessMessage" class="exchange-message-custom">
                    <!-- Message text injected via JS -->
                </div>

                <!-- Bottom Action Button -->
                <button class="exchange-action-btn-custom" onclick="closeExchangeSuccessPopup()">@Language.Close</button>
            </div>
        </div>
    </div>

</div>

@section Scripts {
    <script>
        // Message Popup Logic (Redesigned)
        function showMessagePopup(type, message) {
            const popup = document.getElementById('messagePopup');
            const container = document.getElementById('messagePopupContainer');
            const titleContainer = document.getElementById('messageTitleCustom');
            const textContainer = document.getElementById('messageTextCustom');
            const diceSuccess = document.getElementById('diceSuccess');
            const diceError = document.getElementById('diceError');
            const actionBtn = document.getElementById('messageActionBtn');
            
            // Set message
            textContainer.textContent = message;
            
            // Set title, background and dice based on type
            if (type === 'success') {
                titleContainer.textContent = '@Language.StatusSuccessful';
                if (actionBtn) {
                    actionBtn.textContent = '@Language.PlayNow';
                    actionBtn.onclick = function() {
                        window.location.href = '/Home/Play';
                    };
                }
                container.className = 'message-popup-container-custom success';
                // Show success dice, hide error dice
                diceSuccess.style.display = 'block';
                diceError.style.display = 'none';
            } else {
                titleContainer.textContent = '@Language.StatusFailed';
                if (actionBtn) {
                    actionBtn.textContent = '@Language.Close';
                    actionBtn.onclick = closeMessagePopup;
                }
                container.className = 'message-popup-container-custom error';
                // Show error dice, hide success dice
                diceSuccess.style.display = 'none';
                diceError.style.display = 'block';
            }
            
            popup.style.display = 'flex';
        }

        function closeMessagePopup() {
            document.getElementById('messagePopup').style.display = 'none';
        }

        function showExchangeSuccessPopup(message) {
            const popup = document.getElementById('exchangeSuccessPopup');
            const textContainer = document.getElementById('exchangeSuccessMessage');
            if (textContainer) {
                textContainer.textContent = message;
            }
            popup.style.display = 'flex';
        }

        function closeExchangeSuccessPopup() {
            document.getElementById('exchangeSuccessPopup').style.display = 'none';
        }

        // Override Site methods to use our custom popup
        // Ensure this runs after site.js
        $(document).ready(function() {
            if (typeof Site !== 'undefined') {
                Site.showSuccess = function(message) {
                    showMessagePopup('success', message);
                };
                
                Site.showError = function(message) {
                    showMessagePopup('error', message);
                };
            }
            
            // Setup OTP Input Logic
            setupOtpInputs();
        });
        
        // OTP Inputs Logic
        function setupOtpInputs() {
            const container = document.getElementById('otpInputContainer');
            if (!container) return;
            
            const inputs = container.querySelectorAll('.otp-box');
            
            inputs.forEach((input, index) => {
                // Determine pattern to only allow numbers?
                input.addEventListener('input', function(e) {
                     // Ensure primitive validation: only numbers
                     this.value = this.value.replace(/[^0-9]/g, '');
                     
                     if (this.value.length >= 1) {
                         if (index < inputs.length - 1) {
                             inputs[index + 1].focus();
                         }
                     }
                });
                
                input.addEventListener('keydown', function(e) {
                    if (e.key === 'Backspace' && this.value === '') {
                        if (index > 0) {
                            inputs[index - 1].focus();
                        }
                    }
                });
                
                // On paste?
                 input.addEventListener('paste', function(e) {
                    e.preventDefault();
                    const text = (e.clipboardData || window.clipboardData).getData('text');
                    if (!text) return;
                    const digits = text.replace(/[^0-9]/g, '').split('');
                    if (digits.length > 0) {
                        let currentIndex = index;
                        for (let i = 0; i < digits.length; i++) {
                            if (currentIndex < inputs.length) {
                                inputs[currentIndex].value = digits[i];
                                currentIndex++;
                            }
                        }
                        // Focus on the next available or last
                        if (currentIndex < inputs.length) {
                             inputs[currentIndex].focus();
                        } else {
                             inputs[inputs.length - 1].focus();
                        }
                    }
                 });
            });
        }

        // Track registration state
        var isRegistered = @(isRegistered.ToString().ToLower());
        
        function handleRegisterClick() {
            if (isRegistered) {
                // Already registered, show withdraw popup
                handleWithdraw();
            } else {
                // Not registered, show register popup
                handleRegister();
            }
        }
        
        function handleRegister() {
            // Show the register popup
            document.getElementById('registerPopup').style.display = 'flex';
        }
        
        function closeRegisterPopup() {
            document.getElementById('registerPopup').style.display = 'none';
        }
        
        function handleRegisterConfirm() {
            Site.showLoading();
            
            $.ajax({
                url: '/Home/Register',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({}),
                success: function(response) {
                    Site.hideLoading();
                    
                    if (response.errorCode === '0' || response.errorCode === 0) {
                       Site.showSuccess(response.message);
                       
                       // Mark as registered and change button to Withdraw
                       isRegistered = true;
                       document.getElementById('registerBtnLabel').textContent = 'Withdraw'; 
                       
                       // Update coins
                       if(response.data) {
                           if(document.getElementById('betCoinVal')) document.getElementById('betCoinVal').textContent = Site.formatNumber(response.data.betCoin);
                           if(document.getElementById('winCoinVal')) {
                               const formattedWinCoin = Site.formatNumber(response.data.winCoin);
                               document.getElementById('winCoinVal').textContent = formattedWinCoin;
                               if(document.getElementById('withdrawPopupCoinValue')) {
                                    document.getElementById('withdrawPopupCoinValue').textContent = formattedWinCoin;
                               }
                           }
                       }

                       closeRegisterPopup();
                       
                       // No reload needed
                    } else {
                       Site.showError(response.message || 'Registration failed');
                       closeRegisterPopup();
                    }
                },
                error: function(xhr, status, error) {
                    Site.hideLoading();
                    console.error('Register error:', error);
                    Site.showError('Connection error: ' + error);
                }
            });
        }
        
        function handleWithdraw() {
            // Show the withdraw popup
            document.getElementById('withdrawPopup').style.display = 'flex';
        }
        
        function closeWithdrawPopup() {
            document.getElementById('withdrawPopup').style.display = 'none';
        }
        
        // Global variables for withdraw flow
        let selectedWithdrawConfig = null;

        function handleWithdrawConfirm() {
            const selectedOption = document.querySelector('input[name="withdrawValue"]:checked');
            if (selectedOption) {
                const configId = selectedOption.value;
                const coins = parseFloat(selectedOption.getAttribute('data-coins'));
                const money = parseFloat(selectedOption.getAttribute('data-money'));
                const feeRatio = 0; 
                
                selectedWithdrawConfig = {
                    id: configId,
                    coins: coins,
                    money: money
                };

                // Update Confirm Popup UI
                document.getElementById('withdrawAmountHtg').textContent = Site.formatNumber(money);
                document.getElementById('withdrawFeePoints').textContent = '-' + Site.formatNumber(coins);
                
                // Get current balance from cache/DOM
                let currentBalance = 0;
                const balanceEl = document.getElementById('winCoinVal');
                if(balanceEl) {
                     // remove commas
                     currentBalance = parseFloat(balanceEl.textContent.replace(/,/g, '')) || 0;
                }
                
                // CHECK: Insufficient Balance
                if (currentBalance < coins) {
                    Site.showError('@Language.Insufficient');
                    return;
                }

                const newBalance = currentBalance - coins;
                document.getElementById('withdrawBalancePoints').textContent = Site.formatNumber(newBalance);

                // Show Confirm Popup, Hide Withdraw Popup
                closeWithdrawPopup();
                document.getElementById('confirmWithdrawPopup').style.display = 'flex';

            } else {
                Site.showError('Please select a withdraw amount'); 
            }
        }

        function closeConfirmWithdrawPopup() {
            document.getElementById('confirmWithdrawPopup').style.display = 'none';
        }

        function processWithdraw() {
            if (!selectedWithdrawConfig) return;
            
            // Call API to request OTP
            Site.showLoading();
            
            API.post('/Home/RequestWithdrawOtp', { configId: selectedWithdrawConfig.id }, function(response) {
                Site.hideLoading();
                if (response.errorCode === '0' || response.errorCode === 0) {
                     // Success - Show OTP Popup
                     closeConfirmWithdrawPopup();
                     // Clear inputs
                     const inputs = document.querySelectorAll('.otp-box');
                     inputs.forEach(i => i.value = '');
                     
                     document.getElementById('otpPopup').style.display = 'flex';
                     // Focus first input
                     if(inputs.length > 0) inputs[0].focus();
                     
                     // Optional: Store otpId if returned
                } else {
                     Site.showError(response.message || 'Request failed');
                }
            });
        }

        function closeOtpPopup() {
            document.getElementById('otpPopup').style.display = 'none';
        }

        function verifyOtp() {
            // Gather OTP
            let otp = '';
            const inputs = document.querySelectorAll('.otp-box');
            inputs.forEach(input => {
                otp += input.value;
            });
            
            if(!otp || otp.length < 6) {
                Site.showError('Please enter full OTP');
                return;
            }

            Site.showLoading();
            
            API.post('/Home/ConfirmWithdrawOtp', { otpCode: otp }, function(response) {
                Site.hideLoading();
                
                if (response.errorCode === '0' || response.errorCode === 0) {
                     closeOtpPopup();
                     let msg = response.message;
                     if (!msg || msg === 'EXCHANGE_REQUEST_SUCCESS') {
                        msg = '@Language.StatusSuccessful'; 
                     }
                     showExchangeSuccessPopup(msg);
                     
                     // Update balance
                     if(response.data) {
                         if(document.getElementById('betCoinVal') && response.data.betCoin !== undefined) 
                             document.getElementById('betCoinVal').textContent = Site.formatNumber(response.data.betCoin);
                         if(document.getElementById('winCoinVal') && response.data.winCoin !== undefined) {
                             const formattedWinCoin = Site.formatNumber(response.data.winCoin);
                             document.getElementById('winCoinVal').textContent = formattedWinCoin;
                             // Update value in withdraw popup as well
                             if(document.getElementById('withdrawPopupCoinValue')) {
                                 document.getElementById('withdrawPopupCoinValue').textContent = formattedWinCoin;
                             }
                         }
                     }
                } else {
                     Site.showError(response.message || 'Verification failed');
                }
            });
        }

        function handleBuyMore() {
            // Simply show the popup, data is pre-loaded via Razor
            document.getElementById('selectPackagePopup').style.display = 'flex';
        }
        
        function closePackagePopup() {
            document.getElementById('selectPackagePopup').style.display = 'none';
        }
        
        let selectedPackageCode = null;

        function handlePackageNext() {
            const selectedPackage = document.querySelector('input[name="package"]:checked');
            if (selectedPackage) {
                const packageCode = selectedPackage.value;
                const coins = parseFloat(selectedPackage.getAttribute('data-coin'));
                const price = parseFloat(selectedPackage.getAttribute('data-price'));
                
                selectedPackageCode = packageCode;

                // Update confirm popup with selected values
                document.getElementById('confirmCoinsAmount').textContent = Site.formatNumber(coins);
                document.getElementById('confirmPriceAmount').textContent = Site.formatNumber(price);
                
                // Hide select popup and show confirm popup
                closePackagePopup();
                document.getElementById('confirmBuyMorePopup').style.display = 'flex';
            } else {
                Site.showError('Please select a package'); // Use new popup
            }
        }
        
        function closeConfirmPopup() {
            document.getElementById('confirmBuyMorePopup').style.display = 'none';
        }
        
        function handleConfirmBuy() {
            if (!selectedPackageCode) return;
            
            API.post('/Home/BuyMore', { packageCode: selectedPackageCode }, function(response) {
                 if (response.errorCode === '0') {
                     Site.showSuccess('@Language.StatusSuccessful');
                     
                     // Update coins
                     if(response.data) {
                         if(document.getElementById('betCoinVal')) document.getElementById('betCoinVal').textContent = Site.formatNumber(response.data.betCoin);
                         if(document.getElementById('winCoinVal')) {
                             const formattedWinCoin = Site.formatNumber(response.data.winCoin);
                             document.getElementById('winCoinVal').textContent = formattedWinCoin;
                             if(document.getElementById('withdrawPopupCoinValue')) {
                                  document.getElementById('withdrawPopupCoinValue').textContent = formattedWinCoin;
                             }
                         }
                     }

                     closeConfirmPopup();
                     // No reload needed
                 } else {
                     Site.showError(response.message);
                 }
            });
        }
        
        // Close popup when clicking overlay
        document.getElementById('selectPackagePopup')?.addEventListener('click', function(e) {
            if (e.target === this) {
                closePackagePopup();
            }
        });
        
        document.getElementById('confirmBuyMorePopup')?.addEventListener('click', function(e) {
            if (e.target === this) {
                closeConfirmPopup();
            }
        });
        
        document.getElementById('registerPopup')?.addEventListener('click', function(e) {
            if (e.target === this) {
                closeRegisterPopup();
            }
        });
        
        document.getElementById('withdrawPopup')?.addEventListener('click', function(e) {
            if (e.target === this) {
                closeWithdrawPopup();
            }
        });

        document.getElementById('messagePopup')?.addEventListener('click', function(e) {
            if (e.target === this) {
                closeMessagePopup();
            }
        });

        document.getElementById('exchangeSuccessPopup')?.addEventListener('click', function(e) {
            if (e.target === this) {
                closeExchangeSuccessPopup();
            }
        });

        function handlePlay() {
            // TODO: Implement play logic
            // Site.showSuccess('Starting game...'); Use new popup example
            window.location.href = '/Home/Play';
        }
    </script>
}
