@extends('front.layouts.app')

@section('content')
<div class="container mx-auto px-4 py-8">
    <div class="max-w-4xl mx-auto">
        <!-- Header -->
        <div class="text-center mb-8">
            <h1 class="text-5xl font-bold bg-gradient-to-r from-orange-400 to-yellow-400 bg-clip-text text-transparent mb-4">
                {{ trans('daily-spin.title') }}
            </h1>
            <p class="text-gray-400 text-xl">{{ trans('daily-spin.subtitle', ['currency' => $settings['currency_name']]) }}</p>
            <div class="flex justify-center items-center mt-4 space-x-4">
                <div class="flex items-center text-gray-500">
                    <i class="fas fa-box mr-2"></i>
                    <span>{{ trans('daily-spin.cs_go_style') }}</span>
                </div>
                <div class="w-2 h-2 bg-gray-600 rounded-full"></div>
                <div class="flex items-center text-gray-500">
                    <i class="fas fa-clock mr-2"></i>
                    <span>{{ trans('daily-spin.daily_reset') }}</span>
                </div>
                <div class="w-2 h-2 bg-gray-600 rounded-full"></div>
                <div class="flex items-center text-gray-500">
                    <i class="fas fa-coins mr-2"></i>
                    <span>{{ trans('daily-spin.instant_rewards') }}</span>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Spin Wheel Section -->
            <div class="lg:col-span-2">
                <div class="bg-gray-800/95 rounded-xl shadow-lg border border-gray-700/60">
                    <div class="p-8 text-center">
                        @if($canSpin)
                            <!-- CS:GO Case Opening -->
                            <div class="relative mb-8">
                                <h3 class="text-2xl font-bold text-white mb-6 text-center">{{ trans('daily-spin.title') }}</h3>
                                
                                <!-- Case Opening Container -->
                                <div class="max-w-5xl mx-auto">
                                    <!-- Case Display -->
                                    <div class="bg-gradient-to-b from-gray-800 to-gray-900 rounded-2xl shadow-2xl border border-gray-600/50 p-6 mb-6">
                                        <!-- Case Header -->
                                        <div class="text-center mb-6">
                                            <div class="inline-flex items-center px-6 py-3 bg-gradient-to-r from-orange-500/20 to-yellow-500/20 rounded-full border border-orange-500/30">
                                                <i class="fas fa-box text-orange-400 mr-3 text-xl"></i>
                                                <span class="text-white font-bold text-lg">{{ trans('daily-spin.daily_reward_case') }}</span>
                                            </div>
                                        </div>
                                        
                                        <!-- CS:GO Style Scrolling Items -->
                                        <div class="relative bg-gray-900/80 rounded-xl p-4 mb-6 overflow-hidden border-2 border-gray-700/50">
                                            <!-- Selection Indicator -->
                                            <div class="absolute top-0 left-1/2 transform -translate-x-1/2 w-1 h-full bg-gradient-to-b from-transparent via-orange-500 to-transparent z-20 pointer-events-none"></div>
                                            <div class="absolute top-2 left-1/2 transform -translate-x-1/2 w-6 h-6 bg-orange-500 rounded-full z-20 pointer-events-none shadow-lg"></div>
                                            <div class="absolute bottom-2 left-1/2 transform -translate-x-1/2 w-6 h-6 bg-orange-500 rounded-full z-20 pointer-events-none shadow-lg"></div>
                                            
                                            <!-- Items Container -->
                                            <div class="relative h-32 overflow-hidden">
                                                <div id="items-container" class="absolute top-0 left-0 flex items-center h-full transition-transform duration-[3000ms] ease-out" style="transform: translateX(0px);">
                                                    <!-- Generate many items for scrolling effect -->
                                                    @foreach($items as $item)
                                                        <div class="flex-shrink-0 w-24 h-28 mx-1 relative">
                                                            <!-- Item Card -->
                                                            <div class="w-full h-full rounded-lg border-2 p-2 flex flex-col items-center justify-center text-center
                                                                @if($item['rarity'] == 'legendary') bg-gradient-to-b from-yellow-500/20 to-orange-500/20 border-yellow-500/60
                                                                @elseif($item['rarity'] == 'epic') bg-gradient-to-b from-purple-500/20 to-pink-500/20 border-purple-500/60
                                                                @elseif($item['rarity'] == 'rare') bg-gradient-to-b from-blue-500/20 to-cyan-500/20 border-blue-500/60
                                                                @elseif($item['rarity'] == 'uncommon') bg-gradient-to-b from-green-500/20 to-emerald-500/20 border-green-500/60
                                                                @else bg-gradient-to-b from-gray-500/20 to-gray-600/20 border-gray-500/60
                                                                @endif
                                                            ">
                                                                <!-- Coin Icon -->
                                                                <i class="fas fa-coins text-2xl mb-1
                                                                    @if($item['rarity'] == 'legendary') text-yellow-400
                                                                    @elseif($item['rarity'] == 'epic') text-purple-400
                                                                    @elseif($item['rarity'] == 'rare') text-blue-400
                                                                    @elseif($item['rarity'] == 'uncommon') text-green-400
                                                                    @else text-gray-400
                                                                    @endif
                                                                "></i>
                                                                
                                                                <!-- Amount -->
                                                                <div class="text-white font-bold text-xs">
                                                                    {{ number_format($item['reward']) }}
                                                                </div>
                                                                <div class="text-gray-300 text-xs">
                                                                    {{ $settings['currency_name'] }}
                                                                </div>
                                                            </div>
                                                            
                                                            <!-- Rarity Glow Effect -->
                                                            <div class="absolute inset-0 rounded-lg opacity-0 transition-opacity duration-300
                                                                @if($item['rarity'] == 'legendary') shadow-lg shadow-yellow-500/50
                                                                @elseif($item['rarity'] == 'epic') shadow-lg shadow-purple-500/50
                                                                @elseif($item['rarity'] == 'rare') shadow-lg shadow-blue-500/50
                                                                @elseif($item['rarity'] == 'uncommon') shadow-lg shadow-green-500/50
                                                                @endif
                                                            "></div>
                                                        </div>
                                                    @endforeach
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Status Display -->
                                        <div class="text-center mb-4">
                                            <div id="current-prize" class="text-xl font-bold text-white mb-2">
                                                {{ trans('daily-spin.ready_to_open') }}
                                            </div>
                                            <div class="text-gray-400 text-sm">
                                                {{ trans('daily-spin.click_to_start') }}
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Winner Display -->
                                    <div id="winner-display" class="opacity-0 transition-all duration-500 mb-6">
                                        <div class="bg-gradient-to-r from-orange-500 to-yellow-500 rounded-2xl p-6 text-center shadow-2xl border border-yellow-500/50">
                                            <div class="text-black font-bold text-2xl mb-2">{{ trans('daily-spin.case_opened') }}</div>
                                            <div class="text-black font-bold text-3xl">
                                                You received <span id="winner-amount" class="text-yellow-900"></span>!
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Open Case Button -->
                            <button id="spin-btn" class="bg-gradient-to-r from-orange-500 to-yellow-500 hover:from-orange-600 hover:to-yellow-600 text-black font-bold px-16 py-5 text-2xl rounded-2xl shadow-2xl hover:shadow-orange-500/25 transition-all duration-300 transform hover:scale-105 border border-yellow-500/50">
                                <i class="fas fa-box-open mr-4 text-2xl"></i>
                                {{ trans('daily-spin.open_case') }}
                            </button>
                        @else
                            <!-- Already Opened Case -->
                            <div class="text-center py-12">
                                <h3 class="text-2xl font-bold text-white mb-6">📦 {{ trans('daily-spin.title') }}</h3>
                                
                                <!-- Disabled Case Display -->
                                <div class="bg-gradient-to-b from-gray-900/50 to-gray-800/50 rounded-2xl p-8 border-2 border-gray-600/30 shadow-xl opacity-60">
                                    <!-- Already Used Message -->
                                    <div class="text-center mb-6">
                                        <div class="inline-flex items-center px-8 py-4 bg-gray-600/50 rounded-full text-gray-400 font-bold text-xl border border-gray-500/30">
                                            <i class="fas fa-box-open mr-3 text-2xl"></i>
                                            {{ trans('daily-spin.case_already_opened') }}
                                        </div>
                                    </div>
                                    
                                    <!-- Disabled Case Items Preview -->
                                    <div class="relative bg-gray-900/60 rounded-xl p-4 mb-6 border border-gray-700/30">
                                        <div class="text-center mb-4">
                                            <div class="text-gray-400 font-bold">{{ trans('daily-spin.possible_rewards') }}</div>
                                        </div>
                                        
                                        <!-- Items Grid -->
                                        <div class="flex justify-center items-center space-x-2 overflow-hidden">
                                            @foreach($previewItems as $item)
                                                <div class="flex-shrink-0 w-20 h-24 relative">
                                                    <!-- Item Card -->
                                                    <div class="w-full h-full rounded-lg border p-2 flex flex-col items-center justify-center text-center
                                                        @if($item['rarity'] == 'legendary') bg-gradient-to-b from-yellow-500/10 to-orange-500/10 border-yellow-500/30
                                                        @elseif($item['rarity'] == 'epic') bg-gradient-to-b from-purple-500/10 to-pink-500/10 border-purple-500/30
                                                        @elseif($item['rarity'] == 'rare') bg-gradient-to-b from-blue-500/10 to-cyan-500/10 border-blue-500/30
                                                        @elseif($item['rarity'] == 'uncommon') bg-gradient-to-b from-green-500/10 to-emerald-500/10 border-green-500/30
                                                        @else bg-gradient-to-b from-gray-500/10 to-gray-600/10 border-gray-500/30
                                                        @endif
                                                    ">
                                                        <!-- Coin Icon -->
                                                        <i class="fas fa-coins text-lg mb-1
                                                            @if($item['rarity'] == 'legendary') text-yellow-600
                                                            @elseif($item['rarity'] == 'epic') text-purple-600
                                                            @elseif($item['rarity'] == 'rare') text-blue-600
                                                            @elseif($item['rarity'] == 'uncommon') text-green-600
                                                            @else text-gray-600
                                                            @endif
                                                        "></i>
                                                        
                                                        <!-- Amount -->
                                                        <div class="text-gray-500 font-bold text-xs">
                                                            {{ number_format($item['reward']) }}
                                                        </div>
                                                        <div class="text-gray-600 text-xs">
                                                            {{ $settings['currency_name'] }}
                                                        </div>
                                                    </div>
                                                </div>
                                            @endforeach
                                        </div>
                                    </div>
                                    
                                    <!-- Closed Case Visual -->
                                    <div class="flex justify-center mb-6">
                                        <div class="w-32 h-32 bg-gradient-to-br from-gray-700/50 to-gray-800/50 rounded-2xl border-2 border-gray-600/30 flex items-center justify-center">
                                            <i class="fas fa-lock text-4xl text-gray-500"></i>
                                        </div>
                                    </div>
                                </div>
                                
                                <h3 class="text-2xl font-bold text-gray-400 mb-4">{{ trans('daily-spin.already_opened_title') }}</h3>
                                <p class="text-gray-500 mb-6">{{ trans('daily-spin.come_back_tomorrow') }}</p>
                                
                                @if($nextSpinTime)
                                    <div class="bg-dark-50 rounded-lg p-4 inline-block">
                                        <p class="text-sm text-dark-600">{{ trans('daily-spin.next_spin_available') }}</p>
                                        <p class="text-lg font-bold text-primary-400" id="countdown">
                                            {{ $nextSpinTime->format('M j, Y g:i A') }}
                                        </p>
                                    </div>
                                @endif
                            </div>
                        @endif
                    </div>
                </div>
            </div>

            <!-- Info Sidebar -->
            <div class="space-y-6">
                <!-- Case Info -->
                <div class="bg-gray-800/95 rounded-xl shadow-lg border border-gray-700/60">
                    <div class="p-4 border-b border-gray-700/60">
                        <h3 class="text-lg font-bold text-white flex items-center">
                            <i class="fas fa-box mr-2 text-orange-400"></i>
                            {{ trans('daily-spin.case_contents') }}
                        </h3>
                    </div>
                    <div class="p-6">
                        <div class="text-center mb-4">
                            <div class="text-2xl font-bold text-orange-400 mb-1">
                                {{ number_format($settings['daily_spin_min_reward']) }} - {{ number_format($settings['daily_spin_max_reward']) }}
                            </div>
                            <p class="text-gray-400">{{ $settings['currency_name'] }}</p>
                        </div>
                        
                        <!-- Rarity Distribution -->
                        <div class="space-y-2 text-sm">
                            <div class="flex justify-between items-center">
                                <span class="text-yellow-400">● {{ trans('daily-spin.legendary') }}</span>
                                <span class="text-gray-400">5%</span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-purple-400">● {{ trans('daily-spin.epic') }}</span>
                                <span class="text-gray-400">15%</span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-blue-400">● {{ trans('daily-spin.rare') }}</span>
                                <span class="text-gray-400">25%</span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-green-400">● {{ trans('daily-spin.uncommon') }}</span>
                                <span class="text-gray-400">30%</span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-gray-400">● {{ trans('daily-spin.common') }}</span>
                                <span class="text-gray-400">25%</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Rules -->
                <div class="bg-gray-800/95 rounded-xl shadow-lg border border-gray-700/60">
                    <div class="p-4 border-b border-gray-700/60">
                        <h3 class="text-lg font-bold text-white flex items-center">
                            <i class="fas fa-info-circle mr-2 text-blue-400"></i>
                            {{ trans('daily-spin.case_rules') }}
                        </h3>
                    </div>
                    <div class="p-6">
                        <ul class="space-y-3 text-sm text-gray-300">
                            <li class="flex items-start">
                                <i class="fas fa-check text-green-400 mt-0.5 mr-3 flex-shrink-0"></i>
                                {{ trans('daily-spin.rules.one_per_day') }}
                            </li>
                            <li class="flex items-start">
                                <i class="fas fa-check text-green-400 mt-0.5 mr-3 flex-shrink-0"></i>
                                {{ trans('daily-spin.rules.resets_midnight') }}
                            </li>
                            <li class="flex items-start">
                                <i class="fas fa-check text-green-400 mt-0.5 mr-3 flex-shrink-0"></i>
                                {{ trans('daily-spin.rules.rewards_instant') }}
                            </li>
                            <li class="flex items-start">
                                <i class="fas fa-check text-green-400 mt-0.5 mr-3 flex-shrink-0"></i>
                                {{ trans('daily-spin.rules.must_be_logged') }}
                            </li>
                        </ul>
                    </div>
                </div>

                <!-- Current Balance -->
                <div class="bg-gray-800/95 rounded-xl shadow-lg border border-gray-700/60">
                    <div class="p-4 border-b border-gray-700/60">
                        <h3 class="text-lg font-bold text-white flex items-center">
                            <i class="fas fa-wallet mr-2 text-green-400"></i>
                            {{ trans('daily-spin.your_balance') }}
                        </h3>
                    </div>
                    <div class="p-6">
                        <div class="text-center">
                            @if(Auth::check())
                                <div class="text-3xl font-bold text-green-400" id="user-balance">
                                    {{ number_format(Auth::user()->money) }}
                                </div>
                                <p class="text-gray-400">{{ $settings['currency_name'] }}</p>
                            @else
                                <div class="text-xl font-medium text-gray-300">{{ trans('daily-spin.login_to_play') }}</div>
                                <div class="mt-3">
                                    <a href="{{ url('auth/login') }}" class="px-4 py-2 bg-indigo-600 text-white rounded">{{ trans('main.login') }}</a>
                                </div>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Success Modal -->
<div id="success-modal" class="fixed inset-0 bg-black bg-opacity-75 hidden items-center justify-center z-50">
    <div class="bg-gradient-to-b from-gray-800 to-gray-900 rounded-2xl p-8 max-w-lg mx-4 text-center border border-gray-600/50 shadow-2xl">
        <div class="text-6xl mb-4">📦</div>
        <h3 class="text-3xl font-bold text-white mb-2">{{ trans('daily-spin.case_opened_success') }}</h3>
        <div class="text-orange-400 text-lg font-semibold mb-4">{{ trans('daily-spin.item_received') }}</div>
        <p class="text-gray-300 mb-6 text-lg" id="success-message"></p>
        <button onclick="closeSuccessModal()" class="bg-gradient-to-r from-orange-500 to-yellow-500 hover:from-orange-600 hover:to-yellow-600 text-black font-bold px-8 py-3 text-lg rounded-xl shadow-lg transition-all duration-300 transform hover:scale-105">
            <i class="fas fa-check mr-2"></i>
            {{ trans('daily-spin.collect_reward') }}
        </button>
    </div>
</div>

@endsection

@section('scripts')
<script>
let isSpinning = false;

document.getElementById('spin-btn')?.addEventListener('click', function() {
    if (isSpinning) return;
    
    isSpinning = true;
    this.disabled = true;
    this.innerHTML = '<i class="fas fa-spinner animate-spin mr-4 text-2xl"></i>OPENING CASE...';
    this.classList.add('opacity-75', 'cursor-not-allowed');
    
    // Get CS:GO style elements
    const itemsContainer = document.getElementById('items-container');
    const currentPrizeEl = document.getElementById('current-prize');
    const winnerDisplay = document.getElementById('winner-display');
    const winnerAmount = document.getElementById('winner-amount');
    
    // Hide winner display initially
    winnerDisplay.classList.add('opacity-0');
    
    // Update status
    currentPrizeEl.textContent = 'Opening case...';
    
    // Calculate scroll distance for CS:GO effect
    const itemWidth = 104; // Each item is w-24 (96px) + margin (8px) = 104px
    const containerWidth = itemsContainer.parentElement.offsetWidth;
    const centerOffset = containerWidth / 2;
    
    // Add opening sound effect (visual feedback)
    currentPrizeEl.classList.add('animate-pulse');
    
    // Start initial slow scroll
    let currentPosition = 0;
    const initialScrollSpeed = 50;
    const scrollInterval = setInterval(() => {
        currentPosition -= initialScrollSpeed;
        itemsContainer.style.transform = `translateX(${currentPosition}px)`;
    }, 50);
    
    // Make API call to get the actual reward
    fetch('{{ url("daily-spin/spin") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Stop initial scroll after 1 second
            setTimeout(() => {
                clearInterval(scrollInterval);
                
                // Calculate final position (scroll past many items then slow down)
                const scrollDistance = itemWidth * 60; // Scroll past 60 items
                const randomOffset = (Math.random() - 0.5) * itemWidth * 0.8; // Random landing within item bounds
                const finalPosition = -scrollDistance + centerOffset + randomOffset;
                
                // Update status
                currentPrizeEl.textContent = 'Rolling items...';
                currentPrizeEl.classList.remove('animate-pulse');
                currentPrizeEl.classList.add('animate-bounce');
                
                // Start fast scroll animation
                itemsContainer.style.transition = 'transform 2.5s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
                itemsContainer.style.transform = `translateX(${finalPosition}px)`;
                
                // Add visual effects during scroll
                const items = itemsContainer.querySelectorAll('.flex-shrink-0');
                items.forEach((item, index) => {
                    setTimeout(() => {
                        item.style.filter = 'blur(2px)';
                        setTimeout(() => {
                            item.style.filter = 'blur(0px)';
                        }, 100);
                    }, index * 20);
                });
                
                // After scroll animation completes
                setTimeout(() => {
                    // Stop bouncing
                    currentPrizeEl.classList.remove('animate-bounce');
                    
                    // Show winner with dramatic effect
                    currentPrizeEl.textContent = 'Case opened successfully!';
                    currentPrizeEl.classList.add('text-green-400');
                    
                    // Highlight the winning item
                    const centerItem = Math.floor(items.length / 2);
                    if (items[centerItem]) {
                        items[centerItem].style.transform = 'scale(1.1)';
                        items[centerItem].style.zIndex = '30';
                        items[centerItem].querySelector('.absolute').style.opacity = '1';
                    }
                    
                    // Show winner display with animation
                    setTimeout(() => {
                        winnerAmount.textContent = new Intl.NumberFormat().format(data.reward) + ' {{ $settings["currency_name"] }}';
                        winnerDisplay.classList.remove('opacity-0');
                        winnerDisplay.classList.add('animate-pulse');
                        
                        // Update user balance display
                        const balanceEl = document.getElementById('user-balance');
                        if (balanceEl) {
                            const currentBalance = parseInt(balanceEl.textContent.replace(/,/g, ''));
                            const newBalance = currentBalance + data.reward;
                            balanceEl.textContent = new Intl.NumberFormat().format(newBalance);
                            balanceEl.classList.add('text-green-400', 'animate-pulse');
                        }
                        
                        // Show success modal after winner display
                        setTimeout(() => {
                            document.getElementById('success-message').textContent = data.message;
                            document.getElementById('success-modal').classList.remove('hidden');
                            document.getElementById('success-modal').classList.add('flex');
                            
                            // Auto-reload after modal shows
                            setTimeout(() => {
                                location.reload();
                            }, 4000);
                        }, 2000);
                    }, 500);
                }, 2500);
            }, 1000);
        } else {
            clearInterval(scrollInterval);
            alert(data.message);
            location.reload();
        }
    })
    .catch(error => {
        clearInterval(scrollInterval);
        console.error('Error:', error);
        alert('An error occurred. Please try again.');
        location.reload();
    });
});

function closeSuccessModal() {
    document.getElementById('success-modal').classList.add('hidden');
    document.getElementById('success-modal').classList.remove('flex');
    location.reload();
}

// Countdown timer for next spin
@if(!$canSpin && $nextSpinTime)
function updateCountdown() {
    const nextSpin = new Date('{{ $nextSpinTime->toISOString() }}');
    const now = new Date();
    const diff = nextSpin - now;
    
    if (diff <= 0) {
        location.reload();
        return;
    }
    
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);
    
    document.getElementById('countdown').textContent = 
        `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}

setInterval(updateCountdown, 1000);
updateCountdown();
@endif
</script>
@endsection