<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{{ $game->name }} - Top Up - RISTOPUP</title>
    <link rel="icon" type="image/png" href="{{ asset('images/favicon.png') }}">
    <link rel="stylesheet" href="{{ asset('css/app.css') }}">
    <link rel="stylesheet" href="{{ asset('css/home.css') }}?v={{ time() }}">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
</head>
<body>
    @include('layouts.header')

    <div class="container">
        <!-- Main Content -->
        <main class="main-content">
            <!-- Breadcrumb -->
            <div class="breadcrumb">
                <a href="{{ route('home') }}">Home</a>
                <span>/</span>
                <a href="{{ route('category.show', $game->category->slug) }}">{{ $game->category->name }}</a>
                <span>/</span>
                <span>{{ $game->name }}</span>
            </div>

            <!-- Game Header -->
            <div class="game-header-card">
                <div class="game-banner">
                    <img src="{{ asset('storage/' . $game->image) }}" alt="{{ $game->name }}" class="game-img-fallback" data-fallback="{{ asset('images/default-game.jpg') }}">
                </div>
                <div class="game-header-info">
                    <h1>{{ $game->name }}</h1>
                    <p class="game-dev">{{ $game->developer }}</p>
                    <span class="game-cat-badge">{{ $game->category->name }}</span>
                    @if($game->description)
                    <p class="game-description">{{ $game->description }}</p>
                    @endif
                </div>
            </div>

            <!-- Products Section -->
            <section class="products-section">
                <div class="section-header">
                    <h2>Pilih Nominal</h2>
                    <p class="section-desc">Pilih jumlah {{ $game->name }} yang ingin kamu beli</p>
                </div>

                <div class="products-grid">
                    @forelse($game->activeProducts as $product)
                    @php
                        $hasFlashSale = isset($flashSales[$product->id]);
                        $flashSale = $hasFlashSale ? $flashSales[$product->id] : null;
                        $displayPrice = $hasFlashSale ? $flashSale->flash_price : $product->price;
                        $originalPrice = $product->price;
                    @endphp
                    <div class="product-card {{ $hasFlashSale ? 'flash-sale-product' : '' }}" 
                         data-product-id="{{ $product->id }}" 
                         data-product-price="{{ $displayPrice }}"
                         data-flash-sale-id="{{ $hasFlashSale ? $flashSale->id : '' }}"
                         data-original-price="{{ $originalPrice }}">
                        
                        @if($hasFlashSale)
                        <div class="flash-sale-ribbon">
                            <svg viewBox="0 0 24 24" fill="currentColor" width="12" height="12">
                                <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>
                            </svg>
                            Flash Sale
                        </div>
                        @endif

                        <div class="product-header">
                            <h3>{{ $product->name }}</h3>
                            @if($hasFlashSale)
                            <span class="discount-badge">-{{ $flashSale->getDiscountPercentage() }}%</span>
                            @elseif($product->hasDiscount())
                            <span class="discount-badge">-{{ $product->getDiscountPercentage() }}%</span>
                            @endif
                        </div>
                        
                        @if($product->description)
                        <p class="product-desc">{{ $product->description }}</p>
                        @endif
                        
                        <div class="product-price">
                            @if($hasFlashSale)
                            <span class="price-original">Rp {{ number_format($originalPrice, 0, ',', '.') }}</span>
                            <span class="price-current flash-price">Rp {{ number_format($flashSale->flash_price, 0, ',', '.') }}</span>
                            @elseif($product->hasDiscount())
                            <span class="price-original">Rp {{ number_format($product->original_price, 0, ',', '.') }}</span>
                            <span class="price-current">Rp {{ number_format($product->price, 0, ',', '.') }}</span>
                            @else
                            <span class="price-current">Rp {{ number_format($product->price, 0, ',', '.') }}</span>
                            @endif
                        </div>

                        @if($hasFlashSale)
                        <div class="flash-stock-mini">
                            <span>Sisa {{ $flashSale->getRemainingStock() }}</span>
                        </div>
                        @endif

                        @if($product->stock > 0 && (!$hasFlashSale || $flashSale->getRemainingStock() > 0))
                        <button class="btn-select-product">Pilih</button>
                        @else
                        <button class="btn-select-product" disabled>Stok Habis</button>
                        @endif
                    </div>
                    @empty
                    <div class="empty-state">
                        <p>Produk untuk game ini belum tersedia.</p>
                    </div>
                    @endforelse
                </div>
            </section>

            <!-- Order Form (Initially Hidden) -->
            <div class="order-form-section" id="orderFormSection" style="display: none;">
                <div class="section-header">
                    <h2>Detail Pemesanan</h2>
                </div>

                <form action="{{ route('products.checkout', $game->slug) }}" method="POST" class="order-form">
                    @csrf
                    <input type="hidden" name="product_id" id="selectedProductId">
                    <input type="hidden" name="flash_sale_id" id="selectedFlashSaleId">

                    <div class="form-group">
                        <label for="user_id">ID Game / User ID</label>
                        <input type="text" id="user_id" name="user_id" placeholder="Masukkan ID game kamu" required>
                        <small class="form-hint">Pastikan ID yang kamu masukkan benar</small>
                    </div>

                    @if(in_array($game->slug, ['ml', 'aov']))
                    <div class="form-group">
                        <label for="zone_id">Server / Zone ID</label>
                        <input type="text" id="zone_id" name="zone_id" placeholder="Masukkan Server ID" required>
                    </div>
                    @endif

                    <div class="form-group">
                        <label for="whatsapp">Nomor WhatsApp</label>
                        <input type="tel" id="whatsapp" name="whatsapp" placeholder="08xxxxxxxxxx" required>
                        <small class="form-hint">Untuk konfirmasi dan notifikasi</small>
                    </div>

                    <div class="order-summary">
                        <h3>Ringkasan Pesanan</h3>
                        <div class="summary-item">
                            <span>Produk</span>
                            <span id="summaryProduct">-</span>
                        </div>
                        <div class="summary-item">
                            <span>Harga</span>
                            <span id="summaryPrice">-</span>
                        </div>
                        <div class="summary-total">
                            <span>Total</span>
                            <span id="summaryTotal">-</span>
                        </div>
                    </div>

                    <button type="submit" class="btn-checkout">Lanjutkan Pembayaran</button>
                </form>
            </div>
        </main>

        <!-- Sidebar -->
        <aside class="sidebar">
            <div class="sidebar-card">
                <h3>Cara Order</h3>
                <div class="steps-list">
                    <div class="step-item">
                        <span class="step-number">1</span>
                        <div class="step-text">
                            <strong>Pilih Nominal</strong>
                            <p>Pilih jumlah yang ingin dibeli</p>
                        </div>
                    </div>
                    <div class="step-item">
                        <span class="step-number">2</span>
                        <div class="step-text">
                            <strong>Masukkan Data</strong>
                            <p>Isi ID game dan nomor WhatsApp</p>
                        </div>
                    </div>
                    <div class="step-item">
                        <span class="step-number">3</span>
                        <div class="step-text">
                            <strong>Pilih Pembayaran</strong>
                            <p>Pilih metode pembayaran</p>
                        </div>
                    </div>
                    <div class="step-item">
                        <span class="step-number">4</span>
                        <div class="step-text">
                            <strong>Selesai</strong>
                            <p>Proses otomatis dalam hitungan detik</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="sidebar-card">
                <h3>Keamanan Transaksi</h3>
                <div class="info-item">
                    <span class="info-icon">🔒</span>
                    <div class="info-text">
                        <strong>100% Aman</strong>
                        <p>Transaksi terjamin aman</p>
                    </div>
                </div>
                <div class="info-item">
                    <span class="info-icon">⚡</span>
                    <div class="info-text">
                        <strong>Proses Cepat</strong>
                        <p>Otomatis dalam hitungan detik</p>
                    </div>
                </div>
            </div>
        </aside>
    </div>

    @include('layouts.footer')

    <!-- JavaScript -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const productCards = document.querySelectorAll('.product-card');
            const orderFormSection = document.getElementById('orderFormSection');
            const selectedProductIdInput = document.getElementById('selectedProductId');
            const selectedFlashSaleIdInput = document.getElementById('selectedFlashSaleId');
            const summaryProduct = document.getElementById('summaryProduct');
            const summaryPrice = document.getElementById('summaryPrice');
            const summaryTotal = document.getElementById('summaryTotal');

            // Handle image error fallback - only once per image
            document.querySelectorAll('.game-img-fallback').forEach(img => {
                img.addEventListener('error', function() {
                    if (!this.dataset.fallbackAttempted) {
                        this.dataset.fallbackAttempted = 'true';
                        this.src = this.dataset.fallback;
                    }
                }, { once: true });
            });

            // Handle product selection
            productCards.forEach(card => {
                const selectBtn = card.querySelector('.btn-select-product');
                if (!selectBtn || selectBtn.disabled) return;

                selectBtn.addEventListener('click', function() {
                    // Remove active class from all cards
                    productCards.forEach(c => c.classList.remove('active'));
                    
                    // Add active class to selected card
                    card.classList.add('active');

                    // Get product data
                    const productId = card.dataset.productId;
                    const productName = card.querySelector('h3').textContent;
                    const productPrice = parseFloat(card.dataset.productPrice);
                    const flashSaleId = card.dataset.flashSaleId || '';

                    // Update form
                    selectedProductIdInput.value = productId;
                    selectedFlashSaleIdInput.value = flashSaleId;
                    summaryProduct.textContent = productName;
                    summaryPrice.textContent = 'Rp ' + productPrice.toLocaleString('id-ID');
                    summaryTotal.textContent = 'Rp ' + productPrice.toLocaleString('id-ID');

                    // Add flash sale indicator if applicable
                    if (flashSaleId) {
                        summaryProduct.innerHTML = productName + ' <span class="flash-indicator">⚡ Flash Sale</span>';
                    }

                    // Show order form
                    orderFormSection.style.display = 'block';
                    orderFormSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
                });
            });
        });
    </script>
</body>
</html>
