<x-app-layout>
    <x-slot name="header">
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
            <div class="flex items-center">
                <div class="gradient-primary w-1 h-6 sm:h-8 rounded-full mr-3"></div>
                <h2 class="text-xl sm:text-2xl font-bold text-slate-800 flex items-center gap-2">
                    <i class="fas fa-shopping-cart text-amber-600"></i>
                    {{ __('Keranjang Belanja') }}
                </h2>
            </div>
            <a href="{{ route('product.index') }}"
                class="inline-flex items-center justify-center px-6 py-3 bg-stone-100 hover:bg-stone-200 text-stone-700 font-medium rounded-xl border border-stone-200 transition-all duration-200">
                <i class="fas fa-arrow-left text-xs"></i>
                <span>Lanjut Belanja</span>
            </a>
        </div>
    </x-slot>

    <div class="space-y-6 lg:space-y-8">


        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 lg:gap-8">

            {{-- CART LIST --}}
            <div class="lg:col-span-2 space-y-4">
                <div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">

                    {{-- HEADER --}}
                    @if($carts->count() > 0)
                    <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 px-4 sm:px-6 py-4 border-b border-slate-200 bg-gradient-to-r from-slate-50 to-white">
                        <label class="flex items-center gap-3 cursor-pointer group">
                            <input id="select-all" type="checkbox"
                                class="w-4 h-4 text-amber-600 bg-white border-slate-300 rounded focus:ring-2 focus:ring-amber-500">
                            <span class="text-sm font-medium text-slate-700 group-hover:text-amber-600 transition-colors">
                                <i class="fas fa-check-double mr-2 text-xs"></i>
                                Pilih Semua
                            </span>
                        </label>

                        <button id="delete-selected" disabled
                            class="inline-flex items-center justify-center gap-2 px-4 py-2 text-sm text-white bg-gradient-to-r from-rose-500 to-rose-600 hover:from-rose-600 hover:to-rose-700 rounded-xl shadow-md hover:shadow-lg transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:shadow-none min-w-[130px]">
                            <i class="fas fa-trash-alt"></i>
                            <span>Hapus Terpilih</span>
                            <span id="selected-count-badge" class="px-1.5 py-0.5 bg-white/20 rounded-full text-xs font-bold hidden">0</span>
                        </button>
                    </div>
                    @endif

                    {{-- ITEMS --}}
                    <div id="cart-items" class="divide-y divide-slate-100">
                        @forelse ($carts as $cart)
                        <div id="cart-item-{{ $cart->cart_id }}"
                            class="flex flex-col sm:flex-row sm:items-start gap-4 p-4 sm:p-6 hover:bg-slate-50 transition-colors group">

                            {{-- CHECKBOX & IMAGE --}}
                            <div class="flex items-start gap-4">
                                <div class="pt-1">
                                    <input type="checkbox"
                                        class="cart-checkbox w-4 h-4 text-amber-600 bg-white border-slate-300 rounded focus:ring-2 focus:ring-amber-500"
                                        data-cart-id="{{ $cart->cart_id }}"
                                        data-price="{{ $cart->product->price }}"
                                        data-qty="{{ $cart->quantity }}">
                                </div>

                                {{-- IMAGE --}}
                                <div class="flex-shrink-0">
                                    <div class="w-20 h-20 sm:w-24 sm:h-24 bg-gradient-to-br from-slate-100 to-amber-50 rounded-xl overflow-hidden border border-slate-200 shadow-sm">
                                        @php
                                        $productImage = $cart->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="{{ $cart->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-amber-300"></i>
                                        </div>
                                        @endif
                                    </div>
                                </div>
                            </div>

                            {{-- INFO --}}
                            <div class="flex-1 min-w-0">
                                <div class="flex flex-col sm:flex-row sm:items-start justify-between gap-3">
                                    <div class="flex-1">
                                        <h4 class="font-semibold text-slate-800 truncate max-w-xs sm:max-w-md">
                                            {{ $cart->product->product_name }}
                                        </h4>
                                        <p class="text-xs text-slate-500 mt-1 flex items-center gap-1">
                                            <i class="fas fa-tag text-[10px]"></i>
                                            {{ $cart->product->category->category_name ?? 'Uncategorized' }}
                                        </p>
                                    </div>

                                    {{-- DELETE SINGLE --}}
                                    <button type="button"
                                        onclick="openDeleteSingleModal('{{ $cart->cart_id }}', '{{ addslashes($cart->product->product_name) }}')"
                                        class="text-slate-400 hover:text-rose-600 transition-colors p-2 hover:bg-rose-50 rounded-full w-9 h-9 flex items-center justify-center"
                                        title="Hapus item">
                                        <i class="fas fa-trash-alt"></i>
                                    </button>
                                    <form id="delete-form-{{ $cart->cart_id }}" method="POST" action="{{ route('cart.destroy', $cart->cart_id) }}" style="display: none;">
                                        @csrf
                                        @method('DELETE')
                                    </form>
                                </div>

                                <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mt-3">
                                    <div>
                                        <p class="text-base sm:text-lg font-bold text-amber-600">
                                            Rp {{ number_format($cart->product->price, 0, ',', '.') }}
                                        </p>
                                        <p class="text-xs text-slate-500 mt-1 flex items-center gap-1">
                                            <i class="fas fa-cubes text-[10px]"></i>
                                            Stok: {{ $cart->product->stock ?? 'Tersedia' }}
                                        </p>
                                    </div>

                                    {{-- QUANTITY CONTROLS --}}
                                    <div class="flex items-center gap-2 bg-slate-50 rounded-xl p-1 border border-slate-200">
                                        <form action="{{ route('cart.decrease', $cart->cart_id) }}" method="POST" class="inline">
                                            @csrf
                                            <button type="submit"
                                                class="w-8 h-8 rounded-lg hover:bg-white flex items-center justify-center transition-colors text-slate-600 hover:text-amber-600"
                                                @if($cart->quantity <= 1) disabled @endif>
                                                    <i class="fas fa-minus text-sm"></i>
                                            </button>
                                        </form>

                                        <span class="w-10 text-center font-semibold text-slate-800">
                                            {{ $cart->quantity }}
                                        </span>

                                        <form action="{{ route('cart.increase', $cart->cart_id) }}" method="POST" class="inline">
                                            @csrf
                                            <button type="submit"
                                                class="w-8 h-8 rounded-lg hover:bg-white flex items-center justify-center transition-colors text-slate-600 hover:text-amber-600"
                                                @if($cart->product->stock && $cart->quantity >= $cart->product->stock) disabled @endif>
                                                <i class="fas fa-plus text-sm"></i>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>

                            {{-- SUBTOTAL --}}
                            <div class="flex-shrink-0 text-left sm:text-right pt-2 sm:pt-0 border-t sm:border-t-0 border-slate-100 mt-3 sm:mt-0">
                                <p class="text-xs text-slate-500 uppercase tracking-wider">Subtotal</p>
                                <p class="text-base sm:text-lg font-bold text-slate-800 mt-1">
                                    Rp {{ number_format($cart->product->price * $cart->quantity, 0, ',', '.') }}
                                </p>
                                <p class="text-xs text-slate-500 mt-1">
                                    <i class="fas fa-boxes mr-1"></i>
                                    {{ $cart->quantity }} item
                                </p>
                            </div>
                        </div>
                        @empty
                        {{-- EMPTY STATE --}}
                        <div class="py-12 sm:py-16 md:py-20 text-center">
                            <div class="w-24 h-24 sm:w-28 sm:h-28 md:w-32 md:h-32 mx-auto bg-gradient-to-br from-slate-100 to-slate-50 rounded-2xl flex items-center justify-center shadow-sm border border-slate-200 mb-4 sm:mb-6">
                                <i class="fas fa-shopping-cart text-4xl sm:text-5xl text-slate-400"></i>
                            </div>
                            <h3 class="text-lg sm:text-xl font-bold text-slate-800 mb-2">Keranjang Anda Kosong</h3>
                            <p class="text-sm text-slate-600 mb-6 max-w-sm mx-auto">
                                Belum ada produk di keranjang. Yuk, mulai belanja sekarang!
                            </p>
                            <a href="{{ route('product.index') }}"
                                class="inline-flex items-center justify-center gap-2 px-6 py-3 btn-primary text-sm font-medium rounded-xl shadow-md hover:shadow-lg transition-all duration-200 min-w-[140px]">
                                <i class="fas fa-shopping-bag"></i>
                                <span>Belanja Sekarang</span>
                            </a>
                        </div>
                        @endforelse
                    </div>
                </div>
            </div>

            {{-- SUMMARY --}}
            @if($carts->count() > 0)
            <div class="lg:col-span-1">
                <div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden sticky top-24">
                    <div class="p-5 sm:p-6">
                        <h3 class="text-base sm:text-lg font-bold text-slate-800 mb-5 flex items-center gap-2">
                            <i class="fas fa-receipt text-amber-600"></i>
                            Ringkasan Belanja
                        </h3>

                        <div class="space-y-4 text-sm">
                            <div class="flex justify-between items-center pb-3 border-b border-slate-200">
                                <span class="text-slate-600 flex items-center gap-2">
                                    <i class="fas fa-boxes text-slate-400"></i>
                                    Total Barang
                                </span>
                                <span id="cart-count" class="font-semibold text-slate-800 bg-slate-100 px-3 py-1 rounded-full text-sm">0</span>
                            </div>

                            <div class="flex justify-between items-center">
                                <span class="text-slate-600 flex items-center gap-2">
                                    <i class="fas fa-money-bill-wave text-slate-400"></i>
                                    Total Harga
                                </span>
                                <span id="cart-total" class="font-semibold text-slate-800">Rp 0</span>
                            </div>

                            <div class="flex justify-between items-center pt-3 mt-3 border-t-2 border-slate-200">
                                <span class="font-semibold text-slate-800 flex items-center gap-2">
                                    <i class="fas fa-calculator text-amber-600"></i>
                                    Total Belanja
                                </span>
                                <span id="cart-grand-total" class="text-lg sm:text-xl font-bold text-amber-600">Rp 0</span>
                            </div>
                        </div>

                        {{-- INFO ONGKIR --}}
                        <div class="mt-4 p-3 sm:p-4 bg-amber-50 rounded-xl border border-amber-100">
                            <p class="text-xs text-amber-700 flex items-start gap-2">
                                <i class="fas fa-truck mt-0.5"></i>
                                <span>Ongkos kirim akan dihitung saat checkout berdasarkan alamat pengiriman dan pilihan kurir.</span>
                            </p>
                        </div>

                        {{-- CHECKOUT FORM --}}
                        <form action="{{ route('cart.checkout') }}" method="POST" id="checkout-cart-form" class="mt-6">
                            @csrf
                            <input type="hidden" name="selected_items" id="selected-items" value="">

                            <button type="submit"
                                id="checkout-btn"
                                disabled
                                class="w-full py-3 sm:py-4 px-6 rounded-xl font-semibold btn-primary transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed shadow-md hover:shadow-lg flex items-center justify-center gap-2 min-h-[48px]">
                                <i class="fas fa-shopping-cart"></i>
                                <span id="checkout-text">Checkout (0)</span>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
            @endif
        </div>
    </div>


    <!-- Modal Hapus Item Keranjang -->
    <div id="deleteCartModal" class="fixed inset-0 z-[9999] hidden items-center justify-center bg-black/50 backdrop-blur-sm transition-all duration-300">
        <div class="bg-white rounded-2xl max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0 shadow-2xl" id="deleteCartModalContent">
            <div class="p-6">
                <!-- Icon & Title -->
                <div class="text-center mb-4">
                    <div class="mx-auto w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mb-3">
                        <svg class="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                        </svg>
                    </div>
                    <h3 class="text-xl font-bold text-slate-800" id="deleteModalTitle">Hapus Item</h3>
                </div>

                <!-- Pesan -->
                <p class="text-slate-500 text-center text-sm mb-2" id="deleteModalMessage">
                    Apakah Anda yakin ingin menghapus item ini dari keranjang?
                </p>
                <p class="text-center font-semibold text-slate-800 mb-6" id="deleteModalItemName"></p>

                <!-- Tombol -->
                <div class="flex gap-3">
                    <button
                        onclick="closeDeleteModal()"
                        class="flex-1 px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-semibold rounded-xl transition-all duration-200">
                        Batal
                    </button>
                    <button
                        id="confirmDeleteBtn"
                        class="flex-1 px-4 py-2.5 text-white text-sm font-semibold rounded-xl transition-all duration-200"
                        style="background: linear-gradient(135deg, #e11d48, #be123c);">
                        <i class="fas fa-trash-alt mr-1"></i> Hapus
                    </button>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const selectAll = document.getElementById('select-all');
            const checkboxes = document.querySelectorAll('.cart-checkbox');
            const cartTotal = document.getElementById('cart-total');
            const cartGrand = document.getElementById('cart-grand-total');
            const cartCount = document.getElementById('cart-count');
            const checkoutBtn = document.getElementById('checkout-btn');
            const checkoutText = document.getElementById('checkout-text');
            const deleteSelected = document.getElementById('delete-selected');
            const checkoutForm = document.getElementById('checkout-cart-form');
            const selectedItemsInput = document.getElementById('selected-items');
            const selectedCountBadge = document.getElementById('selected-count-badge');

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

            // Update Summary
            function updateSummary() {
                let total = 0;
                let count = 0;
                const selectedIds = [];

                checkboxes.forEach(cb => {
                    if (cb.checked) {
                        const price = parseInt(cb.dataset.price);
                        const qty = parseInt(cb.dataset.qty);
                        total += price * qty;
                        count++;
                        selectedIds.push(cb.dataset.cartId);
                    }
                });

                cartTotal.textContent = formatRupiah(total);
                cartGrand.textContent = formatRupiah(total);
                cartCount.textContent = count;

                if (checkoutText) {
                    checkoutText.innerHTML = `Checkout (${count})`;
                }

                if (selectedItemsInput) {
                    selectedItemsInput.value = JSON.stringify(selectedIds);
                }

                // Update button states
                if (checkoutBtn) {
                    checkoutBtn.disabled = count === 0;
                }

                if (deleteSelected) {
                    deleteSelected.disabled = count === 0;
                }

                if (selectedCountBadge) {
                    if (count > 0) {
                        selectedCountBadge.textContent = count;
                        selectedCountBadge.classList.remove('hidden');
                    } else {
                        selectedCountBadge.classList.add('hidden');
                    }
                }

                // Update select all checkbox
                if (selectAll && checkboxes.length > 0) {
                    const allChecked = Array.from(checkboxes).every(x => x.checked);
                    const someChecked = Array.from(checkboxes).some(x => x.checked);
                    selectAll.checked = allChecked;
                    selectAll.indeterminate = someChecked && !allChecked;
                }
            }

            // Select All
            if (selectAll) {
                selectAll.addEventListener('change', function() {
                    checkboxes.forEach(cb => cb.checked = this.checked);
                    updateSummary();
                });
            }

            // Individual Checkbox
            checkboxes.forEach(cb => {
                cb.addEventListener('change', function() {
                    updateSummary();
                });
            });

            // Modal Logic
            let deleteType = null;
            let currentDeleteId = null;
            let batchSelectedIds = [];

            window.openDeleteSingleModal = function(id, name) {
                deleteType = 'single';
                currentDeleteId = id;
                document.getElementById('deleteModalTitle').textContent = 'Hapus Item';
                document.getElementById('deleteModalMessage').textContent = 'Apakah Anda yakin ingin menghapus item ini dari keranjang?';
                document.getElementById('deleteModalItemName').textContent = name;
                openModal();
            };

            function openBatchDeleteModal(ids, count) {
                deleteType = 'batch';
                batchSelectedIds = ids;
                document.getElementById('deleteModalTitle').textContent = 'Hapus Multiple Item';
                document.getElementById('deleteModalMessage').textContent = 'Apakah Anda yakin ingin menghapus item terpilih dari keranjang?';
                document.getElementById('deleteModalItemName').textContent = count + ' Item akan dihapus';
                openModal();
            }

            function openModal() {
                const modal = document.getElementById('deleteCartModal');
                const modalContent = document.getElementById('deleteCartModalContent');

                modal.classList.remove('hidden');
                modal.classList.add('flex');

                void modal.offsetHeight;

                setTimeout(() => {
                    modalContent.classList.remove('scale-95', 'opacity-0');
                    modalContent.classList.add('scale-100', 'opacity-100');
                }, 10);

                document.body.style.overflow = 'hidden';
            }

            window.closeDeleteModal = function() {
                const modal = document.getElementById('deleteCartModal');
                const modalContent = document.getElementById('deleteCartModalContent');

                modalContent.classList.remove('scale-100', 'opacity-100');
                modalContent.classList.add('scale-95', 'opacity-0');

                setTimeout(() => {
                    modal.classList.remove('flex');
                    modal.classList.add('hidden');
                    document.body.style.overflow = '';
                    deleteType = null;
                    currentDeleteId = null;
                    batchSelectedIds = [];
                }, 300);
            };

            document.getElementById('confirmDeleteBtn').addEventListener('click', async function() {
                if (deleteType === 'single' && currentDeleteId) {
                    document.getElementById('delete-form-' + currentDeleteId).submit();
                } else if (deleteType === 'batch' && batchSelectedIds.length > 0) {
                    const deleteBtn = document.getElementById('delete-selected');
                    const originalText = deleteBtn.innerHTML;

                    deleteBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i><span>Menghapus...</span>';
                    deleteBtn.disabled = true;
                    closeDeleteModal();

                    try {
                        const response = await fetch('{{ route("cart.batchDelete") }}', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                                'Accept': 'application/json'
                            },
                            body: JSON.stringify({
                                cart_ids: batchSelectedIds
                            })
                        });

                        const data = await response.json();

                        if (data.success) {
                            setTimeout(() => location.reload(), 500);
                        } else {
                            deleteBtn.innerHTML = originalText;
                            deleteBtn.disabled = false;
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        deleteBtn.innerHTML = originalText;
                        deleteBtn.disabled = false;
                    }
                }
            });

            // Close on click outside
            document.getElementById('deleteCartModal').addEventListener('click', function(e) {
                if (e.target === this) {
                    closeDeleteModal();
                }
            });

            // Close on Escape key
            document.addEventListener('keydown', function(e) {
                const modal = document.getElementById('deleteCartModal');
                if (e.key === 'Escape' && modal && modal.classList.contains('flex')) {
                    closeDeleteModal();
                }
            });

            // Delete Selected
            if (deleteSelected) {
                deleteSelected.addEventListener('click', function() {
                    const selectedIds = Array.from(checkboxes)
                        .filter(cb => cb.checked)
                        .map(cb => parseInt(cb.dataset.cartId));

                    if (selectedIds.length === 0) return;

                    openBatchDeleteModal(selectedIds, selectedIds.length);
                });
            }

            // Initial Update
            updateSummary();
        });
    </script>
    @endpush

    <style>
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .animate-fade-in {
            animation: fadeIn 0.3s ease-in-out;
        }

        /* Better button styling for all devices */
        button,
        a,
        [role="button"] {
            touch-action: manipulation;
            min-height: 44px;
            min-width: 44px;
        }

        /* Ensure all buttons have proper text */
        .btn-text {
            display: inline-block;
        }

        /* Responsive button text */
        @media (max-width: 640px) {

            button span,
            a span {
                font-size: 0.875rem;
            }
        }

        input,
        select,
        textarea {
            font-size: 16px !important;
        }
    </style>
</x-app-layout>