
@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-2451537563071235"
        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 }},
        speedUnit: '{{ "MH/s" }}',
        minReturnPerDay: {{ $userPlan->min_return_per_day ?? 0.53500000 }},
        maxReturnPerDay: {{ $userPlan->max_return_per_day ?? 1.53500000 }},
        period: {{ $userPlan->period ?? 1 }},
        maintenanceCost: {{ $userPlan->maintenance_cost ?? 0 }},
        title: '{{ $userPlan->title ?? "Free Plan" }}',
        isFree: {{ $userPlan ? 'false' : 'true' }},
        stakedAmount: {{ user()->staked ?? 0 }}
    };
    window.userBalance = {{ user()->coin_balance ?? 0 }};
    window.updateBalanceUrl = '{{ route("user.mining.update-balance") }}';
    window.checkPlanExpirationUrl = '{{ route("user.mining.check-plan-expiration") }}';
    window.startMiningUrl = '{{ route("user.mining.start") }}';
    window.miningStatusUrl = '{{ route("user.mining.status") }}';
    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',
                    'float': 'float 6s ease-in-out infinite',
                    'glow': 'glow 2s ease-in-out infinite alternate'
                },
                keyframes: {
                    rotateBorder: {
                        '0%': { transform: 'rotate(0deg)' },
                        '100%': { transform: 'rotate(360deg)' }
                    },
                    float: {
                        '0%, 100%': { transform: 'translateY(0px)' },
                        '50%': { transform: 'translateY(-10px)' }
                    },
                    glow: {
                        '0%': { boxShadow: '0 0 5px currentColor' },
                        '100%': { boxShadow: '0 0 20px currentColor' }
                    }
                }
            }
        }
    }
</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);
    }
    
    .mining-active-glow {
        animation: glow 2s ease-in-out infinite alternate;
    }
    
    .floating-particles::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: radial-gradient(circle at 20% 20%, rgba(0, 255, 255, 0.1) 0%, transparent 50%),
                    radial-gradient(circle at 80% 80%, rgba(139, 92, 246, 0.1) 0%, transparent 50%),
                    radial-gradient(circle at 40% 60%, rgba(255, 107, 53, 0.1) 0%, transparent 50%);
        animation: float 6s ease-in-out infinite;
        pointer-events: none;
    }
    
    .status-indicator {
        position: relative;
        display: inline-block;
    }
    
    .status-indicator::before {
        content: '';
        position: absolute;
        top: -2px;
        right: -2px;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #10b981;
        box-shadow: 0 0 10px #10b981;
        animation: pulse 2s infinite;
    }
    
    .mining-stats-card {
        background: linear-gradient(135deg, rgba(139, 92, 246, 0.1) 0%, rgba(0, 255, 255, 0.05) 100%);
        border: 1px solid rgba(139, 92, 246, 0.3);
        backdrop-filter: blur(10px);
        transition: all 0.3s ease;
    }
    
    .mining-stats-card:hover {
        border-color: rgba(139, 92, 246, 0.5);
        box-shadow: 0 8px 32px rgba(139, 92, 246, 0.2);
    }
    
    .balance-card {
        background: linear-gradient(135deg, rgba(16, 185, 129, 0.1) 0%, rgba(6, 182, 212, 0.1) 100%);
        border: 1px solid rgba(16, 185, 129, 0.3);
        backdrop-filter: blur(10px);
    }
    
    .progress-text {
        text-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;
        }
    }
    
    .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);
    }
    
    .notification-overlay {
        backdrop-filter: blur(10px);
        background: rgba(0, 0, 0, 0.8);
    }
    
    .notification-card {
        background: linear-gradient(135deg, rgba(31, 41, 55, 0.95) 0%, rgba(17, 24, 39, 0.95) 100%);
        border: 1px solid rgba(139, 92, 246, 0.3);
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
    }
    
    .sync-indicator {
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        z-index: 1000;
        background: rgba(139, 92, 246, 0.9);
        color: white;
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 12px;
        opacity: 0;
        transition: opacity 0.3s ease;
    }
    
    .sync-indicator.show {
        opacity: 1;
    }
</style>

<div class="transition-all duration-300 ease-in-out"
     :class="{
         'lg:ml-64': !isCollapsed,
         'lg:ml-20': isCollapsed
     }">
    
    <!-- Sync Indicator -->
    <div id="sync-indicator" class="sync-indicator">
        <i class="fas fa-sync-alt fa-spin mr-2"></i>
        Syncing with server...
    </div>
    
    <div class="min-h-screen m-6 lg:m-12 floating-particles" id="refreshPage">
        <!-- Header -->
        <div class="text-center pb-4 px-4">
            <div class="mb-4">
                <h1 class="text-white text-2xl md:text-3xl font-bold mb-2 progress-text">
                    {{ $userPlan->title ?? 'Free Mining Plan' }}
                </h1>
                <p class="text-gray-300 text-sm opacity-80">Personal Profits Analysis</p>
                
                <!-- Server Status Indicator -->
                <div id="server-status" class="mt-2 text-xs">
                    <span class="status-indicator text-green-400">
                        <i class="fas fa-circle mr-1"></i>Connected to Server
                    </span>
                </div>
            </div>
            
            <div class="mt-2">
                @if($userPlan)
                    <span class="bg-purple-600 text-white px-3 mb-2 py-1 rounded-full text-xs mining-active-glow">
                        {{ $userPlan->miners }} Miners • {{ $userPlan->speed }} MH/s
                    </span>
                    <br/>
                    
                    @if($userPlan->price > 0)
                        <span class="bg-green-600 text-white px-3 py-1 rounded-full text-xs ml-2">
                            ${{ number_format(user()->staked, 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/>
                    <span class="bg-orange-600 text-white px-3 py-1 rounded-full text-xs ml-2">
                        ${{ number_format(user()->staked, 2) }} Staked
                    </span>
                @endif
            </div>
            
            <!-- Account Balance Display -->
            <div class="mt-4 balance-card rounded-lg p-4 max-w-sm mx-auto">
                <div class="text-gray-400 text-xs mb-1 uppercase tracking-wide">Account Balance</div>
                <div class="text-green-400 text-xl md:text-2xl font-bold progress-text" id="account-balance">
                    {{ number_format(user()->coin_balance ?? 0, 8) }} CBC
                </div>
                <div class="text-gray-400 text-sm">
                    
                    ≈ $<span id="balance-usd">{{ number_format((user()->coin_balance ?? 0) * 2.3186, 6) }}</span>
                </div>
                <div class="text-xs text-gray-500 mt-1">
                    Last Updated: <span id="balance-last-updated">{{ now()->format('H:i:s') }}</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 animate-rotate-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 progress-text" id="hash-rate-value">{{ $userPlan->speed ?? 50 }}</div>
                        <div class="text-gray-400 text-sm">MH/S</div>
                        <div class="text-xs text-gray-500 mt-1">
                            <span id="hash-rate-status">Initializing...</span>
                        </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 animate-float">
                            <i class="fas fa-pickaxe text-white text-xs sm:text-sm"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Mining Progress 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 progress-text">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 animate-float">
                        <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 progress-text" id="btc-mined">0.00000000</span>
                </div>
                <div class="text-gray-400 text-xs sm:text-sm">
                    = $<span id="btc-usd-value">0.000000</span>
                </div>
                
                <!-- Mining Rate Display -->
                <div class="mt-2 text-xs text-gray-500">
                    <div id="mining-rate-display" class="hidden">
                        Rate: <span id="mining-rate">0.00000000</span> CBC/min
                    </div>
                    <div id="session-duration" class="hidden">
                        Session: <span id="session-time">00:00:00</span>
                    </div>
                </div>
                
                <div class="mt-2 text-yellow-400 text-xs">
                        <i class="fas fa-info-circle mr-1"></i>
                        After activation kindly wait for atleast 5 minutes to see increase in mined balance!
                    </div>
                
                @if(!$userPlan)
                    <div class="mt-2 text-red-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="mining-stats-card rounded-lg p-2 sm:p-3 md:p-4 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 glow-effect"></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 class="text-xs text-gray-500" id="power-efficiency">Efficiency: 98%</div>
                        </div>
                    </div>
                </div>

                <!-- Miners Card -->
                <div class="mining-stats-card rounded-lg p-2 sm:p-3 md:p-4 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 glow-effect"></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 class="text-xs text-gray-500" id="miners-status">Active</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Mining Controls -->
            <div class="mt-6 sm:mt-8 w-full max-w-md">
                <!-- Activate Button -->
                <button id="activate-btn" onclick="showAd()" 
                        class="w-full bg-gradient-to-r from-orange-500 to-orange-600 hover:from-orange-600 hover:to-orange-700 px-4 py-2 sm:px-6 sm:py-3 mb-3 rounded-lg text-white font-semibold transition-all duration-300 text-sm sm:text-base transform hover:scale-105 hidden">
                    <i class="fas fa-play mr-2"></i>
                    Activate Mining
                </button>
                
                <!-- Mining Status -->
                <div id="mining-status" class="text-center mb-4 hidden">
                    <div class="mining-stats-card rounded-lg p-4 mb-3">
                        <div class="text-green-400 font-semibold text-sm sm:text-base mb-2">
                            <i class="fas fa-play-circle mr-2 animate-pulse"></i>Mining Active
                        </div>
                        <div class="text-gray-400 text-xs sm:text-sm" id="next-activation">
                            Session expires in: <span id="countdown-timer" class="text-white font-mono">--:--:--</span>
                        </div>
                        <div class="mt-2 text-xs text-gray-500">
                            <div>Last Server Sync: <span id="last-sync-time">{{ now()->format('H:i:s') }}</span></div>
                        </div>
                    </div>
                </div>
                
                <!-- Ad Container -->
                <div id="adsense-container" class="mt-6 hidden">
                    <div class="notification-card rounded-lg p-4 md:p-6 max-w-md mx-auto">
                        <div class="text-center mb-4">
                            <div class="w-16 h-16 mx-auto mb-4 bg-gradient-to-r from-orange-500 to-orange-600 rounded-full flex items-center justify-center">
                                <i class="fas fa-play text-white text-2xl"></i>
                            </div>
                            <h3 class="text-white font-semibold mb-2 text-sm md:text-base">Watch Ad to Start Mining</h3>
                            <div class="text-gray-400 text-xs md:text-sm">
                                Please watch the ad for <span id="ad-countdown" class="text-orange-400 font-semibold">30</span> seconds
                            </div>
                            <div class="mt-3">
                                <div class="w-full bg-gray-700 rounded-full h-2">
                                    <div id="ad-progress-bar" class="bg-gradient-to-r from-orange-500 to-orange-600 h-2 rounded-full transition-all duration-1000" style="width: 0%"></div>
                                </div>
                                <div class="text-xs text-gray-500 mt-1">
                                    Progress: <span id="ad-progress-percent">0</span>%
                                </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-2451537563071235"-->
                        <!--        data-ad-slot="1234567890"-->
                        <!--        data-ad-format="rectangle"-->
                        <!--        data-full-width-responsive="true"></ins>-->
                        <!--</div>-->
                        <script async="async" data-cfasync="false" src="//pl27256198.profitableratecpm.com/66282c20c4bee2ad59deb6c8360c326d/invoke.js " ></script>
                        
                        <div style="border-radius: 20px" id="container-66282c20c4bee2ad59deb6c8360c326d"></div>
                        
                        
                        
                        <!-- Ad Timer and Continue Button -->
                        <div class="text-center">
                            <button id="continue-mining-btn" onclick="startMining()" 
                                    class="w-full bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 px-4 py-2 md:px-6 md:py-3 rounded-lg text-white font-semibold transition-all duration-300 opacity-50 cursor-not-allowed text-sm md:text-base" disabled>
                                <i class="fas fa-hourglass-half mr-2"></i>
                                Continue Mining (<span id="continue-countdown">30</span>s)
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Upgrade Button -->
                <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>
    </div>
</div>

<script>
// Global Variables
let isMiningActive = false;
let nextActivationTime = null;
let adCountdownTimer = null;
let planCountdownTimer = null;
let serverSyncInterval = null;
let miningUpdateIntervals = [];
let adStartTime = null;
let adDuration = 30;
let planPeriodHours = window.planData.period;
let totalMined = 0;
let currentAccountBalance = window.userBalance;
let sessionStartTime = null;
let sessionDurationTimer = null;
let lastServerSyncTime = new Date();
let miningRatePerMinute = 0;

// Mining animation variables
let currentHashRate = window.planData.speed;
let hashRateDirection = 1;
let animationFrame = 0;
let currentMiners = window.planData.miners;

// Update frequency - sync every 5 seconds for real-time updates
const SYNC_INTERVAL = 5000; // 5 seconds
const HASH_RATE_UPDATE_INTERVAL = 1000; // 1 second for hash rate fluctuations

// Utility Functions
function formatTime(seconds) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

function formatTimeRemaining(seconds) {
    if (seconds <= 0) return '00:00:00';
    return formatTime(Math.floor(seconds));
}

function showSyncIndicator() {
    const indicator = document.getElementById('sync-indicator');
    if (indicator) {
        indicator.classList.add('show');
        setTimeout(() => {
            indicator.classList.remove('show');
        }, 1500);
    }
}

function updateServerStatus(connected = true) {
    const statusElement = document.getElementById('server-status');
    if (statusElement) {
        if (connected) {
            statusElement.innerHTML = '<span class="status-indicator text-green-400"><i class="fas fa-circle mr-1"></i>Connected to Server</span>';
        } else {
            statusElement.innerHTML = '<span class="text-red-400"><i class="fas fa-exclamation-triangle mr-1"></i>Connection Issues</span>';
        }
    }
}

function updateLastSyncTime() {
    lastServerSyncTime = new Date();
    const element = document.getElementById('last-sync-time');
    if (element) {
        element.textContent = lastServerSyncTime.toLocaleTimeString();
    }
}

function updateBalanceLastUpdated() {
    const element = document.getElementById('balance-last-updated');
    if (element) {
        element.textContent = new Date().toLocaleTimeString();
    }
}

// Enhanced Server Synchronization with real-time updates
function syncWithServer() {
    showSyncIndicator();
    
    return fetch(window.miningStatusUrl, {
        method: 'GET',
        headers: {
            'X-CSRF-TOKEN': window.csrfToken
        }
    })
    .then(response => {
        if (response.status === 401) {
            window.location.href = '/login';
            return;
        }
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        if (!data) return;
        
        updateServerStatus(true);
        updateLastSyncTime();
        
        console.log('Server sync completed:', {
            timestamp: data.timestamp,
            has_session: data.has_active_session,
            total_mined: data.has_active_session ? data.session.total_mined : 0,
            user_balance: data.user_balance,
            mining_rate: data.has_active_session ? data.session.mining_rate_per_minute : 0
        });

        if (data.success) {
            if (data.has_active_session && !data.session.is_expired) {
                const session = data.session;
                
                // Update mining state with server data
                isMiningActive = true;
                nextActivationTime = new Date(session.expires_at);
                
                // Update totals from server (real-time sync)
                const newTotalMined = parseFloat(session.total_mined);
                const newBalance = parseFloat(data.user_balance);
                
                // Check if values actually changed to show real progress
                if (newTotalMined !== totalMined) {
                    totalMined = newTotalMined;
                    console.log(`Mining progress updated: ${totalMined.toFixed(8)} CBC`);
                }
                
                if (newBalance !== currentAccountBalance) {
                    currentAccountBalance = newBalance;
                    console.log(`Balance updated: ${currentAccountBalance.toFixed(8)} CBC`);
                }
                
                miningRatePerMinute = parseFloat(session.mining_rate_per_minute);
                
                if (!sessionStartTime) {
                    sessionStartTime = new Date(session.started_at);
                }
                
                // Show detailed progress
                console.log('Active Mining Session:', {
                    session_id: session.id,
                    plan: session.plan_name,
                    total_mined: session.total_mined,
                    remaining_time: formatTimeRemaining(session.remaining_seconds),
                    mining_rate_per_minute: session.mining_rate_per_minute,
                    user_balance: data.user_balance
                });
                
                // Update UI with real server data
                showMiningActive();
                updateMinedDisplay();
                updateBalanceDisplay();
                updateMiningRateDisplay(session.mining_rate_per_minute);
                updateHashRateStatus('Mining Active');
                
                // Update plan data based on server response
                updatePlanDataFromServer(session);
                
                if (!planCountdownTimer) {
                    startPlanCountdown();
                }
                
                if (!sessionDurationTimer) {
                    startSessionDurationTimer();
                }
                
                if (!serverSyncInterval) {
                    startMiningUpdates();
                    startServerSync();
                }
            } else {
                console.log('No active mining session on server');
                showActivateButton();
            }
        }
    })
    .catch(error => {
        console.error('Server sync failed:', error);
        updateServerStatus(false);
        // Don't reset mining state on temporary connection issues
        if (!isMiningActive) {
            checkPendingAd();
        }
    });
}

function updatePlanDataFromServer(session) {
    // Update global plan data with actual server values
    const plan = session.plan_name;
    if (plan && plan !== 'Free Plan') {
        // Update current hash rate based on plan
        if (window.planData.speed !== 100) { // Assuming your plan has 100 MH/s
            window.planData.speed = 100;
            currentHashRate = 100;
            updateHashRateDisplay();
        }
    }
}

// Mining State Management
function initializeMiningState() {
    console.log('Initializing mining state...');
    updateHashRateStatus('Connecting to server...');
    
    syncWithServer()
        .then(() => {
            if (!isMiningActive) {
                checkPendingAd();
            }
        })
        .catch(error => {
            console.error('Failed to sync with server during initialization:', error);
            checkPendingAd();
        });
}

function checkPendingAd() {
    const savedAdStartTime = localStorage.getItem('adStartTime');
    if (savedAdStartTime) {
        const elapsed = Math.floor((Date.now() - parseInt(savedAdStartTime)) / 1000);
        if (elapsed < adDuration) {
            console.log('Resuming ad countdown...');
            showAdContainer();
            startAdCountdown();
            return;
        } else {
            localStorage.removeItem('adStartTime');
        }
    }
    showActivateButton();
}

function startServerSync() {
    if (serverSyncInterval) {
        clearInterval(serverSyncInterval);
    }
    
    console.log(`Starting server synchronization every ${SYNC_INTERVAL/1000} seconds`);
    serverSyncInterval = setInterval(() => {
        if (isMiningActive) {
            syncWithServer().catch(error => {
                console.error('Scheduled server sync failed:', error);
            });
        }
    }, SYNC_INTERVAL); // Sync every 5 seconds for real-time updates
}

// Ad Management (keeping existing code)
function showAd() {
    console.log('Starting ad sequence...');
    showAdContainer();
    
    adStartTime = Date.now();
    localStorage.setItem('adStartTime', adStartTime.toString());
    
    try {
        (adsbygoogle = window.adsbygoogle || []).push({});
    } catch (e) {
        console.error("AdSense error:", e);
    }
    
    startAdCountdown();
}

function showAdContainer() {
    const activateBtn = document.getElementById('activate-btn');
    const adsenseContainer = document.getElementById('adsense-container');
    
    if (activateBtn) {
        activateBtn.classList.add('hidden');
    }
    if (adsenseContainer) {
        adsenseContainer.classList.remove('hidden');
    }
}

function startAdCountdown() {
    if (adCountdownTimer) {
        clearInterval(adCountdownTimer);
    }
    
    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');
    const progressPercent = document.getElementById('ad-progress-percent');
    
    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);
        const progress = ((adDuration - remaining) / adDuration) * 100;
        
        if (countdownElement) {
            countdownElement.textContent = remaining;
        }
        if (adCountdownElement) {
            adCountdownElement.textContent = remaining;
        }
        if (progressBar) {
            progressBar.style.width = `${progress}%`;
        }
        if (progressPercent) {
            progressPercent.textContent = Math.round(progress);
        }
        
        if (remaining <= 0) {
            clearInterval(adCountdownTimer);
            if (continueButton) {
                continueButton.disabled = false;
                continueButton.classList.remove('opacity-50', 'cursor-not-allowed');
                continueButton.classList.add('hover:from-green-600', 'hover:to-green-700');
                continueButton.innerHTML = '<i class="fas fa-check mr-2"></i>Continue Mining';
            }
            if (progressBar) {
                progressBar.style.width = '100%';
            }
            if (progressPercent) {
                progressPercent.textContent = '100';
            }
            
            localStorage.removeItem('adStartTime');
        }
    }
    
    updateCountdown();
    adCountdownTimer = setInterval(updateCountdown, 1000);
}

// Mining Session Management
function startMining() {
    console.log('Starting mining session...');
    
    const adsenseContainer = document.getElementById('adsense-container');
    if (adsenseContainer) {
        adsenseContainer.classList.add('hidden');
    }
    
    if (adCountdownTimer) {
        clearInterval(adCountdownTimer);
    }
    localStorage.removeItem('adStartTime');
    
    updateHashRateStatus('Starting session...');
    
    fetch(window.startMiningUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': window.csrfToken
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Failed to start mining session');
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            console.log('Mining session started successfully:', data.session);
            
            isMiningActive = true;
            nextActivationTime = new Date(data.session.expires_at);
            totalMined = parseFloat(data.session.total_mined);
            sessionStartTime = new Date();
            
            showMiningActive();
            updateMinedDisplay();
            updateHashRateStatus('Mining Active');
            
            clearLocalMiningData();
            
            startPlanCountdown();
            startSessionDurationTimer();
            startMiningUpdates();
            startServerSync();
            
            resetAdCountdown();
        } else {
            console.error('Failed to start mining session:', data.message);
            updateHashRateStatus('Failed to start');
            showActivateButton();
        }
    })
    .catch(error => {
        console.error('Error starting mining session:', error);
        updateHashRateStatus('Connection failed');
        showActivateButton();
    });
}

// UI State Management
function showMiningActive() {
    const miningStatus = document.getElementById('mining-status');
    const activateBtn = document.getElementById('activate-btn');
    const miningRateDisplay = document.getElementById('mining-rate-display');
    const sessionDuration = document.getElementById('session-duration');
    
    if (miningStatus) {
        miningStatus.classList.remove('hidden');
    }
    if (activateBtn) {
        activateBtn.classList.add('hidden');
    }
    if (miningRateDisplay) {
        miningRateDisplay.classList.remove('hidden');
    }
    if (sessionDuration) {
        sessionDuration.classList.remove('hidden');
    }
}

function showActivateButton() {
    console.log('Showing activate button...');
    clearAllTimers();
    
    isMiningActive = false;
    nextActivationTime = null;
    totalMined = 0;
    sessionStartTime = null;
    miningRatePerMinute = 0;
    
    clearLocalMiningData();
    
    const miningStatus = document.getElementById('mining-status');
    const activateBtn = document.getElementById('activate-btn');
    const adsenseContainer = document.getElementById('adsense-container');
    const miningRateDisplay = document.getElementById('mining-rate-display');
    const sessionDuration = document.getElementById('session-duration');
    
    if (miningStatus) {
        miningStatus.classList.add('hidden');
    }
    if (activateBtn) {
        activateBtn.classList.remove('hidden');
    }
    if (adsenseContainer) {
        adsenseContainer.classList.add('hidden');
    }
    if (miningRateDisplay) {
        miningRateDisplay.classList.add('hidden');
    }
    if (sessionDuration) {
        sessionDuration.classList.add('hidden');
    }
    
    updateMinedDisplay();
    updateHashRateStatus('Ready to mine');
    resetAdCountdown();
}

function clearAllTimers() {
    if (planCountdownTimer) {
        clearInterval(planCountdownTimer);
        planCountdownTimer = null;
    }
    if (adCountdownTimer) {
        clearInterval(adCountdownTimer);
        adCountdownTimer = null;
    }
    if (serverSyncInterval) {
        clearInterval(serverSyncInterval);
        serverSyncInterval = null;
    }
    if (sessionDurationTimer) {
        clearInterval(sessionDurationTimer);
        sessionDurationTimer = null;
    }
    
    miningUpdateIntervals.forEach(interval => clearInterval(interval));
    miningUpdateIntervals = [];
}

function clearLocalMiningData() {
    localStorage.removeItem('nextActivationTime');
    localStorage.removeItem('adStartTime');
    localStorage.removeItem('isMiningActive');
    localStorage.removeItem('sessionStartTime');
    localStorage.removeItem('sessionProgress');
}

// Timer Functions
function startPlanCountdown() {
    if (planCountdownTimer) {
        clearInterval(planCountdownTimer);
    }
    
    function updateCountdown() {
        if (!nextActivationTime) {
            showActivateButton();
            return;
        }

        const now = new Date();
        const timeLeft = nextActivationTime - now;

        if (timeLeft <= 0) {
            console.log('Mining session expired');
            // If user is on a paid plan, refresh the page
            // if (!window.planData.isFree) {
            window.location.reload();
                // return;
            // }
            showActivateButton();
            return;
        }

        const timeString = formatTimeRemaining(Math.floor(timeLeft / 1000));
        const countdownElement = document.getElementById('countdown-timer');
        if (countdownElement) {
            countdownElement.textContent = timeString;
        }
    }

    updateCountdown();
    planCountdownTimer = setInterval(updateCountdown, 1000);
}

function startSessionDurationTimer() {
    if (sessionDurationTimer) {
        clearInterval(sessionDurationTimer);
    }
    
    function updateDuration() {
        if (!sessionStartTime) return;
        
        const now = new Date();
        const elapsed = Math.floor((now - sessionStartTime) / 1000);
        
        const element = document.getElementById('session-time');
        if (element) {
            element.textContent = formatTime(elapsed);
        }
    }
    
    updateDuration();
    sessionDurationTimer = setInterval(updateDuration, 1000);
}

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');
    const progressPercent = document.getElementById('ad-progress-percent');
    
    if (continueButton) {
        continueButton.disabled = true;
        continueButton.classList.add('opacity-50', 'cursor-not-allowed');
        continueButton.classList.remove('hover:from-green-600', 'hover:to-green-700');
        continueButton.innerHTML = '<i class="fas fa-hourglass-half mr-2"></i>Continue Mining (<span id="continue-countdown">30</span>s)';
    }
    if (continueCountdown) {
        continueCountdown.textContent = '30';
    }
    if (adCountdown) {
        adCountdown.textContent = '30';
    }
    if (progressBar) {
        progressBar.style.width = '0%';
    }
    if (progressPercent) {
        progressPercent.textContent = '0';
    }
}

// Display Update Functions
function updateMinedDisplay() {
    const btcPrice = 2.3186;
    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;
    }
}

function updateBalanceDisplay() {
    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 * 2.3186).toFixed(6);
    }
    
    updateBalanceLastUpdated();
}

function updateMiningRateDisplay(ratePerMinute) {
    const element = document.getElementById('mining-rate');
    if (element && ratePerMinute) {
        element.textContent = (ratePerMinute).toFixed(8);
        miningRatePerMinute = ratePerMinute;
    }
}

function updateHashRateStatus(status) {
    const element = document.getElementById('hash-rate-status');
    if (element) {
        element.textContent = status;
    }
}

function updateHashRateDisplay() {
    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}`;
    }
}

// Enhanced Mining Animation Functions with Real Fluctuations
function updateHashRate() {
    if (!isMiningActive) return;
    
    const planSpeed = window.planData.speed;
    const maxFluctuation = planSpeed * 0.15; // 15% fluctuation
    
    // More realistic fluctuation based on actual mining
    const fluctuation = (Math.random() - 0.5) * maxFluctuation;
    const changeRate = Math.random() * (planSpeed * 0.05) + (planSpeed * 0.01);
    
    if (Math.random() < 0.3) {
        hashRateDirection *= -1;
    }
    
    currentHashRate += (hashRateDirection * changeRate) + fluctuation;
    
    const minSpeed = planSpeed * 0.8;
    const maxSpeed = planSpeed * 1.2;
    currentHashRate = Math.max(minSpeed, Math.min(maxSpeed, currentHashRate));
    
    updateHashRateDisplay();
    updateProgressRingsBasedOnHashRate();
}

function updateMiners() {
    if (!isMiningActive) return;
    
    const planMiners = window.planData.miners;
    currentMiners = planMiners;
    
    const minersElement = document.getElementById('miners-value');
    const minersStatus = document.getElementById('miners-status');
    
    if (minersElement) {
        minersElement.textContent = `${currentMiners} Miners`;
    }
    if (minersStatus) {
        minersStatus.textContent = 'Active';
    }
}

function updateProgressRingsBasedOnHashRate() {
    if (!isMiningActive) return;
    
    const baseSpeed = currentHashRate / 10;
    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;
    
    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;
    }
}

function startMiningUpdates() {
    if (miningUpdateIntervals.length > 0) {
        miningUpdateIntervals.forEach(interval => clearInterval(interval));
        miningUpdateIntervals = [];
    }
    
    console.log('Starting mining animations and visual updates');
    
    // Hash rate updates every second for smooth fluctuations
    miningUpdateIntervals.push(setInterval(() => {
        if (isMiningActive) updateHashRate();
    }, HASH_RATE_UPDATE_INTERVAL));
    
    miningUpdateIntervals.push(setInterval(() => {
        if (isMiningActive) updateMiners();
    }, 5000));
    
    // Progress rings update more frequently for smooth animation
    miningUpdateIntervals.push(setInterval(() => {
        if (isMiningActive) updateProgressRingsBasedOnHashRate();
    }, 50));
}

// Event Listeners
window.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, initializing mining interface...');
    initializeMiningState();
});

// Handle page visibility change to sync when user returns
document.addEventListener('visibilitychange', function() {
    if (!document.hidden && isMiningActive) {
        console.log('Page became visible, syncing with server...');
        syncWithServer().catch(error => {
            console.error('Failed to sync on visibility change:', error);
        });
    }
});

// Handle beforeunload to show user that mining continues
window.addEventListener('beforeunload', function(e) {
    if (isMiningActive) {
        const message = 'Mining will continue in the background even if you close this page.';
        e.returnValue = message;
        return message;
    }
});

// Add touch feedback for mobile
document.querySelectorAll('.stats-card, button, a').forEach(item => {
    item.addEventListener('touchstart', function() {
        this.style.transform = 'scale(0.98)';
    });
    item.addEventListener('touchend', function() {
        this.style.transform = 'scale(1)';
    });
});

console.log('Mining interface script loaded successfully with real-time updates');
</script>
@endsection