<x-app-layout>
    <x-slot name="header">
        <div class="flex flex-col sm:flex-row sm:items-center gap-4 w-full">
            
            <!-- Kiri -->
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl flex items-center justify-center shadow-lg flex-shrink-0"
                    style="background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);">
                    <i class="fas fa-shopping-cart text-white text-sm"></i>
                </div>
                <div>
                    <h1 class="text-lg sm:text-xl font-bold text-stone-800">{{ __('Checkout') }}</h1>
                    <p class="text-xs text-stone-500">Selesaikan pesanan Anda</p>
                </div>
            </div>

            <!-- Tombol -->
            <a href="{{ route('cart.index') }}"
                class="sm:ml-auto inline-flex items-center gap-2 px-4 py-2 bg-white hover:bg-gray-50 text-gray-600 hover:text-gray-800 text-sm font-medium rounded-xl border border-gray-200 shadow-sm hover:shadow transition-all duration-200">
                <i class="fas fa-arrow-left text-xs"></i>
                <span class="hidden sm:inline">Kembali ke Keranjang</span>
                <span class="sm:hidden">Kembali</span>
            </a>

        </div>
    </x-slot>

    <div class="py-6">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <form action="{{ route('payment.store', $order) }}" method="POST" id="checkoutForm">
                @csrf
                <input type="hidden" name="address_id" id="selectedAddressId">
                <input type="hidden" name="updated_quantities" id="updatedQuantities" value="{}">

                @if(auth()->user()->addresses()->count() == 0)
                <div class="mb-6 p-4 bg-red-100 border border-red-300 text-red-700 rounded-xl flex items-center gap-3">
                    <i class="fas fa-exclamation-circle"></i>
                    <div>
                        <p class="font-semibold">Alamat pengiriman belum tersedia</p>
                        <p class="text-sm">Silakan tambahkan alamat terlebih dahulu sebelum melakukan pembayaran.</p>
                    </div>
                </div>
                @endif

                <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    <!-- Left Column: Address & Products -->
                    <div class="lg:col-span-2 space-y-6">

                        <!-- Shipping Address Section (same as before) -->
                        <div class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden">
                            <!-- ... address section content (same as your original) ... -->
                        </div>

                        <!-- Products Section with Quantity Controls -->
                        <div class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden">
                            <div class="p-6">
                                <div class="flex items-center justify-between mb-4">
                                    <h3 class="text-lg font-bold text-gray-900 flex items-center">
                                        <i class="fas fa-boxes mr-2 text-indigo-600"></i>
                                        Produk Pesanan
                                    </h3>
                                    <span class="text-xs text-gray-500 bg-gray-100 px-3 py-1 rounded-full">
                                        <i class="fas fa-edit mr-1"></i>Klik +/- untuk mengubah jumlah
                                    </span>
                                </div>

                                <div id="order-items" class="space-y-4">
                                    @foreach($order->items as $index => $item)
                                    <div class="flex items-start gap-4 p-4 bg-gray-50 rounded-xl hover:bg-gray-100 transition-colors duration-200"
                                         id="item-{{ $item->id }}">
                                        <div class="flex-shrink-0 w-20 h-20 bg-gradient-to-br from-indigo-100 to-purple-100 rounded-xl overflow-hidden border border-gray-200">
                                            @php
                                            $productImage = $item->product->image ?? null;
                                            $imageUrl = null;

                                            if ($productImage) {
                                            if (is_array($productImage) && count($productImage) > 0) {
                                            $imageUrl = asset('storage/' . $productImage[0]);
                                            } elseif (is_string($productImage)) {
                                            $decoded = json_decode($productImage, true);
                                            if (is_array($decoded) && count($decoded) > 0) {
                                            $imageUrl = asset('storage/' . $decoded[0]);
                                            } else {
                                            $imageUrl = asset('storage/' . $productImage);
                                            }
                                            }
                                            }
                                            @endphp

                                            @if($imageUrl)
                                            <img src="{{ $imageUrl }}"
                                                alt="{{ $item->product->product_name }}"
                                                class="w-full h-full object-cover">
                                            @else
                                            <div class="w-full h-full flex items-center justify-center">
                                                <i class="fas fa-box text-2xl text-indigo-300"></i>
                                            </div>
                                            @endif
                                        </div>

                                        <div class="flex-1 min-w-0">
                                            <div class="flex items-start justify-between">
                                                <div>
                                                    <h4 class="text-sm font-semibold text-gray-900 truncate">
                                                        {{ $item->product->product_name }}
                                                    </h4>
                                                    <p class="text-xs text-gray-500 mt-1">
                                                        <i class="fas fa-tag mr-1"></i>
                                                        {{ $item->product->category->category_name ?? 'Uncategorized' }}
                                                    </p>
                                                </div>
                                                
                                                <!-- Delete Item Button -->
                                                <button type="button"
                                                    onclick="removeItem({{ $item->id }})"
                                                    class="text-gray-400 hover:text-red-600 transition-colors p-2 hover:bg-red-50 rounded-full"
                                                    title="Hapus item">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                            </div>

                                            <div class="flex items-end justify-between mt-3">
                                                <div>
                                                    <p class="text-base font-bold text-indigo-600">
                                                        Rp {{ number_format($item->price, 0, ',', '.') }}
                                                    </p>
                                                    <p class="text-xs text-gray-500 mt-1">
                                                        <i class="fas fa-cubes mr-1"></i>
                                                        Stok: {{ $item->product->stock ?? 'Tersedia' }}
                                                    </p>
                                                </div>

                                                <!-- Quantity Controls -->
                                                <div class="flex items-center gap-2 bg-white rounded-lg p-1 border border-gray-200 shadow-sm">
                                                    <button type="button"
                                                        onclick="updateQuantity({{ $item->id }}, 'decrease')"
                                                        class="w-8 h-8 rounded-md hover:bg-gray-100 flex items-center justify-center transition-colors"
                                                        {{ $item->quantity <= 1 ? 'disabled' : '' }}>
                                                        <i class="fas fa-minus text-sm text-gray-600"></i>
                                                    </button>

                                                    <span id="qty-{{ $item->id }}" class="w-10 text-center font-semibold text-gray-900">
                                                        {{ $item->quantity }}
                                                    </span>

                                                    <button type="button"
                                                        onclick="updateQuantity({{ $item->id }}, 'increase')"
                                                        class="w-8 h-8 rounded-md hover:bg-gray-100 flex items-center justify-center transition-colors"
                                                        @if($item->product->stock && $item->quantity >= $item->product->stock) disabled @endif>
                                                        <i class="fas fa-plus text-sm text-gray-600"></i>
                                                    </button>
                                                </div>

                                                <!-- Item Subtotal -->
                                                <div class="text-right">
                                                    <p class="text-xs text-gray-500">Subtotal</p>
                                                    <p id="subtotal-{{ $item->id }}" class="text-base font-bold text-indigo-600">
                                                        Rp {{ number_format($item->price * $item->quantity, 0, ',', '.') }}
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    @endforeach
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Right Column: Payment & Summary (with dynamic totals) -->
                    <div class="lg:col-span-1">
                        <div class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden sticky top-6">
                            <div class="p-6">
                                <!-- Payment Method Section (same as before) -->
                                <h3 class="text-lg font-bold text-gray-900 mb-4 flex items-center">
                                    <i class="fas fa-credit-card mr-2 text-indigo-600"></i>
                                    Metode Pembayaran
                                </h3>

                                <div class="space-y-3 mb-6">
                                    <!-- ... payment method options (same as your original) ... -->
                                </div>

                                <!-- Order Summary with Dynamic Updates -->
                                <div class="border-t border-gray-200 pt-4">
                                    <h4 class="text-sm font-bold text-gray-900 mb-3 flex items-center">
                                        <i class="fas fa-receipt mr-2 text-indigo-600"></i>
                                        Ringkasan Belanja
                                    </h4>

                                    <div class="space-y-3 text-sm bg-gray-50 rounded-xl p-4">
                                        <div class="flex justify-between items-center">
                                            <span class="text-gray-600">Total Barang</span>
                                            <span id="total-items" class="font-semibold text-gray-900">{{ $order->items->count() }} barang</span>
                                        </div>
                                        <div class="flex justify-between items-center">
                                            <span class="text-gray-600">Subtotal</span>
                                            <span id="subtotal-total" class="font-bold text-indigo-600">
                                                Rp {{ number_format($order->total_price, 0, ',', '.') }}
                                            </span>
                                        </div>
                                        <div class="flex justify-between items-center">
                                            <span class="text-gray-600 flex items-center">
                                                <i class="fas fa-truck mr-1 text-gray-400"></i>
                                                Ongkos Kirim
                                            </span>
                                            <span class="inline-flex items-center px-3 py-1 bg-gradient-to-r from-green-100 to-emerald-100 text-green-700 rounded-full text-xs font-semibold border border-green-200">
                                                <i class="fas fa-check-circle mr-1"></i>GRATIS
                                            </span>
                                        </div>
                                        <div class="border-t border-gray-200 pt-3 mt-3">
                                            <div class="flex justify-between items-center">
                                                <span class="font-bold text-gray-900">Total Pembayaran</span>
                                                <span id="grand-total" class="text-xl font-extrabold text-indigo-600">
                                                    Rp {{ number_format($order->total_price, 0, ',', '.') }}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Submit Button -->
                                <button type="submit"
                                    @if(auth()->user()->addresses()->count() == 0) disabled @endif
                                    class="w-full mt-6 inline-flex justify-center items-center px-6 py-4 
                                    @if(auth()->user()->addresses()->count() == 0)
                                    bg-gray-400 cursor-not-allowed
                                    @else
                                    bg-gradient-to-r from-indigo-600 to-purple-600 hover:shadow-lg transform hover:scale-105
                                    @endif
                                    text-white font-bold rounded-xl shadow-md transition-all duration-200">
                                    <i class="fas fa-check-circle mr-2"></i>
                                    Konfirmasi Pembayaran
                                </button>

                                <p class="text-xs text-center text-gray-500 mt-4">
                                    <i class="fas fa-lock mr-1"></i>
                                    Dengan melakukan pembelian, Anda menyetujui syarat & ketentuan kami
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal Address Selection/Add (same as before) -->
    <!-- ... address modal content ... -->

<script>
    // Store original order data
    const orderItems = {
        @foreach($order->items as $item)
        {{ $item->id }}: {
            id: {{ $item->id }},
            price: Number({{ $item->price }}), // 🔥 fix: paksa number
            stock: {{ $item->product->stock ?? 999 }},
            quantity: {{ $item->quantity }}
        },
        @endforeach
    };

    let removedItems = new Set();
    let quantityChanges = {};

    function formatRupiah(number) {
        return 'Rp ' + new Intl.NumberFormat('id-ID').format(number);
    }

    function updateQuantity(itemId, action) {
        const item = orderItems[itemId];
        if (!item) return;

        const qtySpan = document.getElementById(`qty-${itemId}`);
        let currentQty = parseInt(qtySpan.textContent);

        if (action === 'increase') {
            if (currentQty < item.stock) {
                currentQty++;
            } else {
                showNotification('Stok tidak mencukupi', 'warning');
                return;
            }
        } else if (action === 'decrease') {
            if (currentQty > 1) {
                currentQty--;
            } else {
                return;
            }
        }

        // update UI
        qtySpan.textContent = currentQty;

        // simpan perubahan
        quantityChanges[itemId] = currentQty;
        document.getElementById('updatedQuantities').value = JSON.stringify(quantityChanges);

        // update subtotal item
        const subtotal = item.price * currentQty;
        document.getElementById(`subtotal-${itemId}`).textContent = formatRupiah(subtotal);

        // update tombol
        const decreaseBtn = document.querySelector(`#item-${itemId} button[onclick*="decrease"]`);
        const increaseBtn = document.querySelector(`#item-${itemId} button[onclick*="increase"]`);

        if (decreaseBtn) decreaseBtn.disabled = currentQty <= 1;
        if (increaseBtn) increaseBtn.disabled = currentQty >= item.stock;

        updateTotals();
    }

    function removeItem(itemId) {
        if (!confirm('Hapus item ini dari pesanan?')) return;

        const itemElement = document.getElementById(`item-${itemId}`);

        itemElement.style.transition = 'all 0.3s ease';
        itemElement.style.transform = 'translateX(100%)';
        itemElement.style.opacity = '0';

        setTimeout(() => {
            itemElement.remove();
            removedItems.add(itemId);
            updateTotals();
            showNotification('Item telah dihapus dari pesanan', 'success');
        }, 300);
    }

    function updateTotals() {
        let totalItems = 0;
        let subtotal = 0;

        document.querySelectorAll('[id^="item-"]').forEach(itemElement => {
            const itemId = parseInt(itemElement.id.replace('item-', ''));
            const qty = parseInt(document.getElementById(`qty-${itemId}`).textContent);
            const price = Number(orderItems[itemId].price);

            totalItems += qty; // 🔥 FIX (sebelumnya cuma +1)
            subtotal += price * qty;
        });

        document.getElementById('total-items').textContent = `${totalItems} barang`;
        document.getElementById('subtotal-total').textContent = formatRupiah(subtotal);
        document.getElementById('grand-total').textContent = formatRupiah(subtotal);
    }

    function animateElement(element) {
        element.style.transition = 'transform 0.2s ease';
        element.style.transform = 'scale(1.1)';
        setTimeout(() => {
            element.style.transform = 'scale(1)';
        }, 200);
    }

    document.getElementById('checkoutForm').addEventListener('submit', function(e) {
        const hasAddress = {{ auth()->user()->addresses()->count() > 0 ? 'true' : 'false' }};

        if (!hasAddress) {
            e.preventDefault();
            showNotification('Tambahkan alamat pengiriman terlebih dahulu', 'warning');
            return;
        }

        const remainingItems = document.querySelectorAll('[id^="item-"]').length;
        if (remainingItems === 0) {
            e.preventDefault();
            showNotification('Tidak ada item yang dipesan', 'warning');
            return;
        }

        const removedInput = document.createElement('input');
        removedInput.type = 'hidden';
        removedInput.name = 'removed_items';
        removedInput.value = JSON.stringify(Array.from(removedItems));
        this.appendChild(removedInput);
    });

    function showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `fixed top-4 right-4 z-50 px-6 py-3 rounded-lg shadow-lg flex items-center gap-3 ${
            type === 'success' ? 'bg-green-500' : 
            type === 'error' ? 'bg-red-500' : 
            type === 'warning' ? 'bg-yellow-500' : 'bg-blue-500'
        } text-white`;

        notification.innerHTML = message;
        document.body.appendChild(notification);

        setTimeout(() => notification.remove(), 3000);
    }

    // 🔥 PENTING BANGET: biar total langsung bener pas load
    document.addEventListener('DOMContentLoaded', function() {
        updateTotals();
    });
</script>
</x-app-layout>