<x-app-layout>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" />

    {{-- TOAST NOTIFICATION --}}
    <div id="toast-success" class="fixed top-24 right-5 z-[9999] transform translate-x-[150%] transition-transform duration-500 ease-in-out">
        <div class="bg-white px-5 py-4 rounded-xl shadow-2xl flex items-center gap-3 border-l-4 border-[#f59e0b]">
            <div class="w-8 h-8 bg-[#f59e0b] rounded-full flex items-center justify-center">
                <i class="fas fa-check text-white text-xs"></i>
            </div>
            <div>
                <p class="text-xs font-bold text-[#2c1a0e] uppercase tracking-wider">Berhasil!</p>
                <p class="text-[11px] text-[#8c6a4a]">Produk ditambahkan ke keranjang.</p>
            </div>
        </div>
    </div>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 lg:py-10 bg-[#FAF7F2]">
        {{-- Top Navigation --}}
        <div class="mb-6">
            <a href="{{ route('products.index') }}" class="group inline-flex items-center gap-2 text-[#8c6a4a] hover:text-[#f59e0b] transition-all font-semibold text-sm">
                <div class="w-8 h-8 rounded-full bg-white shadow-sm flex items-center justify-center group-hover:bg-[#fef3c7] transition">
                    <i class="fas fa-arrow-left text-[10px]"></i>
                </div>
                Kembali ke Katalog
            </a>
        </div>

        {{-- Product Main Card --}}
        <div class="bg-white rounded-2xl shadow-lg border border-[#e0d3c2] overflow-hidden mb-10">
            <div class="flex flex-col lg:flex-row">
                {{-- LEFT: GALLERY --}}
                <div class="lg:w-1/2 p-6 lg:p-8 bg-[#fef9f0]">
                    <div class="sticky top-24">
                        <div class="swiper mainSwiper rounded-xl overflow-hidden shadow-md bg-white border border-[#e0d3c2]">
                            <div class="swiper-wrapper">
                                @php $allImages = $product->variants->flatMap->images; @endphp
                                @forelse($allImages as $img)
                                    <div class="swiper-slide !h-auto flex items-center justify-center p-8">
                                        <img src="{{ asset('storage/'.$img->image) }}" 
                                             class="w-full h-auto max-h-[50vh] object-contain rounded-xl" 
                                             alt="{{ $product->name }}" />
                                    </div>
                                @empty
                                    <div class="swiper-slide aspect-square flex flex-col items-center justify-center text-[#8c6a4a] bg-[#fef3c7] font-bold text-sm">
                                        <i class="fas fa-image text-4xl mb-3"></i>
                                        <span>Tidak ada gambar</span>
                                    </div>
                                @endforelse
                            </div>
                            <div class="swiper-button-next !text-[#f59e0b] !after:text-sm !w-10 !h-10 !bg-white/90 backdrop-blur-sm rounded-full shadow-md border border-[#e0d3c2]"></div>
                            <div class="swiper-button-prev !text-[#f59e0b] !after:text-sm !w-10 !h-10 !bg-white/90 backdrop-blur-sm rounded-full shadow-md border border-[#e0d3c2]"></div>
                        </div>
                    </div>
                </div>

                {{-- RIGHT: DETAILS --}}
                <div class="lg:w-1/2 p-6 lg:p-8">
                    <div class="flex items-center justify-between mb-4 flex-wrap gap-3">
                        <span class="px-3 py-1.5 bg-[#fef3c7] text-[#d97706] text-[10px] font-bold uppercase tracking-wider rounded-full">
                            <i class="fas fa-tag mr-1 text-[8px]"></i>
                            {{ $product->category->name ?? 'Furniture' }}
                        </span>
                        @auth
                        <form action="{{ route('wishlist.toggle', $product->id) }}" method="POST">
                            @csrf
                            @php $isWishlisted = auth()->user()->wishlists->contains('product_id', $product->id); @endphp
                            <button type="submit" class="w-10 h-10 rounded-xl flex items-center justify-center transition-all shadow-sm border {{ $isWishlisted ? 'bg-red-500 border-red-500 text-white' : 'bg-white border-[#e0d3c2] text-[#8c6a4a] hover:text-red-500 hover:border-red-200' }}">
                                <i class="fas fa-heart text-sm"></i>
                            </button>
                        </form>
                        @endauth
                    </div>

                    <h1 class="text-2xl lg:text-3xl font-bold text-[#2c1a0e] mb-3 leading-tight">{{ $product->name }}</h1>
                    
                    {{-- Rating Summary --}}
                    <div class="flex items-center gap-3 mb-5 bg-[#fef9f0] w-fit px-3 py-1.5 rounded-lg border border-[#e0d3c2]">
                        <div class="flex items-center gap-0.5 text-sm">
                            @php $avg = round($product->reviews->avg('rating') ?? 0, 1); @endphp
                            @for($i=1; $i<=5; $i++)
                                <i class="fas fa-star text-xs {{ $i <= $avg ? 'text-[#f59e0b]' : 'text-[#e0d3c2]' }}"></i>
                            @endfor
                        </div>
                        <span class="text-xs font-semibold text-[#8c6a4a]">{{ number_format($avg, 1) }} / 5.0</span>
                        <span class="text-xs text-[#8c6a4a]">({{ $product->reviews->count() }} ulasan)</span>
                    </div>

                    <p class="text-[#2c1a0e]/80 leading-relaxed text-sm mb-6">
                        {{ $product->description }}
                    </p>

                    <form id="purchase-form">
                        @csrf
                        <input type="hidden" name="product_id" value="{{ $product->id }}">

                        {{-- Variant Selection --}}
                        <div class="mb-6">
                            <label class="text-[#8c6a4a] text-[10px] font-bold uppercase tracking-wider block mb-3">
                                <i class="fas fa-palette mr-1"></i> Pilih Warna / Varian
                            </label>
                            <div class="grid grid-cols-2 sm:grid-cols-3 gap-3">
                                @foreach($product->variants as $index => $variant)
                                    <label class="cursor-pointer group">
                                        <input type="radio" name="product_variant_id" value="{{ $variant->id }}" 
                                            class="peer sr-only variant-radio" 
                                            data-variant-index="{{ $index }}" 
                                            data-stock="{{ $variant->stock }}" 
                                            data-price="{{ $variant->price ?? $product->base_price }}"
                                            {{ $loop->first ? 'checked' : '' }} required>
                                        
                                        <div class="relative p-3 rounded-xl border-2 transition-all peer-checked:border-[#f59e0b] peer-checked:bg-[#fef3c7] cursor-pointer
                                                    {{ $loop->first ? 'border-[#f59e0b] bg-[#fef3c7]' : 'border-[#e0d3c2] bg-white' }}">
                                            
                                            <div class="flex items-center gap-3">
                                                <div class="relative">
                                                    @php $variantImage = $variant->images->first(); @endphp
                                                    @if($variantImage)
                                                        <img src="{{ asset('storage/'.$variantImage->image) }}" class="w-12 h-12 rounded-lg object-cover border border-[#e0d3c2] shadow-sm">
                                                    @else
                                                        <div class="w-12 h-12 rounded-lg flex items-center justify-center bg-[#f59e0b]/80 shadow-sm">
                                                            <i class="fas fa-couch text-white text-lg"></i>
                                                        </div>
                                                    @endif
                                                </div>
                                                <div class="flex-1">
                                                    <p class="text-sm font-bold text-[#2c1a0e] capitalize">{{ $variant->color ?? $variant->name }}</p>
                                                    <p class="text-[10px] text-[#8c6a4a]">Stok: {{ $variant->stock }}</p>
                                                </div>
                                            </div>
                                        </div>
                                    </label>
                                @endforeach
                            </div>
                        </div>

                        {{-- Price & Quantity --}}
                        <div class="bg-gradient-to-r from-[#fef9f0] to-white rounded-xl p-5 mb-6 border border-[#e0d3c2]">
                            <div class="flex flex-col sm:flex-row items-center justify-between gap-4">
                                <div>
                                    <span class="text-[#8c6a4a] text-[10px] font-bold uppercase tracking-wider block mb-1">Total Harga</span>
                                    <h2 class="text-2xl font-bold text-[#f59e0b]" id="price-display" data-base-price="{{ (float)($product->variants->first()->price ?? $product->base_price) }}">
                                        Rp {{ number_format($product->variants->first()->price ?? $product->base_price, 0, ',', '.') }}
                                    </h2>
                                </div>
                                <div class="flex items-center bg-[#fef9f0] rounded-xl p-1 border border-[#e0d3c2]">
                                    <button type="button" id="btn-minus" class="w-10 h-10 hover:bg-[#fef3c7] rounded-lg transition-colors font-bold text-lg text-[#2c1a0e]">-</button>
                                    <input type="number" id="qty-input" name="quantity" value="1" min="1" readonly class="w-14 bg-transparent border-none text-center font-bold focus:ring-0 text-base text-[#2c1a0e]">
                                    <button type="button" id="btn-plus" class="w-10 h-10 hover:bg-[#fef3c7] rounded-lg transition-colors font-bold text-lg text-[#2c1a0e]">+</button>
                                </div>
                            </div>
                        </div>

                        {{-- Action Buttons --}}
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                            <button type="button" onclick="addToCartAJAX()" class="py-3 rounded-xl border-2 border-[#f59e0b] text-[#d97706] font-bold text-xs uppercase tracking-wider hover:bg-[#f59e0b] hover:text-white transition-all flex items-center justify-center gap-2">
                                <i class="fas fa-shopping-cart"></i> Tambah ke Keranjang
                            </button>
                            <button type="submit" formaction="{{ route('cart.directCheckout') }}" formmethod="POST" class="py-3 rounded-xl bg-gradient-to-r from-[#f59e0b] to-[#d97706] hover:from-[#d97706] hover:to-[#b45309] text-white font-bold text-xs uppercase tracking-wider transition-all shadow-md flex items-center justify-center gap-2">
                                <i class="fas fa-bolt"></i> Beli Sekarang
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        {{-- SECTION: REVIEWS & RATING --}}
        <div class="bg-white rounded-2xl shadow-md border border-[#e0d3c2] p-6 lg:p-8">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-end gap-6 mb-8">
                <div>
                    <h2 class="text-2xl font-bold text-[#2c1a0e] mb-2"><i class="fas fa-star mr-2 text-[#f59e0b]"></i>Ulasan Pembeli</h2>
                    <p class="text-[#8c6a4a] text-sm">Apa kata mereka tentang <span class="text-[#d97706] font-semibold">{{ $product->name }}</span></p>
                </div>
                
                {{-- Rating Summary Card --}}
                <div class="flex items-center gap-6 bg-[#fef9f0] p-5 rounded-xl border border-[#e0d3c2]">
                    <div class="text-center">
                        <p class="text-4xl font-bold text-[#f59e0b] leading-none mb-1">{{ number_format($product->reviews->avg('rating') ?? 0, 1) }}</p>
                        <p class="text-[10px] font-bold text-[#8c6a4a] uppercase tracking-wider">Skor Rata-rata</p>
                    </div>
                    <div class="w-px h-10 bg-[#e0d3c2]"></div>
                    <div>
                        <div class="flex text-[#f59e0b] text-sm gap-0.5 mb-1">
                            @php $avg_star = round($product->reviews->avg('rating') ?? 0); @endphp
                            @for($i=1; $i<=5; $i++)
                                <i class="fas fa-star {{ $i <= $avg_star ? 'text-[#f59e0b]' : 'text-[#e0d3c2]' }}"></i>
                            @endfor
                        </div>
                        <p class="text-[10px] font-bold text-[#8c6a4a] uppercase tracking-wider">{{ $product->reviews->count() }} Total Ulasan</p>
                    </div>
                </div>
            </div>

            {{-- Reviews List --}}
            <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                @forelse($product->reviews->take(4) as $review)
                    <div class="bg-[#fef9f0] border border-[#e0d3c2] p-5 rounded-xl hover:shadow-md transition-all duration-300">
                        <div class="flex items-start justify-between mb-3">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-full bg-[#f59e0b] flex items-center justify-center font-bold text-white text-sm uppercase">
                                    {{ substr($review->user->name, 0, 1) }}
                                </div>
                                <div>
                                    <p class="text-sm font-bold text-[#2c1a0e]">{{ $review->user->name }}</p>
                                    <p class="text-[10px] font-medium text-[#8c6a4a]">{{ $review->created_at->format('d M Y') }}</p>
                                </div>
                            </div>
                            <div class="flex text-[#f59e0b] text-[10px] gap-0.5 bg-white px-2 py-1 rounded-lg shadow-sm">
                                @for($i=1; $i<=5; $i++)
                                    <i class="fas fa-star {{ $i <= $review->rating ? 'text-[#f59e0b]' : 'text-[#e0d3c2]' }}"></i>
                                @endfor
                            </div>
                        </div>

                        <p class="text-[#2c1a0e]/80 text-sm leading-relaxed pl-5 relative mb-4">
                            <i class="fas fa-quote-left text-[#e0d3c2] text-xs absolute left-0 top-1"></i>
                            {{ $review->comment ?? 'Tidak ada komentar.' }}
                        </p>

                        @if(!empty($review->photos) && is_array($review->photos))
                            <div class="flex flex-wrap gap-2 pl-5 mt-3">
                                @foreach($review->photos as $photo)
                                    <a href="{{ asset('storage/' . $photo) }}" target="_blank" class="block">
                                        <img src="{{ asset('storage/' . $photo) }}" 
                                             class="w-16 h-16 object-cover rounded-lg border border-[#e0d3c2] hover:scale-105 transition-transform shadow-sm" 
                                             onerror="this.src='https://placehold.co/100x100?text=Error+Foto'"
                                             alt="Foto ulasan">
                                    </a>
                                @endforeach
                            </div>
                        @endif
                    </div>
                @empty
                    <div class="col-span-1 md:col-span-2 py-16 text-center bg-[#fef9f0] rounded-xl border border-dashed border-[#e0d3c2]">
                        <i class="fas fa-comment-slash text-[#c9b59b] text-3xl mb-3"></i>
                        <p class="text-[#8c6a4a] font-semibold uppercase tracking-wider text-sm">Belum Ada Ulasan</p>
                        <p class="text-[#8c6a4a] text-xs mt-1 text-center max-w-xs mx-auto">Hanya pembeli yang telah menerima produk yang dapat memberikan ulasan melalui menu pesanan.</p>
                    </div>
                @endforelse
            </div>
            
            @if($product->reviews->count() > 4)
                <div class="text-center mt-6 pt-4 border-t border-[#e0d3c2]">
                    <a href="{{ route('reviews.index', $product->id) }}" class="inline-flex items-center gap-2 text-sm font-semibold text-[#d97706] hover:text-[#f59e0b] transition">
                        Lihat Semua {{ $product->reviews->count() }} Ulasan <i class="fas fa-arrow-right text-xs"></i>
                    </a>
                </div>
            @endif
        </div>
    </div>

    {{-- SCRIPTS --}}
    <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Swiper
            const mainSwiper = new Swiper(".mainSwiper", {
                navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev" },
                effect: 'fade', 
                autoHeight: true,
                loop: {{ $allImages->count() > 1 ? 'true' : 'false' }},
            });

            const priceDisplay = document.getElementById('price-display');
            const qtyInput = document.getElementById('qty-input');
            let currentPrice = parseFloat(priceDisplay.getAttribute('data-base-price'));

            // Variant change
            document.querySelectorAll('.variant-radio').forEach(radio => {
                radio.addEventListener('change', function() {
                    const index = parseInt(this.getAttribute('data-variant-index'));
                    currentPrice = parseFloat(this.getAttribute('data-price'));
                    if (mainSwiper && !isNaN(index)) mainSwiper.slideTo(index);
                    qtyInput.value = 1;
                    updateTotalPrice();
                });
            });

            // Qty buttons
            document.getElementById('btn-plus').addEventListener('click', () => {
                const stock = parseInt(document.querySelector('.variant-radio:checked')?.getAttribute('data-stock') || 0);
                if (parseInt(qtyInput.value) < stock) {
                    qtyInput.value = parseInt(qtyInput.value) + 1;
                    updateTotalPrice();
                } else {
                    Swal.fire({ icon: 'warning', title: 'Stok Terbatas', text: `Stok hanya tersisa ${stock} unit`, confirmButtonColor: '#f59e0b' });
                }
            });

            document.getElementById('btn-minus').addEventListener('click', () => {
                if (parseInt(qtyInput.value) > 1) {
                    qtyInput.value = parseInt(qtyInput.value) - 1;
                    updateTotalPrice();
                }
            });

            function updateTotalPrice() {
                const total = currentPrice * parseInt(qtyInput.value);
                priceDisplay.innerText = new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', minimumFractionDigits: 0 }).format(total).replace('IDR', 'Rp');
            }
        });

        // AJAX Add to Cart
        async function addToCartAJAX() {
            const form = document.getElementById('purchase-form');
            const formData = new FormData(form);
            try {
                const response = await fetch("{{ route('cart.store') }}", {
                    method: "POST",
                    body: formData,
                    headers: { "X-Requested-With": "XMLHttpRequest", "X-CSRF-TOKEN": "{{ csrf_token() }}" }
                });
                const data = await response.json();
                if (data.success) {
                    const toast = document.getElementById('toast-success');
                    toast.classList.remove('translate-x-[150%]');
                    setTimeout(() => { toast.classList.add('translate-x-[150%]'); }, 3000);
                }
            } catch (e) { console.error(e); }
        }
    </script>
</x-app-layout>