@extends('templates.' . site('template') . '.layouts.user')
@section('contents')
<!-- Load Tailwind + AdSense -->
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxxxxxxxxxx"
        crossorigin="anonymous"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Pass plan data to JavaScript -->
    <script>
        window.userPlan = @json($userPlan ?? null);
        window.planData = {
            miners: {{ $userPlan->miners ?? 1 }},
            speed: {{ $userPlan->speed ?? 50 }}, // Free plan: 50 MH/s
            speedUnit: '{{ "MH/s" }}',
            minReturnPerDay: {{ $userPlan->min_return_per_day ?? 0.00001000 }}, // Free plan: very small return
            maxReturnPerDay: {{ $userPlan->max_return_per_day ?? 0.00002000 }}, // Free plan: small return
            period: {{ $userPlan->period ?? 1 }}, // Plan period in hours
            maintenanceCost: {{ $userPlan->maintenance_cost ?? 0 }},
            title: '{{ $userPlan->title ?? "Free Plan" }}',
            isFree: {{ $userPlan ? 'false' : 'true' }},
            stakedAmount: {{ $userPlan->price ?? 0 }} // 0 for free plan
        };
        window.userBalance = {{ user()->coin_balance ?? 0 }};
        window.updateBalanceUrl = '{{ route("user.mining.update-balance") }}';
        window.checkPlanExpirationUrl = '{{ route("user.mining.check-plan-expiration") }}';
        window.csrfToken = '{{ csrf_token() }}';
    </script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    colors: {
                        'dark-purple': '#1a0e2e',
                        'purple-deep': '#2a1b3d',
                        'purple-medium': '#3d2a5a',
                        'purple-light': '#4a3567',
                        'cyan-glow': '#00ffff',
                        'purple-glow': '#8b5cf6',
                        'orange-glow': '#ff6b35'
                    },
                    animation: {
                        'spin-slow': 'spin 20s linear infinite',
                        'pulse-glow': 'pulse 2s ease-in-out infinite',
                        'rotate-border': 'rotateBorder 4s linear infinite',
                    },
                    keyframes: {
                        rotateBorder: {
                            '0%': { transform: 'rotate(0deg)' },
                            '100%': { transform: 'rotate(360deg)' }
                        }
                    }
                }
            }
        }
    </script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
     
        
        .circular-progress {
            transform: rotate(-90deg);
        }
        
        .progress-ring {
            transition: stroke-dasharray 0.5s ease-in-out;
        }
        
        .glow-effect {
            filter: drop-shadow(0 0 10px currentColor);
        }
        
       
        
        /* Mobile responsiveness */
        @media (max-width: 640px) {
            .central-meter {
                width: 250px !important;
                height: 250px !important;
            }
            
            .central-meter svg {
                width: 220px !important;
                height: 220px !important;
            }
            
            .hash-rate-text {
                font-size: 2rem !important;
            }
            
            .stats-grid {
                gap: 0.5rem !important;
            }
            
            .stats-card {
                padding: 0.5rem !important;
            }
            
            #adsense-container {
                margin: 1rem -1rem !important;
                padding: 1rem !important;
            }
            
            #adsense-box {
                width: 100% !important;
                max-width: 320px !important;
            }
            
            .adsbygoogle {
                width: 100% !important;
                max-width: 300px !important;
                height: 250px !important;
            }
        }
        
        @media (max-width: 480px) {
            .central-meter {
                width: 220px !important;
                height: 220px !important;
            }
            
            .central-meter svg {
                width: 190px !important;
                height: 190px !important;
            }
            
            .hash-rate-text {
                font-size: 1.8rem !important;
            }
            
            .adsbygoogle {
                width: 100% !important;
                max-width: 280px !important;
                height: 200px !important;
            }
        }
        
        /* Tablet responsiveness */
        @media (min-width: 641px) and (max-width: 1024px) {
            .central-meter {
                width: 320px !important;
                height: 320px !important;
            }
            
            .central-meter svg {
                width: 290px !important;
                height: 290px !important;
            }
            
            #adsense-container {
                max-width: 500px !important;
                margin: 0 auto !important;
            }
        }
        
        /* Removed animations for better performance */
        
        .theme-toggle {
            position: fixed;
            top: 1rem;
            right: 1rem;
            z-index: 50;
            background: rgba(139, 92, 246, 0.2);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(139, 92, 246, 0.3);
            border-radius: 50%;
            width: 48px;
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .theme-toggle:hover {
            background: rgba(139, 92, 246, 0.4);
            transform: scale(1.1);
        }
    </style>


<div class="transition-all duration-300 ease-in-out"
     :class="{
         'lg:ml-64': !isCollapsed,
         'lg:ml-20': isCollapsed
     }">
  <div class="min-h-screen m-6 lg:m-12" id="refreshPage">
        <!-- Header -->
        <div class="text-center pb-4 px-4">
            <h1 class="text-white text-2xl font-bold mb-2">{{ $userPlan->title ?? 'Free Mining Plan' }}</h1>
            <p class="text-gray-300 text-sm opacity-80">Personal Profits Analysis</p>
            <div class="mt-2">
                @if($userPlan)
                    <span class="bg-purple-600 text-white px-3 mb-2 py-1 rounded-full text-xs">
                        {{ $userPlan->miners }} Miners • {{ $userPlan->speed }} MH/s
                    </span>
                    <br></br>
                    
                    @if($userPlan->price > 0)
                        <span class="bg-green-600 text-white px-3 py-1 rounded-full text-xs ml-2">
                            ${{ number_format($userPlan->price, 2) }} Staked
                        </span>
                    @endif
                @else
                    <span class="bg-gray-600 text-white px-3 py-1 mb-2 rounded-full text-xs">
                        1 Miner • 50 MH/s • Free Plan
                    </span>
                    <br></br>
                    <span class="bg-orange-600 text-white px-3 py-1 rounded-full text-xs ml-2">
                        $0.00 Staked
                    </span>
                @endif
            </div>
            
            <!-- Account Balance Display -->
            <div class="mt-3 bg-gray-800/50 rounded-lg p-3 max-w-sm mx-auto">
                <div class="text-gray-400 text-xs mb-1">ACCOUNT BALANCE</div>
                <div class="text-green-400 text-lg font-bold" id="account-balance">
                    {{ number_format(user()->coin_balance ?? 0, 4) }} CBC
                </div>
                <div class="text-gray-400 text-xs">
                    ≈ $<span id="balance-usd">{{ number_format((user()->coin_balance ?? 0) * 0.895, 4) }}</span>
                </div>
            </div>
        </div>

            <!-- Main Content -->
            <div class="flex-1 flex flex-col items-center justify-center px-2 sm:px-4 pb-20">
                <!-- Central Hash Rate Meter -->
                <div class="relative mb-6 sm:mb-8 md:mb-12 central-meter w-80 h-80">
                    <!-- Outer rotating border -->
                    <div class="absolute inset-0 w-full h-full rounded-full">
                        <div class="w-full h-full rounded-full border-4 border-transparent bg-gradient-to-r from-cyan-glow via-purple-glow to-orange-glow bg-clip-border"></div>
                    </div>
                    
                    <!-- Inner circle container -->
                    <div class="relative w-full h-full rounded-full bg-dark-purple border-4 border-gray-600 flex items-center justify-center">
                        <!-- Progress circles -->
                        <svg class="absolute inset-4 w-72 h-72 circular-progress" viewBox="0 0 100 100">
                            <!-- Background circle -->
                            <circle cx="50" cy="50" r="45" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="2"/>
                            
                            <!-- Outer progress ring -->
                            <circle cx="50" cy="50" r="45" fill="none" stroke="url(#gradientOuter)" stroke-width="3" 
                                    stroke-linecap="round" stroke-dasharray="283" stroke-dashoffset="70" 
                                    class="progress-ring glow-effect" id="outer-progress"/>
                            
                            <!-- Middle progress ring -->
                            <circle cx="50" cy="50" r="38" fill="none" stroke="url(#gradientMiddle)" stroke-width="2" 
                                    stroke-linecap="round" stroke-dasharray="239" stroke-dashoffset="120" 
                                    class="progress-ring glow-effect" id="middle-progress"/>
                            
                            <!-- Inner progress ring -->
                            <circle cx="50" cy="50" r="32" fill="none" stroke="url(#gradientInner)" stroke-width="2" 
                                    stroke-linecap="round" stroke-dasharray="201" stroke-dashoffset="150" 
                                    class="progress-ring glow-effect" id="inner-progress"/>
                            
                            <!-- Gradient definitions -->
                            <defs>
                                <linearGradient id="gradientOuter" x1="0%" y1="0%" x2="100%" y2="0%">
                                    <stop offset="0%" style="stop-color:#00ffff"/>
                                    <stop offset="50%" style="stop-color:#8b5cf6"/>
                                    <stop offset="100%" style="stop-color:#ff6b35"/>
                                </linearGradient>
                                <linearGradient id="gradientMiddle" x1="0%" y1="0%" x2="100%" y2="0%">
                                    <stop offset="0%" style="stop-color:#8b5cf6"/>
                                    <stop offset="100%" style="stop-color:#00ffff"/>
                                </linearGradient>
                                <linearGradient id="gradientInner" x1="0%" y1="0%" x2="100%" y2="0%">
                                    <stop offset="0%" style="stop-color:#ff6b35"/>
                                    <stop offset="100%" style="stop-color:#8b5cf6"/>
                                </linearGradient>
                            </defs>
                        </svg>
                        
                        <!-- Center content -->
                        <div class="text-center z-10">
                            <div class="text-gray-400 text-xs mb-1 tracking-widest">HASH RATE</div>
                            <div class="text-white text-3xl sm:text-4xl font-bold mb-1 hash-rate-text" id="hash-rate-value">{{ $userPlan->speed ?? 50 }}</div>
                            <div class="text-gray-400 text-sm">{{ 'MH/S' }}</div>
                        </div>
                        
                        <!-- Mining symbol -->
                        <div class="absolute bottom-6 sm:bottom-8 left-1/2 transform -translate-x-1/2">
                            <div class="w-6 h-6 sm:w-8 sm:h-8 rounded-full bg-gradient-to-r from-cyan-400 to-blue-500 flex items-center justify-center glow-effect">
                                <i class="fas fa-pickaxe text-white text-xs sm:text-sm"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Total BTC Mined Section -->
                <div class="text-center mb-4 sm:mb-6 md:mb-8 px-4">
                    <h2 class="text-white text-base sm:text-lg font-semibold mb-4">Session CBC Mined</h2>
                    <div class="flex items-center justify-center space-x-3 mb-2">
                        <div class="w-6 h-6 sm:w-8 sm:h-8 rounded-full bg-gradient-to-r from-yellow-500 to-yellow-700 flex items-center justify-center">
                            <img src="https://i.ibb.co/BHGNxDC2/logo-cb-x.png" class="w-3 h-3 sm:w-3 sm:h-3" />
                        </div>
                        <span class="text-white text-lg sm:text-xl md:text-2xl font-bold" id="btc-mined">{{ number_format($userPlan->min_return_per_day ?? 0.00001000, 8) }}</span>
                    </div>
                    <div class="text-gray-400 text-xs sm:text-sm">
                        = $<span id="btc-usd-value">{{ number_format(($userPlan->min_return_per_day ?? 0.00001000) * 0.895, 6) }}</span>
                    </div>
                    @if(!$userPlan)
                        <div class="mt-2 text-yellow-400 text-xs">
                            <i class="fas fa-info-circle mr-1"></i>
                            Free plan: Limited earnings • Upgrade for higher returns
                        </div>
                    @endif
                </div>

                <!-- Stats Cards -->
                <div class="grid grid-cols-2 gap-2 sm:gap-3 md:gap-4 w-full max-w-xs sm:max-w-sm stats-grid">
                    <!-- Power Card -->
                    <div class="bg-purple-deep/50 backdrop-blur-sm rounded-lg p-2 sm:p-3 md:p-4 border border-purple-light/30 stats-card">
                        <div class="flex items-center space-x-2 sm:space-x-3">
                            <div class="w-5 h-5 sm:w-6 sm:h-6 md:w-8 md:h-8 rounded-full bg-cyan-500/20 flex items-center justify-center">
                                <i class="fas fa-bolt text-cyan-400 text-xs sm:text-sm"></i>
                            </div>
                            <div>
                                <div class="text-gray-400 text-xs">POWER</div>
                                <div class="text-white text-xs sm:text-sm font-semibold" id="power-value">{{ $userPlan->speed ?? 50 }} {{ 'MH/s' }}</div>
                            </div>
                        </div>
                    </div>

                    <!-- Miners Card -->
                    <div class="bg-purple-deep/50 backdrop-blur-sm rounded-lg p-2 sm:p-3 md:p-4 border border-purple-light/30 stats-card">
                        <div class="flex items-center space-x-2 sm:space-x-3">
                            <div class="w-5 h-5 sm:w-6 sm:h-6 md:w-8 md:h-8 rounded-full bg-purple-500/20 flex items-center justify-center">
                                <i class="fas fa-microchip text-purple-400 text-xs sm:text-sm"></i>
                            </div>
                            <div>
                                <div class="text-gray-400 text-xs">MINERS</div>
                                <div class="text-white text-xs sm:text-sm font-semibold" id="miners-value">{{ $userPlan->miners ?? 1 }} Miners</div>
                            </div>
                        </div>
                    </div>
                </div>                <!-- Subscribe Button -->
                <div class="mt-6 sm:mt-8 w-full max-w-md">
                    <!-- Activate Button -->
                    <button id="activate-btn" onclick="showAd()" class="w-full bg-orange-600 hover:bg-orange-700 px-4 py-2 sm:px-6 sm:py-3 mb-3 rounded-lg text-white font-semibold transition text-sm sm:text-base hidden">
                        Activate Mining
                    </button>
                    
                    <!-- Mining Status -->
                    <div id="mining-status" class="text-center mb-4">
                        <div class="text-green-400 font-semibold text-sm sm:text-base">
                            <i class="fas fa-play-circle mr-2"></i>Mining Active
                        </div>
                        <div class="text-gray-400 text-xs sm:text-sm" id="next-activation">
                            Next activation in: <span id="countdown-timer">--:--:--</span>
                        </div>
                    </div>
                    
                    <!-- Ad Container -->
                    <div id="adsense-container" class="mt-6 hidden">
                        <div class="bg-gray-900/90 backdrop-blur-sm rounded-lg p-4 md:p-6 border border-gray-600 max-w-md mx-auto">
                            <div class="text-center mb-4">
                                <h3 class="text-white font-semibold mb-2 text-sm md:text-base">Watch Ad to Continue Mining</h3>
                                <div class="text-gray-400 text-xs md:text-sm">
                                    Please watch the ad for <span id="ad-countdown">30</span> seconds
                                </div>
                                <div class="mt-2">
                                    <div class="w-full bg-gray-700 rounded-full h-2">
                                        <div id="ad-progress-bar" class="bg-orange-600 h-2 rounded-full transition-all duration-1000" style="width: 0%"></div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- AdSense Ad Slot -->
                            <div id="adsense-box" class="flex justify-center mb-4 w-full">
                                <ins class="adsbygoogle"
                                    style="display:block; width:100%; max-width:320px; height:250px;"
                                    data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
                                    data-ad-slot="1234567890"
                                    data-ad-format="rectangle"
                                    data-full-width-responsive="true"></ins>
                            </div>
                            
                            <!-- Ad Timer and Continue Button -->
                            <div class="text-center">
                                <button id="continue-mining-btn" onclick="startMining()" class="w-full bg-green-600 hover:bg-green-700 px-4 py-2 md:px-6 md:py-3 rounded-lg text-white font-semibold transition opacity-50 cursor-not-allowed text-sm md:text-base" disabled>
                                    Continue Mining (<span id="continue-countdown">30</span>s)
                                </button>
                            </div>
                        </div>
                    </div>
        
                    <a href="{{ route('user.plans') }}" class="inline-flex items-center justify-center space-x-2 bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white font-semibold py-2 px-4 sm:py-3 sm:px-6 rounded-lg transition-all duration-300 transform hover:scale-105 w-full text-sm sm:text-base">
                        <i class="fas fa-rocket"></i>
                        <span>{{ $userPlan ? 'Upgrade Plan' : 'Get Premium Plan' }}</span>
                    </a>
                    
                    @if(!$userPlan)
                        <div class="mt-3 text-center">
                            <p class="text-gray-400 text-xs">
                                <i class="fas fa-gift mr-1"></i>
                                Free plan: 1 hour sessions • Upgrade for longer mining periods
                            </p>
                        </div>
                    @endif
                </div>
            </div>

        <!-- Bottom Navigation -->
        
    </div>
     </div>
     
     <script>
    // Mining state management with plan data
    let isMiningActive = false;
    let nextActivationTime = null;
    let adCountdownTimer = null;
    let planCountdownTimer = null;
    let planExpirationTimer = null;
    let adStartTime = null;
    let adDuration = 30; // 30 seconds
    let planPeriodHours = window.planData.period; // Plan period in hours
    let planStartTime = null; // When the user first activated their current plan

    // Plan expiration checking based on frontend calculation
    function checkPlanExpiration() {
        if (window.planData.isFree) {
            return; // No expiration check needed for free plans
        }

        // Get when the user first started using this plan
        const savedPlanStartTime = localStorage.getItem('planStartTime');
        if (!savedPlanStartTime) {
            // If no plan start time is saved, set it now (for existing users)
            planStartTime = new Date();
            localStorage.setItem('planStartTime', planStartTime.toISOString());
        } else {
            planStartTime = new Date(savedPlanStartTime);
        }

        const currentTime = new Date();
        const planDurationMs = planPeriodHours * 60 * 60 * 1000; // Convert hours to milliseconds
        const planExpirationTime = new Date(planStartTime.getTime() + planDurationMs);

        if (currentTime >= planExpirationTime) {
            // Plan has expired, switch to free plan
            handlePlanExpiration();
        } else {
            // Schedule next check
            const timeUntilExpiration = planExpirationTime - currentTime;
            // Check again in 1 minute or when plan expires, whichever is sooner
            const nextCheckIn = Math.min(timeUntilExpiration, 60000);
            
            if (planExpirationTimer) {
                clearTimeout(planExpirationTimer);
            }
            
            planExpirationTimer = setTimeout(checkPlanExpiration, nextCheckIn);
        }
    }

    function handlePlanExpiration() {
        // Clear any existing timers
        if (planExpirationTimer) {
            clearTimeout(planExpirationTimer);
        }

        // Call server to update user plan_id to null
        fetch(window.checkPlanExpirationUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': window.csrfToken
            },
            body: JSON.stringify({
                action: 'expire_plan'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update plan data to free plan
                updateToFreePlan();
                
                // Show notification to user
                showPlanExpiredNotification();
                
                // Stop current mining session if active
                if (isMiningActive) {
                    showActivateButton();
                }
            }
        })
        .catch(error => {
            console.error('Error handling plan expiration:', error);
            // Fallback: still update to free plan locally
            updateToFreePlan();
            showPlanExpiredNotification();
        });
    }

    function updateToFreePlan() {
        // Update global plan data to free plan values
        window.planData = {
            miners: 1,
            speed: 50,
            speedUnit: 'MH/s',
            minReturnPerDay: 0.00001000,
            maxReturnPerDay: 0.00002000,
            period: 1,
            maintenanceCost: 0,
            title: 'Free Plan',
            isFree: true,
            stakedAmount: 0
        };
        
        window.userPlan = null;
        
        // Update plan period for future sessions
        planPeriodHours = 1;
        
        // Clear plan start time since we're now on free plan
        localStorage.removeItem('planStartTime');
        planStartTime = null;
        
        // Update UI elements
        updatePlanUIElements();
    }

    function initializePlanStartTime() {
        // Only set plan start time for premium plans
        if (!window.planData.isFree && !localStorage.getItem('planStartTime')) {
            planStartTime = new Date();
            localStorage.setItem('planStartTime', planStartTime.toISOString());
        }
    }

    function updatePlanUIElements() {
        // Update header title
        const headerTitle = document.querySelector('h1.text-white.text-2xl');
        if (headerTitle) {
            headerTitle.textContent = 'Free Mining Plan';
        }
        
        // Update plan badges
        const planBadge = document.querySelector('.bg-purple-600');
        if (planBadge) {
            planBadge.className = 'bg-gray-600 text-white px-3 mb-2 py-1 rounded-full text-xs';
            planBadge.innerHTML = '1 Miner • 50 MH/s • Free Plan';
        }
        
        // Update staked amount badge
        const stakedBadge = document.querySelector('.bg-green-600, .bg-orange-600');
        if (stakedBadge) {
            stakedBadge.className = 'bg-orange-600 text-white px-3 py-1 rounded-full text-xs ml-2';
            stakedBadge.textContent = '$0.00 Staked';
        }
        
        // Update upgrade button text
        const upgradeButton = document.querySelector('a[href*="plans"] span');
        if (upgradeButton) {
            upgradeButton.textContent = 'Get Premium Plan';
        }
        
        // Show free plan notice if not already visible
        const freeNotice = document.querySelector('.text-yellow-400');
        if (freeNotice) {
            freeNotice.classList.remove('hidden');
        }
        
        // Update current hash rate and power display
        currentHashRate = 50;
        currentMiners = 1;
        updateHashRate();
        updateMiners();
    }

    function showPlanExpiredNotification() {
        // Create a notification overlay
        const notification = document.createElement('div');
        notification.className = 'fixed top-0 left-0 w-full h-full bg-black bg-opacity-75 flex items-center justify-center z-50';
        notification.innerHTML = `
            <div class="bg-gray-800 rounded-lg p-6 max-w-sm mx-4 border border-gray-600">
                <div class="text-center">
                    <div class="w-16 h-16 mx-auto mb-4 bg-orange-500 rounded-full flex items-center justify-center">
                        <i class="fas fa-clock text-white text-2xl"></i>
                    </div>
                    <h3 class="text-white text-lg font-semibold mb-2">Plan Expired</h3>
                    <p class="text-gray-300 text-sm mb-4">
                        Your premium plan has expired. You've been switched to the free plan with limited features.
                    </p>
                    <div class="space-y-2">
                        <button onclick="this.parentElement.parentElement.parentElement.parentElement.remove()" 
                                class="w-full bg-gray-600 hover:bg-gray-700 text-white py-2 px-4 rounded-lg text-sm">
                            Continue with Free Plan
                        </button>
                        <a href="${document.querySelector('a[href*="plans"]').href}" 
                           class="block w-full bg-purple-600 hover:bg-purple-700 text-white py-2 px-4 rounded-lg text-sm text-center">
                            Upgrade Now
                        </a>
                    </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        // Auto-remove notification after 10 seconds
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 10000);
    }

    function showAd() {
        // Hide activate button and show ad container
        const activateBtn = document.getElementById('activate-btn');
        const adsenseContainer = document.getElementById('adsense-container');
        
        if (activateBtn) {
            activateBtn.classList.add('hidden');
        }
        if (adsenseContainer) {
            adsenseContainer.classList.remove('hidden');
        }
        
        // Set ad start time
        adStartTime = Date.now();
        localStorage.setItem('adStartTime', adStartTime.toString());
        
        // Load AdSense ad
        try {
            (adsbygoogle = window.adsbygoogle || []).push({});
        } catch (e) {
            console.error("AdSense error:", e);
        }
        
        // Start 30-second countdown
        startAdCountdown();
    }

    function startAdCountdown() {
        let remainingTime = adDuration;
        
        // Check if there's a saved ad start time
        const savedAdStartTime = localStorage.getItem('adStartTime');
        if (savedAdStartTime) {
            const elapsed = Math.floor((Date.now() - parseInt(savedAdStartTime)) / 1000);
            remainingTime = Math.max(0, adDuration - elapsed);
        }
        
        const countdownElement = document.getElementById('continue-countdown');
        const adCountdownElement = document.getElementById('ad-countdown');
        const continueButton = document.getElementById('continue-mining-btn');
        const progressBar = document.getElementById('ad-progress-bar');
        
        function updateCountdown() {
            const savedAdStartTime = localStorage.getItem('adStartTime');
            if (!savedAdStartTime) return;
            
            const elapsed = Math.floor((Date.now() - parseInt(savedAdStartTime)) / 1000);
            const remaining = Math.max(0, adDuration - elapsed);
            
            if (countdownElement) {
                countdownElement.textContent = remaining;
            }
            if (adCountdownElement) {
                adCountdownElement.textContent = remaining;
            }
            
            // Update progress bar
            const progress = ((adDuration - remaining) / adDuration) * 100;
            if (progressBar) {
                progressBar.style.width = `${progress}%`;
            }
            
            if (remaining <= 0) {
                clearInterval(adCountdownTimer);
                // Enable continue button
                if (continueButton) {
                    continueButton.disabled = false;
                    continueButton.classList.remove('opacity-50', 'cursor-not-allowed');
                    continueButton.classList.add('hover:bg-green-700');
                    continueButton.innerHTML = 'Continue Mining';
                }
                if (progressBar) {
                    progressBar.style.width = '100%';
                }
                
                // Clear ad start time
                localStorage.removeItem('adStartTime');
            }
        }
        
        // Update immediately and then every second
        updateCountdown();
        adCountdownTimer = setInterval(updateCountdown, 1000);
    }

    function startMining() {
        // Hide ad container
        const adsenseContainer = document.getElementById('adsense-container');
        if (adsenseContainer) {
            adsenseContainer.classList.add('hidden');
        }
        
        // Clear ad timer and start time
        if (adCountdownTimer) {
            clearInterval(adCountdownTimer);
        }
        localStorage.removeItem('adStartTime');
        
        // Activate mining
        isMiningActive = true;
        const miningStatus = document.getElementById('mining-status');
        if (miningStatus) {
            miningStatus.classList.remove('hidden');
        }
        
        // Set next activation time based on plan period (in hours)
        nextActivationTime = new Date(Date.now() + (planPeriodHours * 60 * 60 * 1000));
        localStorage.setItem('nextActivationTime', nextActivationTime.toISOString());
        localStorage.setItem('isMiningActive', 'true');
        
        // Set session start time if not already set
        if (!localStorage.getItem('sessionStartTime')) {
            localStorage.setItem('sessionStartTime', Date.now().toString());
        }
        
        // Start plan period countdown
        startPlanCountdown();
        
        // Start mining updates
        updateHashRate();
        updateBTCMined();
        updateMiners();
        updateProgressRingsBasedOnHashRate();
        startMiningUpdates();
        
        // Reset ad countdown elements
        resetAdCountdown();
    }

    function resetAdCountdown() {
        const continueButton = document.getElementById('continue-mining-btn');
        const progressBar = document.getElementById('ad-progress-bar');
        const continueCountdown = document.getElementById('continue-countdown');
        const adCountdown = document.getElementById('ad-countdown');
        
        if (continueButton) {
            continueButton.disabled = true;
            continueButton.classList.add('opacity-50', 'cursor-not-allowed');
            continueButton.classList.remove('hover:bg-green-700');
        }
        if (continueCountdown) {
            continueCountdown.textContent = '30';
        }
        if (adCountdown) {
            adCountdown.textContent = '30';
        }
        if (progressBar) {
            progressBar.style.width = '0%';
        }
    }

    function startPlanCountdown() {
        function updateCountdown() {
            if (!nextActivationTime) return;
            
            const now = new Date();
            const timeLeft = nextActivationTime - now;
            
            if (timeLeft <= 0) {
                // Plan period expired, show activate button again
                showActivateButton();
                return;
            }
            
            // Format time remaining
            const hours = Math.floor(timeLeft / (1000 * 60 * 60));
            const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);
            
            const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            const countdownElement = document.getElementById('countdown-timer');
            if (countdownElement) {
                countdownElement.textContent = timeString;
            }
        }
        
        // Update immediately and then every second
        updateCountdown();
        planCountdownTimer = setInterval(updateCountdown, 1000);
    }

    // Add plan expiration display in header (optional - shows overall plan time remaining)
    function displayPlanTimeRemaining() {
        if (window.planData.isFree || !planStartTime) return;

        const currentTime = new Date();
        const planDurationMs = planPeriodHours * 60 * 60 * 1000;
        const planExpirationTime = new Date(planStartTime.getTime() + planDurationMs);
        const timeLeft = planExpirationTime - currentTime;

        if (timeLeft <= 0) {
            // Plan has expired
            return;
        }

        // Calculate days, hours, minutes remaining
        const days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
        const hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));

        let timeString = '';
        if (days > 0) {
            timeString = `${days}d ${hours}h ${minutes}m`;
        } else if (hours > 0) {
            timeString = `${hours}h ${minutes}m`;
        } else {
            timeString = `${minutes}m`;
        }

        // You can display this in the UI if desired
        console.log(`Plan expires in: ${timeString}`);
    }

    function showActivateButton() {
        // Clear timers
        if (planCountdownTimer) {
            clearInterval(planCountdownTimer);
        }
        if (adCountdownTimer) {
            clearInterval(adCountdownTimer);
        }
        
        // Reset mining state
        isMiningActive = false;
        nextActivationTime = null;
        
        // Clear session progress when session expires
        clearSessionProgress();
        
        // Update localStorage
        localStorage.removeItem('nextActivationTime');
        localStorage.removeItem('adStartTime');
        localStorage.setItem('isMiningActive', 'false');
        
        // Update UI
        const miningStatus = document.getElementById('mining-status');
        const activateBtn = document.getElementById('activate-btn');
        const adsenseContainer = document.getElementById('adsense-container');
        
        if (miningStatus) {
            miningStatus.classList.add('hidden');
        }
        if (activateBtn) {
            activateBtn.classList.remove('hidden');
        }
        if (adsenseContainer) {
            adsenseContainer.classList.add('hidden');
        }
        
        // Reset ad countdown
        resetAdCountdown();
        
        // Reset the display to show 0
        const btcMinedElement = document.getElementById('btc-mined');
        const btcUsdElement = document.getElementById('btc-usd-value');
        
        if (btcMinedElement) {
            btcMinedElement.textContent = '0.00000000';
        }
        if (btcUsdElement) {
            btcUsdElement.textContent = '0.000000';
        }
    }

    function initializeMiningState() {
        // Check for active ad countdown first
        const savedAdStartTime = localStorage.getItem('adStartTime');
        if (savedAdStartTime) {
            const elapsed = Math.floor((Date.now() - parseInt(savedAdStartTime)) / 1000);
            if (elapsed < adDuration) {
                // Ad is still active, show ad container and continue countdown
                const adsenseContainer = document.getElementById('adsense-container');
                if (adsenseContainer) {
                    adsenseContainer.classList.remove('hidden');
                }
                startAdCountdown();
                return;
            } else {
                // Ad expired, clear it
                localStorage.removeItem('adStartTime');
            }
        }
        
        // Check if mining was previously active
        const savedMiningState = localStorage.getItem('isMiningActive');
        const savedActivationTime = localStorage.getItem('nextActivationTime');
        
        if (savedMiningState === 'true' && savedActivationTime) {
            nextActivationTime = new Date(savedActivationTime);
            const now = new Date();
            
            if (nextActivationTime > now) {
                // Mining is still active, load session progress
                isMiningActive = true;
                loadSessionProgress();
                const miningStatus = document.getElementById('mining-status');
                if (miningStatus) {
                    miningStatus.classList.remove('hidden');
                }
                startPlanCountdown();
            } else {
                // Plan period expired, show activate button
                showActivateButton();
            }
        } else {
            // First time or expired, show activate button
            showActivateButton();
        }
    }

    // Initialize on page load
    window.addEventListener('DOMContentLoaded', function() {
        initializeMiningState();
        
        // Initialize plan start time for premium plans
        initializePlanStartTime();
        
        // Start plan expiration checking only for premium plans
        if (!window.planData.isFree) {
            checkPlanExpiration();
        }
    });
</script>

    <!-- JavaScript for functionality -->
    <script>
        // Global variables for hash rate management based on plan data
        let currentHashRate = window.planData.speed; // Start with plan speed
        let hashRateDirection = 1; // 1 for up, -1 for down
        let animationFrame = 0;
        let currentMiners = window.planData.miners; // Start with plan miners
        let totalMined = 0; // Will be loaded from localStorage or start at 0

        // Theme management
        function initializeTheme() {
            const savedTheme = localStorage.getItem('theme') || 'dark';
            if (savedTheme === 'light') {
                document.body.classList.add('light-mode');
            }
        }

        // Toggle theme function
        function toggleTheme() {
            document.body.classList.toggle('light-mode');
            const isLight = document.body.classList.contains('light-mode');
            localStorage.setItem('theme', isLight ? 'light' : 'dark');
        }

        // Simulate realistic hash rate fluctuations based on plan
        function updateHashRate() {
            const planSpeed = window.planData.speed;
            const maxFluctuation = planSpeed * 0.15; // 15% fluctuation
            
            // Random fluctuation
            const fluctuation = (Math.random() - 0.5) * maxFluctuation;
            const changeRate = Math.random() * (planSpeed * 0.05) + (planSpeed * 0.01); // 1-5% change
            
            // Apply directional change
            if (Math.random() < 0.3) { // 30% chance to change direction
                hashRateDirection *= -1;
            }
            
            currentHashRate += (hashRateDirection * changeRate) + fluctuation;
            
            // Keep within bounds (±20% of plan speed)
            const minSpeed = planSpeed * 0.8;
            const maxSpeed = planSpeed * 1.2;
            currentHashRate = Math.max(minSpeed, Math.min(maxSpeed, currentHashRate));
            
            // Update display
            const displayRate = Math.round(currentHashRate);
            const hashRateElement = document.getElementById('hash-rate-value');
            const powerElement = document.getElementById('power-value');
            
            if (hashRateElement) {
                hashRateElement.textContent = displayRate;
            }
            if (powerElement) {
                powerElement.textContent = `${displayRate} ${window.planData.speedUnit}`;
            }
            
            // Update progress ring speeds based on hash rate
            updateProgressRingsBasedOnHashRate();
        }

        // Update miners count based on plan (always show exact plan miners)
        function updateMiners() {
            const planMiners = window.planData.miners;
            currentMiners = planMiners; // Always use exact plan miners count
            
            const minersElement = document.getElementById('miners-value');
            if (minersElement) {
                minersElement.textContent = `${currentMiners} Miners`;
            }
        }

        function updateBTCMined() {
            // Calculate mining rate based on plan returns and current performance
            const minReturn = window.planData.minReturnPerDay;
            const maxReturn = window.planData.maxReturnPerDay;
            const maintenanceCost = window.planData.maintenanceCost;
            
            // Performance factor based on current hash rate vs plan speed
            const performanceFactor = currentHashRate / window.planData.speed;
            
            // Random increment within plan's return range
            const returnRange = maxReturn - minReturn;
            const randomFactor = Math.random();
            const baseIncrement = minReturn + (returnRange * randomFactor);
            
            // Apply performance factor and miners count
            const minersFactor = currentMiners / window.planData.miners;
            const increment = (baseIncrement * performanceFactor * minersFactor) / (24 * 60); // Per minute rate
            
            // Update total mined
            totalMined += increment;
            
            // Subtract maintenance cost proportionally
            const maintenancePerMinute = maintenanceCost / (24 * 60);
            totalMined = Math.max(0, totalMined - maintenancePerMinute);
            
            // Save session progress to localStorage
            saveSessionProgress();
            
            // Calculate USD value (approximate rate)
            const btcPrice = 0.895; // This should be fetched from API in real implementation
            const usdValue = (totalMined * btcPrice).toFixed(6);
            
            const btcMinedElement = document.getElementById('btc-mined');
            const btcUsdElement = document.getElementById('btc-usd-value');
            
            if (btcMinedElement) {
                btcMinedElement.textContent = totalMined.toFixed(8);
            }
            if (btcUsdElement) {
                btcUsdElement.textContent = usdValue;
            }
            
            // Update account balance every 10 mining updates (roughly every 10 seconds)
            updateBalanceCounter++;
            if (updateBalanceCounter >= 10) {
                updateAccountBalance(increment * 10); // Add the last 10 increments to balance
                updateBalanceCounter = 0;
            }
        }

        // New variable to track balance updates
        let updateBalanceCounter = 0;
        let currentAccountBalance = window.userBalance;

        // Function to save session mining progress
        function saveSessionProgress() {
            if (isMiningActive && nextActivationTime) {
                const sessionData = {
                    totalMined: totalMined,
                    sessionStartTime: localStorage.getItem('sessionStartTime') || Date.now(),
                    nextActivationTime: nextActivationTime.toISOString()
                };
                localStorage.setItem('sessionProgress', JSON.stringify(sessionData));
            }
        }

        // Function to load session mining progress
        function loadSessionProgress() {
            const savedProgress = localStorage.getItem('sessionProgress');
            if (savedProgress) {
                try {
                    const sessionData = JSON.parse(savedProgress);
                    const savedActivationTime = localStorage.getItem('nextActivationTime');
                    
                    // Only restore if the session is still active
                    if (savedActivationTime && new Date(savedActivationTime) > new Date()) {
                        totalMined = sessionData.totalMined || 0;
                        
                        // Update display immediately
                        const btcPrice = 0.895;
                        const usdValue = (totalMined * btcPrice).toFixed(6);
                        
                        const btcMinedElement = document.getElementById('btc-mined');
                        const btcUsdElement = document.getElementById('btc-usd-value');
                        
                        if (btcMinedElement) {
                            btcMinedElement.textContent = totalMined.toFixed(8);
                        }
                        if (btcUsdElement) {
                            btcUsdElement.textContent = usdValue;
                        }
                    } else {
                        // Session expired, clear progress
                        clearSessionProgress();
                    }
                } catch (e) {
                    console.error('Error loading session progress:', e);
                    clearSessionProgress();
                }
            }
        }

        // Function to clear session progress
        function clearSessionProgress() {
            localStorage.removeItem('sessionProgress');
            localStorage.removeItem('sessionStartTime');
            totalMined = 0;
        }

        // Function to update account balance in database and UI
        function updateAccountBalance(earnings) {
            if (earnings <= 0) return;
            
            // Update local balance
            currentAccountBalance += earnings;
            
            // Update UI
            const accountBalanceElement = document.getElementById('account-balance');
            const balanceUsdElement = document.getElementById('balance-usd');
            
            if (accountBalanceElement) {
                accountBalanceElement.textContent = currentAccountBalance.toFixed(8) + ' CBC';
            }
            if (balanceUsdElement) {
                balanceUsdElement.textContent = (currentAccountBalance * 0.895).toFixed(3);
            }
            
            // Send to server
            fetch(window.updateBalanceUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': window.csrfToken
                },
                body: JSON.stringify({
                    earnings: earnings
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Update with server response for accuracy
                    currentAccountBalance = data.new_balance;
                    const accountBalanceElement = document.getElementById('account-balance');
                    const balanceUsdElement = document.getElementById('balance-usd');
                    
                    if (accountBalanceElement) {
                        accountBalanceElement.textContent = currentAccountBalance.toFixed(8) + ' CBC';
                    }
                    if (balanceUsdElement) {
                        balanceUsdElement.textContent = (currentAccountBalance * 0.895).toFixed(3);
                    }
                }
            })
            .catch(error => {
                console.error('Error updating balance:', error);
            });
        }

        function updateProgressRingsBasedOnHashRate() {
            // Progress ring speeds based on current hash rate
            const baseSpeed = currentHashRate / 10; // Base speed factor
            const outerSpeed = baseSpeed * 1.5;
            const middleSpeed = baseSpeed * 1.2;
            const innerSpeed = baseSpeed * 0.8;
            
            animationFrame++;
            
            const outerProgress = (animationFrame * outerSpeed / 100) % 360;
            const middleProgress = (animationFrame * middleSpeed / 100) % 360;
            const innerProgress = (animationFrame * innerSpeed / 100) % 360;
            
            const outerCircumference = 283;
            const middleCircumference = 239;
            const innerCircumference = 201;
            
            // Calculate stroke-dashoffset for each ring
            const outerOffset = outerCircumference - (outerProgress / 360 * outerCircumference);
            const middleOffset = middleCircumference - (middleProgress / 360 * middleCircumference);
            const innerOffset = innerCircumference - (innerProgress / 360 * innerCircumference);
            
            const outerProgressElement = document.getElementById('outer-progress');
            const middleProgressElement = document.getElementById('middle-progress');
            const innerProgressElement = document.getElementById('inner-progress');
            
            if (outerProgressElement) {
                outerProgressElement.style.strokeDashoffset = outerOffset;
            }
            if (middleProgressElement) {
                middleProgressElement.style.strokeDashoffset = middleOffset;
            }
            if (innerProgressElement) {
                innerProgressElement.style.strokeDashoffset = innerOffset;
            }
        }

        // Update functions at different intervals (only when mining is active)
        function startMiningUpdates() {
            if (isMiningActive) {
                setInterval(() => {
                    if (isMiningActive) updateHashRate();
                }, 2000);
                
                setInterval(() => {
                    if (isMiningActive) updateBTCMined();
                }, 1000); // More frequent updates for earnings
                
                setInterval(() => {
                    if (isMiningActive) updateMiners();
                }, 5000);
                
                setInterval(() => {
                    if (isMiningActive) updateProgressRingsBasedOnHashRate();
                }, 50);
            }
        }

        // Initialize everything
        window.addEventListener('DOMContentLoaded', function() {
            initializeTheme();
            initializeMiningState();
            
            // Initialize plan start time for premium plans
            initializePlanStartTime();
            
            // Start plan expiration checking only for premium plans
            if (!window.planData.isFree) {
                checkPlanExpiration();
            }
            
            // Start mining updates if mining is active
            setTimeout(() => {
                if (isMiningActive) {
                    updateHashRate();
                    updateBTCMined();
                    updateMiners();
                    updateProgressRingsBasedOnHashRate();
                    startMiningUpdates();
                }
            }, 500);
        });

        // Add touch feedback for mobile
        document.querySelectorAll('.bottom-nav-item').forEach(item => {
            item.addEventListener('touchstart', function() {
                this.style.transform = 'scale(0.95)';
            });
            item.addEventListener('touchend', function() {
                this.style.transform = 'scale(1)';
            });
        });
    </script>
@endsection
