<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Keranjang Belanja - Raja Futsal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style>
        * { font-family: 'Inter', sans-serif; }

        .nav-link {
            transition: all 0.2s ease;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        .nav-link:hover { background-color: #fff7ed; color: #ea580c; }
        .active-nav { background-color: #fff7ed; color: #ea580c; font-weight: 600; }

        .cart-item-hover:hover {
            background-color: #f8fafc;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: linear-gradient(135deg, #f97316 0%, #ea580c 100%);
            transition: all 0.3s ease;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(249, 115, 22, 0.3);
        }

        .action-btn { transition: all 0.2s ease; }
        .action-btn:hover { transform: translateY(-2px); }

        .cart-empty-state { animation: fadeIn 0.5s ease; }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Tombol Qty */
        .qty-btn {
            width: 28px;
            height: 28px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.2s ease;
            border: none;
            outline: none;
        }
        .qty-btn-minus {
            background-color: #fee2e2;
            color: #dc2626;
        }
        .qty-btn-minus:hover {
            background-color: #fca5a5;
            transform: scale(1.1);
        }
        .qty-btn-plus {
            background-color: #dcfce7;
            color: #16a34a;
        }
        .qty-btn-plus:hover {
            background-color: #86efac;
            transform: scale(1.1);
        }
        .qty-btn:disabled {
            opacity: 0.4;
            cursor: not-allowed;
            transform: none !important;
        }
        .qty-value {
            min-width: 36px;
            text-align: center;
            font-weight: 700;
            font-size: 15px;
            color: #1f2937;
        }
        .qty-loading {
            animation: spin 0.6s linear infinite;
        }
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
    </style>
</head>

<body class="bg-gray-50 min-h-screen" data-no-image="{{ asset('images/no-image.png') }}">

    <!-- NAVBAR -->
    <nav class="bg-white/80 backdrop-blur-md border-b shadow-sm sticky top-0 z-50 w-full">
        <div class="px-4 sm:px-6 lg:px-8 py-3">
            <div class="relative flex flex-col md:flex-row md:items-center md:justify-between">
                <div class="flex items-center gap-3 mb-3 md:mb-0">
                    <div class="w-10 h-10 bg-gradient-to-br from-orange-500 to-orange-600 rounded-lg flex items-center justify-center shadow-md">
                        <span class="text-white font-bold text-lg">R</span>
                    </div>
                    <div>
                        <h1 class="font-bold text-lg text-gray-800">Raja Futsal</h1>
                        <p class="text-xs text-gray-500">Keranjang Belanja</p>
                    </div>
                </div>

                <div class="hidden md:flex flex-wrap items-center gap-3 absolute left-1/2 transform -translate-x-1/2">

                    <a href="{{ route('dashboard') }}"
                        class="flex items-center gap-2 px-4 py-2 rounded-lg
                        {{ request()->routeIs('dashboard') ? 'bg-orange-100 text-orange-600' : 'text-gray-600 hover:bg-orange-50 hover:text-orange-600' }}
                        transition">
                        <i class="fas fa-home"></i> Dashboard
                    </a>

                    <a href="{{ route('produk.index') }}"
                        class="flex items-center gap-2 px-4 py-2 rounded-lg
                        {{ request()->routeIs('produk.*') ? 'bg-orange-100 text-orange-600' : 'text-gray-600 hover:bg-orange-50 hover:text-orange-600' }}
                        transition">
                        <i class="fas fa-store"></i> Produk
                    </a>


                    <a href="{{ route('keranjang.index') }}"
                            class="flex items-center gap-2 px-4 py-2 rounded-xl font-medium transition
                            {{ request()->routeIs('keranjang.*') ? 'bg-orange-50 text-orange-600 border border-orange-100' : 'text-gray-600 hover:bg-orange-50 hover:text-orange-600' }}">
                        <i class="fas fa-shopping-cart"></i> Keranjang
                    </a>

                    <a href="{{ route('pesanan.index') }}"
                        class="flex items-center gap-2 px-4 py-2 rounded-lg
                        {{ request()->routeIs('pesanan.*') ? 'bg-orange-100 text-orange-600' : 'text-gray-600 hover:bg-orange-50 hover:text-orange-600' }}
                        transition">
                        <i class="fas fa-clipboard-list"></i> Pesanan
                    </a>

                </div>



                <div class="flex items-center gap-4 mt-3 md:mt-0">
                    <!-- CART & CHAT NOTIF FOR USER -->
                    @if(auth()->check() && auth()->user()->role === 'user')
                        <!-- Cart Icon -->
                        <a href="{{ route('keranjang.index') }}" class="relative p-2 text-gray-500 hover:text-orange-600 transition-all duration-200 focus:outline-none bg-gray-50 hover:bg-orange-50 rounded-xl border border-transparent hover:border-orange-100 flex items-center justify-center">
                            <i class="fas fa-shopping-cart text-xl"></i>
                            @if(isset($cartCount) && $cartCount > 0)
                                <span class="absolute top-1.5 right-1.5 flex h-4 w-4">
                                    <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>
                                    <span class="relative inline-flex rounded-full h-4 w-4 bg-red-500 text-white text-[10px] items-center justify-center font-bold">
                                        {{ $cartCount > 99 ? '99+' : $cartCount }}
                                    </span>
                                </span>
                            @endif
                        </a>

                        <!-- Chat Icon -->
                        <a href="{{ route('chat.index') }}" class="relative p-2 text-gray-500 hover:text-orange-600 transition-all duration-200 focus:outline-none bg-gray-50 hover:bg-orange-50 rounded-xl border border-transparent hover:border-orange-100 flex items-center justify-center">
                            <i class="fas fa-comments text-xl"></i>
                            @if(isset($unreadChatCount) && $unreadChatCount > 0)
                                <span class="absolute top-1.5 right-1.5 flex h-4 w-4">
                                    <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>
                                    <span class="relative inline-flex rounded-full h-4 w-4 bg-red-500 text-white text-[10px] items-center justify-center font-bold">
                                        {{ $unreadChatCount > 99 ? '99+' : $unreadChatCount }}
                                    </span>
                                </span>
                            @endif
                        </a>

                        <!-- NOTIF BELL FOR USER -->
                        <div class="relative">
                            <button id="notifButtonUser" onclick="toggleNotifDropdown(event)" class="relative p-2 text-gray-500 hover:text-orange-600 transition-all duration-200 focus:outline-none bg-gray-50 hover:bg-orange-50 rounded-xl border border-transparent hover:border-orange-100">
                                <i class="fas fa-bell text-xl"></i>
                                @if($unreadReviews->count() > 0)
                                    <span class="absolute top-1.5 right-1.5 flex h-4 w-4">
                                        <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>
                                        <span class="relative inline-flex rounded-full h-4 w-4 bg-red-500 text-white text-[10px] items-center justify-center font-bold">
                                            {{ $unreadReviews->count() }}
                                        </span>
                                    </span>
                                @endif
                            </button>
                            <!-- Dropdown Notif -->
                            <div id="notifDropdownUser" class="hidden absolute right-0 mt-3 w-80 bg-white rounded-2xl shadow-2xl border border-gray-100 py-0 z-50 overflow-hidden">
                                <div class="px-4 py-4 border-b bg-gradient-to-r from-orange-50 to-white">
                                    <h3 class="text-sm font-bold text-gray-800 flex items-center gap-2">
                                        <i class="fas fa-bell text-orange-500"></i> Notifikasi
                                    </h3>
                                </div>
                                <div class="max-h-[400px] overflow-y-auto custom-scrollbar">
                                    @forelse($unreadReviews as $item)
                                        <a href="{{ route('pesanan.show', $item['pesanan_id']) }}?review_produk={{ $item['produk_id'] }}" class="block px-4 py-4 border-b last:border-0 hover:bg-orange-50 transition border-gray-50">
                                            <div class="flex gap-3 items-start">
                                                <div class="w-12 h-12 rounded-xl bg-gray-50 flex-shrink-0 overflow-hidden border border-gray-100">
                                                    <img src="{{ $item['foto'] ? asset('storage/'.$item['foto']) : asset('images/no-image.png') }}" class="w-full h-full object-cover">
                                                </div>
                                                <div class="flex-1 min-w-0">
                                                    <p class="text-xs font-bold text-orange-600 mb-1 uppercase tracking-wider">Silahkan mengulas produk ini</p>
                                                    <p class="text-sm text-gray-800 font-semibold line-clamp-2 leading-snug mb-2">{{ $item['nama_produk'] }}</p>
                                                    <div class="flex items-center justify-between">
                                                        <p class="text-[10px] text-gray-400 flex items-center gap-1">
                                                            <i class="fas fa-receipt text-[9px]"></i> {{ $item['kode_pesanan'] }}
                                                        </p>
                                                        <span class="text-[10px] bg-orange-100 text-orange-600 px-2 py-0.5 rounded-full font-bold">BELUM DIULAS</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </a>
                                    @empty
                                        <div class="px-6 py-10 text-center">
                                            <div class="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4 border border-gray-100">
                                                <i class="fas fa-bell-slash text-gray-300 text-2xl"></i>
                                            </div>
                                            <p class="text-sm text-gray-500 font-bold">Tidak ada notifikasi baru</p>
                                            <p class="text-xs text-gray-400 mt-2 px-10">Semua produk yang Anda beli sudah diulas. Terima kasih!</p>
                                        </div>
                                    @endforelse
                                </div>
                                @if($unreadReviews->count() > 0)
                                    <div class="px-4 py-3 bg-gray-50 text-center border-t border-gray-100">
                                        <p class="text-[10px] text-gray-400 italic">* Klik pada notifikasi untuk memberikan ulasan</p>
                                    </div>
                                @endif
                            </div>
                        </div>
                    @endif

                    @if(Auth::user()->role == 'penjual')
                    <div class="relative" id="notifWrapper">
                        <button onclick="toggleNotif(event)" class="relative p-2.5 text-gray-600 hover:text-orange-600 hover:bg-orange-50 rounded-full transition-all duration-200">
                            <i class="fas fa-bell text-lg"></i>
                            <span id="notifBadge" class="absolute top-1 right-1 w-4 h-4 bg-red-500 rounded-full text-white text-xs hidden items-center justify-center font-bold">0</span>
                        </button>
                        <div id="notifDropdown" class="hidden absolute right-0 mt-2 w-80 bg-white rounded-xl shadow-2xl border border-gray-100 z-50 overflow-hidden" style="animation: fadeInDown 0.2s ease">
                            <div class="bg-gradient-to-r from-orange-500 to-orange-600 px-4 py-3 flex items-center justify-between">
                                <span class="text-white font-semibold text-sm flex items-center gap-2"><i class="fas fa-exclamation-triangle"></i> Stok Hampir Habis</span>
                                <a href="{{ route('restok.index') }}" class="text-white/80 hover:text-white text-xs underline">Kelola Restok →</a>
                            </div>
                            <div id="notifList" class="max-h-72 overflow-y-auto divide-y divide-gray-50">
                                <div class="px-4 py-5 text-center text-gray-400 text-sm"><i class="fas fa-spinner fa-spin mr-2"></i> Memuat...</div>
                            </div>
                        </div>
                    </div>
                    @endif

                    <div class="relative" id="userDropdown">
                        <button onclick="toggleUserDropdown(event)" class="flex items-center gap-3 px-3 py-2 hover:bg-orange-50 rounded-xl transition-all duration-200 border border-transparent hover:border-orange-200 group">
                            <div class="w-9 h-9 bg-gradient-to-br from-orange-500 to-orange-600 rounded-full flex items-center justify-center text-white font-semibold shadow-md">
                                {{ substr(Auth::user()->name, 0, 1) }}
                            </div>
                            <div class="hidden md:block text-left">
                                <p class="text-sm font-medium text-gray-700 group-hover:text-orange-600">{{ Auth::user()->name }}</p>
                                <p class="text-xs text-gray-500">
                                    @if(Auth::user()->role == 'penjual') <i class="fas fa-store mr-1 text-orange-500"></i> Penjual
                                    @elseif(Auth::user()->role == 'admin') <i class="fas fa-shield-alt mr-1 text-purple-500"></i> Admin
                                    @else <i class="fas fa-user mr-1 text-blue-500"></i> Customer @endif
                                </p>
                            </div>
                            <i class="fas fa-chevron-down text-sm text-gray-400 group-hover:text-orange-600 transition-transform duration-200" id="dropdownIcon"></i>
                        </button>

                        <div id="dropdownMenu" class="hidden absolute right-0 mt-2 w-64 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50">
                            <div class="px-4 py-4 border-b border-gray-100">
                                <div class="flex items-center gap-3">
                                    <div class="w-12 h-12 bg-gradient-to-br from-orange-500 to-orange-600 rounded-full flex items-center justify-center text-white font-bold text-xl shadow-md">
                                        {{ substr(Auth::user()->name, 0, 1) }}
                                    </div>
                                    <div>
                                        <p class="font-semibold text-gray-800">{{ Auth::user()->name }}</p>
                                        <p class="text-sm text-gray-500">{{ Auth::user()->email }}</p>
                                        <span class="inline-block mt-1 px-2 py-0.5 rounded-full text-xs font-medium @if(Auth::user()->role == 'penjual') bg-orange-100 text-orange-600 @elseif(Auth::user()->role == 'admin') bg-purple-100 text-purple-600 @else bg-blue-100 text-blue-600 @endif">
                                            @if(Auth::user()->role == 'penjual') <i class="fas fa-store mr-1"></i> Penjual
                                            @elseif(Auth::user()->role == 'admin') <i class="fas fa-shield-alt mr-1"></i> Admin
                                            @else <i class="fas fa-user mr-1"></i> Customer @endif
                                        </span>
                                    </div>
                                </div>
                            </div>

                            @if(Auth::user()->role == 'penjual')
                                @php $toko = App\Models\Toko::where('user_id', auth()->id())->first(); @endphp
                                @if($toko)
                                    <a href="{{ route('toko.edit', $toko->id) }}" class="flex items-center gap-3 px-4 py-3 hover:bg-orange-50 text-gray-700 transition group">
                                        <div class="w-8 h-8 bg-orange-100 rounded-lg flex items-center justify-center group-hover:bg-orange-200"><i class="fas fa-store text-orange-600"></i></div>
                                        <div><p class="font-medium">Pengaturan Toko</p><p class="text-xs text-gray-500">Kelola informasi toko Anda</p></div>
                                    </a>
                                @else
                                    <a href="{{ route('toko.create') }}" class="flex items-center gap-3 px-4 py-3 hover:bg-orange-50 text-gray-700 transition group">
                                        <div class="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center group-hover:bg-green-200"><i class="fas fa-store-alt text-green-600"></i></div>
                                        <div><p class="font-medium">Buka Toko</p><p class="text-xs text-gray-500">Mulai berjualan sekarang</p></div>
                                    </a>
                                @endif
                            @else
                                <a href="{{ route('profile.edit') }}" class="flex items-center gap-3 px-4 py-3 hover:bg-orange-50 text-gray-700 transition group">
                                    <div class="w-8 h-8 bg-gray-100 rounded-lg flex items-center justify-center group-hover:bg-orange-100"><i class="fas fa-user text-gray-500 group-hover:text-orange-600"></i></div>
                                    <div><p class="font-medium">Profil Saya</p><p class="text-xs text-gray-500">Lihat dan edit profil</p></div>
                                </a>
                            @endif

                            <div class="border-t border-gray-100 mt-1 pt-1">
                                <form method="POST" action="{{ route('logout') }}">
                                    @csrf
                                    <button type="submit" class="w-full flex items-center gap-3 px-4 py-3 hover:bg-red-50 text-red-600 transition group">
                                        <div class="w-8 h-8 bg-red-50 rounded-lg flex items-center justify-center group-hover:bg-red-100"><i class="fas fa-sign-out-alt text-red-500"></i></div>
                                        <div class="text-left"><p class="font-medium">Keluar</p><p class="text-xs text-red-400">Akhiri sesi</p></div>
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <!-- KONTEN UTAMA -->
    <div class="w-full px-4 sm:px-6 lg:px-8 py-6">

        <!-- TOAST NOTIFICATION -->
        @if (session('success') || session('error') || session('warning'))
        <div id="toast-notification"
            class="fixed bottom-6 right-6 z-50 flex items-center gap-3 bg-white border {{ session('success') ? 'border-green-200' : (session('warning') ? 'border-yellow-200' : 'border-red-200') }} shadow-2xl rounded-2xl px-5 py-4 max-w-sm w-full"
            style="animation: slideInRight 0.4s ease;">
            <div class="w-10 h-10 {{ session('success') ? 'bg-green-500' : (session('warning') ? 'bg-yellow-500' : 'bg-red-500') }} rounded-xl flex items-center justify-center flex-shrink-0">
                <i class="fas {{ session('success') ? 'fa-check' : (session('warning') ? 'fa-exclamation-triangle' : 'fa-exclamation') }} text-white text-sm"></i>
            </div>
            <div class="flex-1 min-w-0">
                <p class="toast-title font-semibold text-gray-800 text-sm">
                    {{ session('success') ? 'Berhasil!' : (session('warning') ? 'Peringatan!' : 'Gagal!') }}
                </p>
                <p class="toast-message text-gray-500 text-xs mt-0.5 truncate">
                    {{ session('success') ?? (session('warning') ?? session('error')) }}
                </p>
            </div>
            <button onclick="closeToast()" class="text-gray-400 hover:text-gray-600 flex-shrink-0 ml-1">
                <i class="fas fa-times text-xs"></i>
            </button>
            <div class="absolute bottom-0 left-0 h-1 {{ session('success') ? 'bg-green-500' : (session('warning') ? 'bg-yellow-500' : 'bg-red-500') }} rounded-b-2xl" id="toastProgress"
                style="width: 100%; transition: width 5s linear;"></div>
        </div>

        <style>
        @keyframes slideInRight {
            from { opacity: 0; transform: translateX(100px); }
            to   { opacity: 1; transform: translateX(0); }
        }
        @keyframes slideOutRight {
            from { opacity: 1; transform: translateX(0); }
            to   { opacity: 0; transform: translateX(100px); }
        }
        </style>

        <script>
            setTimeout(() => {
                const bar = document.getElementById('toastProgress');
                if (bar) bar.style.width = '0%';
            }, 100);
            setTimeout(() => closeToast(), 5100);
            function closeToast() {
                const toast = document.getElementById('toast-notification');
                if (toast) {
                    toast.style.animation = 'slideOutRight 0.3s ease forwards';
                    setTimeout(() => toast.remove(), 300);
                }
            }
        </script>
        @endif

       <!-- HEADER CARD - KERANJANG BELANJA -->
<div class="relative mb-8 overflow-hidden rounded-2xl bg-gradient-to-r from-orange-500 via-orange-600 to-orange-700 p-6 text-white shadow-xl w-full">
    {{-- Background Decorations --}}
    <div class="absolute top-0 right-0 w-64 h-64 opacity-10">
        <i class="fas fa-shopping-cart text-8xl absolute top-10 right-10"></i>
        <i class="fas fa-bag-shopping text-7xl absolute bottom-0 right-32"></i>
        <i class="fas fa-tag text-6xl absolute top-20 right-48"></i>
    </div>
    <div class="absolute bottom-0 left-0 w-48 h-48 bg-white opacity-5 rounded-full -ml-16 -mb-16"></div>
    
    <div class="relative flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        {{-- Left Section --}}
        <div>
            <div class="flex items-center gap-3 mb-2">
                <div class="w-12 h-12 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center shadow-inner border border-white/30">
                    <i class="fas fa-shopping-cart text-white text-2xl"></i>
                </div>
                <h2 class="text-2xl font-bold text-white">Keranjang Belanja</h2>
            </div>
            <p class="text-orange-100 text-sm ml-[60px]">Kelola produk dalam keranjang belanja Anda</p>
        </div>
        
        {{-- Right Section - Stats --}}
        @if(isset($keranjang) && count($keranjang) > 0)
        <div class="flex-shrink-0 flex items-center gap-3 flex-wrap">
            <div class="bg-white/20 backdrop-blur-sm px-4 py-2 rounded-xl flex items-center gap-2">
                <i class="fas fa-shopping-bag text-orange-200"></i>
                <span class="text-orange-100 text-sm">Item:</span>
                <span class="font-bold text-white text-lg">{{ count($keranjang) }}</span>
            </div>
        </div>
        @else
        <div class="flex-shrink-0">
            <span class="bg-white/20 backdrop-blur-sm px-4 py-2 rounded-xl text-sm font-medium flex items-center gap-2">
                <i class="fas fa-box-open"></i> Keranjang Kosong
            </span>
        </div>
        @endif
    </div>
</div>

        @if(!isset($keranjang) || count($keranjang) === 0)
            <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-12 text-center cart-empty-state w-full">
                <div class="mx-auto w-24 h-24 bg-orange-50 rounded-full flex items-center justify-center mb-6">
                    <i class="fas fa-shopping-cart text-orange-400 text-3xl"></i>
                </div>
                <h3 class="text-xl font-bold text-gray-800 mb-3">Keranjang Anda Kosong</h3>
                <p class="text-gray-500 mb-8 max-w-md mx-auto">
                    Anda belum menambahkan produk ke dalam keranjang belanja. Mulai belanja sekarang!
                </p>
                <div class="flex flex-col sm:flex-row gap-4 justify-center">
                    <a href="{{ route('produk.index') }}"
                       class="btn-primary text-white px-8 py-3 rounded-lg font-semibold inline-flex items-center justify-center gap-2 action-btn">
                        <i class="fas fa-shopping-bag"></i> Mulai Belanja
                    </a>
                    <a href="{{ route('dashboard') }}"
                       class="px-8 py-3 rounded-lg font-semibold border border-gray-300 text-gray-700 hover:bg-gray-50 inline-flex items-center justify-center gap-2 transition">
                        <i class="fas fa-home"></i> Ke Dashboard
                    </a>
                </div>
            </div>
        @else
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 w-full">

                <!-- CART ITEMS -->
                <div class="lg:col-span-2">
                    <div class="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
                        <div class="px-6 py-4 border-b border-gray-100 bg-gradient-to-r from-orange-50 to-white flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-shopping-cart text-orange-600"></i>
                                </div>
                                <div>
                                    <h3 class="font-bold text-gray-800 flex items-center gap-2">
                                        <i class="fas fa-list"></i> Produk dalam Keranjang
                                    </h3>
                                    <p class="text-sm text-gray-500">{{ count($keranjang) }} item</p>
                                </div>
                            </div>
                            <div class="flex flex-col sm:flex-row items-start sm:items-center gap-3 w-full sm:w-auto">
                                <label class="flex items-center gap-2 text-sm">
                                    <input type="checkbox" id="selectAll" checked class="w-4 h-4 text-orange-600 rounded border-gray-300 focus:ring-orange-500">
                                    <span>Pilih Semua</span>
                                </label>
                                <button id="deleteSelected"
                                        class="action-btn px-4 py-2 bg-red-100 text-red-700 rounded-lg font-medium text-sm hover:bg-red-200 flex items-center gap-2 transition w-full sm:w-auto justify-center">
                                    <i class="fas fa-trash"></i> Hapus Terpilih
                                </button>
                            </div>
                        </div>

                        <div class="overflow-x-auto">
                            <table class="w-full">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider w-12">
                                            <i class="fas fa-check-square"></i>
                                        </th>
                                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                                            <i class="fas fa-box mr-1"></i> Produk
                                        </th>
                                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider w-28">
                                            <i class="fas fa-tag mr-1"></i> Harga
                                        </th>
                                        <th class="px-4 py-3 text-center text-xs font-semibold text-gray-600 uppercase tracking-wider w-36">
                                            <i class="fas fa-sort-numeric-up mr-1"></i> Jumlah
                                        </th>
                                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider w-32">
                                            <i class="fas fa-calculator mr-1"></i> Subtotal
                                        </th>
                                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider w-16">
                                            <i class="fas fa-cog mr-1"></i>
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @forelse($keranjang as $item)
                                        @php
                                            $foto = null;
                                            $warnaItem = strtolower(trim($item->warna));

                                            if(!empty($item->produk->foto)){
                                                $allPhotos = explode('|', $item->produk->foto);
                                                
                                                foreach($allPhotos as $p) {
                                                    if(str_contains($p, ':')) {
                                                        $parts = explode(':', $p);
                                                        $warnaFoto = strtolower(trim($parts[0]));
                                                        $fileFoto = $parts[1];
                                                        
                                                        if($warnaFoto === $warnaItem) {
                                                            $foto = $fileFoto;
                                                            break;
                                                        }
                                                    }
                                                }

                                                if (!$foto) {
                                                    $first = $allPhotos[0];
                                                    $foto = str_contains($first, ':') ? explode(':', $first)[1] : $first;
                                                }
                                            }

                                            $hargaProduk = $item->produk->harga ?? 0;
                                            $namaProduk  = $item->produk->nama_produk ?? 'Produk Tidak Ditemukan';
                                            $subtotal    = $item->jumlah * $hargaProduk;
                                            $maxStok     = $item->produk->stok ?? 99;
                                        @endphp

                                        <tr class="cart-item cart-item-hover border-b border-gray-100"
                                            data-id="{{ $item->keranjang_id }}"
                                            data-produk-id="{{ $item->produk_id }}"
                                            data-jumlah="{{ $item->jumlah }}"
                                            data-harga="{{ $hargaProduk }}"
                                            data-max-stok="{{ $maxStok }}"
                                            data-warna="{{ $item->warna ?? '' }}"
                                            data-ukuran="{{ $item->ukuran ?? '' }}">

                                            <!-- CHECKBOX -->
                                            <td class="px-4 py-4">
                                                <input type="checkbox"
                                                       class="select-item w-4 h-4 text-orange-600 rounded border-gray-300 focus:ring-orange-500"
                                                       value="{{ $item->keranjang_id }}"
                                                       data-subtotal="{{ $subtotal }}"
                                                       checked>
                                            </td>

                                            <!-- PRODUK -->
                                            <td class="px-4 py-4">
                                                <div class="flex gap-3 items-center">
                                                    <div class="relative group flex-shrink-0">
                                                        <img src="{{ $foto ? asset('storage/'.$foto) : asset('images/no-image.png') }}"
                                                            onclick="openCartModal(this.src)"
                                                            class="w-16 h-16 border rounded-lg object-contain bg-gray-50 p-1 cursor-zoom-in transition-all duration-300 group-hover:shadow-md group-hover:border-orange-200"
                                                            alt="{{ $namaProduk }}"
                                                            onerror="imgError(this)">
                                                            <script>
                                                                function imgError(image) {
                                                                    image.onerror = null; 
                                                                    image.src = document.body.dataset.noImage;
                                                                }
                                                            </script>
                                                        
                                                        <div class="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
                                                            <i class="fas fa-search-plus text-orange-500 text-xs"></i>
                                                        </div>
                                                    </div>

                                                    <div class="flex flex-col">
                                                        <h4 class="font-semibold text-gray-800 text-sm leading-tight mb-1">
                                                            {{ $namaProduk }}
                                                        </h4>
                                                        
                                                        @if($item->warna || $item->ukuran)
                                                            <div class="flex gap-1.5 flex-wrap">
                                                                @if($item->warna)
                                                                    <span class="inline-flex items-center gap-1 px-2 py-0.5 bg-orange-50 text-orange-700 text-[10px] font-medium rounded-full border border-orange-100">
                                                                        <i class="fas fa-palette text-[9px]"></i> {{ $item->warna }}
                                                                    </span>
                                                                @endif
                                                                
                                                                @if($item->ukuran)
                                                                    <span class="inline-flex items-center gap-1 px-2 py-0.5 bg-blue-50 text-blue-700 text-[10px] font-medium rounded-full border border-blue-100">
                                                                        <i class="fas fa-ruler text-[9px]"></i> {{ $item->ukuran }}
                                                                    </span>
                                                                @endif
                                                            </div>
                                                        @endif
                                                    </div>
                                                </div>
                                            </td>

                                            <div id="cartImageModal" class="fixed inset-0 z-[9999] hidden bg-black/90 flex items-center justify-center p-4 backdrop-blur-sm">
                                                <button onclick="closeCartModal()" class="absolute top-6 right-6 text-white text-4xl hover:text-orange-500 transition-all z-[10000]">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                                
                                                <div class="relative max-w-4xl w-full flex justify-center">
                                                    <img id="cartModalImg" src="" class="max-w-full max-h-[85vh] object-contain rounded-lg shadow-2xl transition-transform duration-300">
                                                </div>
                                            </div>

                                            <script>
                                                function openCartModal(src) {
                                                    const modal = document.getElementById('cartImageModal');
                                                    const modalImg = document.getElementById('cartModalImg');
                                                    
                                                    modalImg.src = src;
                                                    modal.classList.remove('hidden');
                                                    document.body.style.overflow = 'hidden';
                                                }

                                                function closeCartModal() {
                                                    const modal = document.getElementById('cartImageModal');
                                                    modal.classList.add('hidden');
                                                    document.body.style.overflow = 'auto';
                                                }

                                                document.getElementById('cartImageModal').addEventListener('click', function(e) {
                                                    if (e.target === this) {
                                                        closeCartModal();
                                                    }
                                                });

                                                document.addEventListener('keydown', function(e) {
                                                    if (e.key === "Escape") {
                                                        closeCartModal();
                                                    }
                                                });
                                            </script>

                                            <!-- HARGA -->
                                            <td class="px-4 py-4">
                                                <div class="font-medium text-gray-800 text-sm">
                                                    Rp{{ number_format($hargaProduk,0,',','.') }}
                                                </div>
                                            </td>

                                            <!-- TOMBOL +/- JUMLAH -->
                                            <td class="px-4 py-4">
                                                <div class="flex items-center justify-center gap-1">
                                                    {{-- Tombol MINUS --}}
                                                    <button class="qty-btn qty-btn-minus btn-minus"
                                                            data-id="{{ $item->keranjang_id }}"
                                                            {{ $item->jumlah <= 1 ? 'disabled' : '' }}>
                                                        <i class="fas fa-minus text-xs"></i>
                                                    </button>

                                                    {{-- Tampilan jumlah --}}
                                                    <span class="qty-value qty-display-{{ $item->keranjang_id }}">
                                                        {{ $item->jumlah }}
                                                    </span>

                                                    {{-- Tombol PLUS --}}
                                                    <button class="qty-btn qty-btn-plus btn-plus"
                                                            data-id="{{ $item->keranjang_id }}"
                                                            {{ $item->jumlah >= $maxStok ? 'disabled' : '' }}>
                                                        <i class="fas fa-plus text-xs"></i>
                                                    </button>
                                                </div>
                                                <div class="text-center text-xs text-gray-400 mt-1">
                                                    Maks. {{ $maxStok }}
                                                </div>
                                            </td>

                                            <!-- SUBTOTAL -->
                                            <td class="px-4 py-4">
                                                <div class="font-bold text-orange-600 text-sm subtotal-cell subtotal-{{ $item->keranjang_id }}">
                                                    Rp{{ number_format($subtotal,0,',','.') }}
                                                </div>
                                            </td>

                                            <!-- HAPUS -->
                                            <td class="px-4 py-4">
                                                <button class="delete-single text-red-500 hover:text-red-700 transition p-2 hover:bg-red-50 rounded-lg"
                                                        data-id="{{ $item->keranjang_id }}">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    @empty
                                        <tr>
                                            <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                                                <i class="fas fa-shopping-cart text-4xl mb-3 text-gray-300 block"></i>
                                                <p>Keranjang belanja Anda kosong</p>
                                            </td>
                                        </tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- CHECKOUT SUMMARY -->
                <div class="lg:col-span-1">
                    <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-6 sticky top-24">
                        <div class="flex items-center gap-3 mb-6">
                            <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                                <i class="fas fa-receipt text-green-600"></i>
                            </div>
                            <h3 class="font-bold text-gray-800 flex items-center gap-2">
                                <i class="fas fa-file-invoice"></i> Ringkasan Pesanan
                            </h3>
                        </div>

                        @php
                            $tokoId = $keranjang->first()->produk->user_id ?? null;
                            $toko = $tokoId ? \App\Models\Toko::where('user_id', $tokoId)->first() : null;
                            
                            $minBelanjaDiskon = $toko->min_belanja ?? 0;
                            $diskonNominal = $toko->diskon_nominal ?? 0;
                            
                            $ongkir     = 15000;
                            
                            if ($diskonNominal > 0 && ($total ?? 0) >= $minBelanjaDiskon) {
                                $subtotalSetelahDiskon = ($total ?? 0) - $diskonNominal;
                                $statusDiskon = true;
                            } else {
                                $diskonNominal = 0;
                                $subtotalSetelahDiskon = $total ?? 0;
                                $statusDiskon = false;
                            }
                            
                            $totalBayar = $subtotalSetelahDiskon + $ongkir;
                        @endphp

                        <div class="space-y-4">
                            <div class="flex justify-between items-center">
                                <span class="text-gray-600 flex items-center gap-2">
                                    <i class="fas fa-shopping-bag text-gray-400"></i> Subtotal
                                </span>
                                <span id="subtotalDisplay" class="font-medium">
                                    Rp{{ number_format($total ?? 0, 0, ',', '.') }}
                                </span>
                            </div>

                            <!-- INFO MINIMAL BELANJA UNTUK DISKON -->
                            @if(!$statusDiskon && ($total ?? 0) > 0 && ($total ?? 0) < $minBelanjaDiskon)
                            <div class="bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-700" id="minBelanjaInfo">
                                <div class="flex items-start gap-2">
                                    <i class="fas fa-info-circle mt-0.5"></i>
                                    <div>
                                        <p class="font-medium">Belanja minimal Rp{{ number_format($minBelanjaDiskon, 0, ',', '.') }} dapat diskon Rp{{ number_format($diskonNominal > 0 ? $diskonNominal : ($toko->diskon_nominal ?? 0), 0, ',', '.') }}!</p>
                                        <p class="text-xs mt-1">Kurang Rp{{ number_format($minBelanjaDiskon - ($total ?? 0), 0, ',', '.') }} lagi</p>
                                    </div>
                                </div>
                            </div>
                            @endif

                            <!-- DISKON SECTION (hanya tampil jika memenuhi syarat) -->
                            @if($statusDiskon)
                            <div class="flex justify-between items-center text-green-600">
                                <span class="flex items-center gap-2">
                                    <i class="fas fa-tags"></i> Diskon Toko
                                </span>
                                <span id="diskonDisplay" class="font-semibold">
                                    -Rp{{ number_format($diskonNominal, 0, ',', '.') }} <!-- Otomatis 10.000 -->
                                </span>
                            </div>

                            <!-- SUBTOTAL AFTER DISCOUNT -->
                            <div class="flex justify-between items-center border-t border-dashed border-gray-200 pt-2">
                                <span class="text-gray-600 flex items-center gap-2">
                                    <i class="fas fa-calculator text-gray-400"></i> Subtotal Setelah Diskon
                                </span>
                                <span id="subtotalAfterDiskonDisplay" class="font-semibold text-orange-600">
                                    Rp{{ number_format($subtotalSetelahDiskon, 0, ',', '.') }}
                                </span>
                            </div>
                            @endif

                            <!-- PENGIRIMAN - HANYA TEXT INFO -->
                            <div class="flex flex-col space-y-2 bg-blue-50 p-3 rounded-lg">
                                <div class="flex items-start gap-2 text-blue-700">
                                    <i class="fas fa-truck mt-1"></i>
                                    <div>
                                        <p class="font-medium text-sm">Informasi Ongkos Kirim:</p>
                                        <p class="text-xs mt-1">• Ongkir dihitung dari jarak</p>
                                        <p class="text-xs">• Berat</p>
                                        <p class="text-xs">• Satu Pulau & Luar Pulau</p>
                                        <p class="text-xs text-blue-500 mt-1 italic">*Ongkir akan dihitung saat checkout</p>
                                    </div>
                                </div>
                            </div>

                            <div class="border-t border-gray-200 pt-4">
                                <div class="flex justify-between items-center text-lg font-bold">
                                    <span class="flex items-center gap-2">
                                        <i class="fas fa-calculator text-orange-500"></i> Total
                                    </span>
                                    <span id="totalDisplay" class="text-orange-600">
                                        Rp{{ number_format($totalBayar, 0, ',', '.') }}
                                    </span>
                                </div>
                            </div>

                            @php
                                $hasAlamatUtama = \App\Models\UserAlamat::where('user_id', auth()->id())
                                    ->where('alamat_utama', 1)->exists();
                            @endphp

                            @if(!$hasAlamatUtama)
                                <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-3 text-sm text-yellow-700">
                                    <div class="flex items-start gap-2">
                                        <i class="fas fa-exclamation-triangle mt-0.5"></i>
                                        <div>
                                            <p class="font-medium">Belum ada alamat utama</p>
                                            <p class="text-xs mt-1">Silakan tambahkan alamat utama terlebih dahulu</p>
                                            <a href="{{ route('user-alamat.create') }}" class="text-orange-600 hover:text-orange-700 font-medium text-xs mt-2 inline-block">
                                                <i class="fas fa-plus-circle mr-1"></i>Tambah Alamat
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            @endif

                            <form action="{{ route('produk.beli') }}" method="POST" id="checkoutForm"
                                  data-diskon-nominal="{{ $toko->diskon_nominal ?? 0 }}"
                                  data-min-belanja="{{ $toko->min_belanja ?? 0 }}">
                                @csrf
                                <div id="selectedProductsContainer"></div>
                                @if($hasAlamatUtama)
                                    <button type="submit" class="btn-primary w-full py-3 rounded-lg font-bold text-white">
                                        Checkout Sekarang
                                    </button>
                                @else
                                    <button type="button" disabled class="w-full py-3 rounded-lg font-bold text-white bg-gray-400 cursor-not-allowed">
                                        Checkout Sekarang
                                    </button>
                                @endif
                            </form>

                            <div class="mt-4 text-center">
                                <a href="{{ route('produk.index') }}"
                                class="text-orange-600 hover:text-orange-700 text-sm font-medium inline-flex items-center gap-2 transition">
                                    <i class="fas fa-arrow-left"></i> Lanjutkan Belanja
                                </a>
                            </div>

                            <div class="mt-6 pt-6 border-t border-gray-100">
                                <p class="text-sm text-gray-500 mb-3 flex items-center gap-2">
                                    <i class="fas fa-credit-card"></i> Metode Pembayaran
                                </p>
                                <div class="grid grid-cols-2 gap-2">
                                    <div class="border border-gray-200 rounded-lg p-2 text-center hover:border-orange-200 transition">
                                        <i class="fas fa-university text-green-500"></i>
                                        <p class="text-xs mt-1">Transfer</p>
                                    </div>
                                    <div class="border border-gray-200 rounded-lg p-2 text-center hover:border-orange-200 transition">
                                        <i class="fas fa-wallet text-purple-500"></i>
                                        <p class="text-xs mt-1">E-Wallet</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        @endif
    </div>

    <!-- DELETE CONFIRMATION MODAL -->
    <div id="deleteModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
        <div class="bg-white rounded-2xl p-6 max-w-md w-full mx-4 shadow-2xl">
            <div class="flex items-center gap-4 mb-4">
                <div class="w-14 h-14 bg-red-100 rounded-full flex items-center justify-center">
                    <i class="fas fa-exclamation-triangle text-red-600 text-2xl"></i>
                </div>
                <div>
                    <h3 class="font-bold text-gray-800 text-lg">Hapus Item?</h3>
                    <p class="text-gray-600 text-sm">Aksi ini tidak dapat dibatalkan</p>
                </div>
                <button onclick="closeDeleteModal()" class="ml-auto text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <p class="text-gray-700 mb-6" id="deleteModalText">
                Apakah Anda yakin ingin menghapus item ini dari keranjang?
            </p>
            <div class="flex justify-end gap-3">
                <button onclick="closeDeleteModal()"
                        class="px-5 py-2.5 text-gray-700 font-medium hover:bg-gray-100 rounded-lg transition border border-gray-300 flex items-center gap-2">
                    <i class="fas fa-times"></i> Batal
                </button>
                <button id="confirmDelete"
                        class="px-5 py-2.5 bg-red-600 text-white font-medium hover:bg-red-700 rounded-lg transition flex items-center gap-2 shadow-lg">
                    <i class="fas fa-trash"></i> Ya, Hapus
                </button>
            </div>
        </div>
    </div>

<script>
    // ============================================================
    // NOTIFIKASI DROPDOWN (USER)
    // ============================================================
    window.toggleNotifDropdown = function(event) {
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }
        const dropdown = document.getElementById('notifDropdownUser');
        if (dropdown) {
            dropdown.classList.toggle('hidden');
        }
        // Close user dropdown if open
        const userDropdown = document.getElementById('dropdownMenu');
        if (userDropdown) userDropdown.classList.add('hidden');
    };

    // ============================================================
    // USER DROPDOWN TOGGLE
    // ============================================================
    window.toggleUserDropdown = function(event) {
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }
        
        const dropdown = document.getElementById('dropdownMenu');
        const icon = document.getElementById('dropdownIcon');
        
        if (dropdown) {
            if (dropdown.classList.contains('hidden')) {
                dropdown.classList.remove('hidden');
                if (icon) icon.style.transform = 'rotate(180deg)';
            } else {
                dropdown.classList.add('hidden');
                if (icon) icon.style.transform = 'rotate(0deg)';
            }
        }
        // Close notif dropdown if open
        const notifDropdown = document.getElementById('notifDropdownUser');
        if (notifDropdown) notifDropdown.classList.add('hidden');
    };

    // Tutup dropdown saat klik di luar
    document.addEventListener('click', function(event) {
        const dropdown = document.getElementById('dropdownMenu');
        const userDropdown = document.getElementById('userDropdown');
        const notifDropdown = document.getElementById('notifDropdownUser');
        const notifButton = document.getElementById('notifButtonUser');
        
        if (dropdown && userDropdown && !userDropdown.contains(event.target)) {
            if (!dropdown.classList.contains('hidden')) {
                dropdown.classList.add('hidden');
                const icon = document.getElementById('dropdownIcon');
                if (icon) icon.style.transform = 'rotate(0deg)';
            }
        }

        if (notifDropdown && notifButton && !notifButton.contains(event.target) && !notifDropdown.contains(event.target)) {
            notifDropdown.classList.add('hidden');
        }
    });

    // ============================================================
    // NOTIFIKASI TOGGLE (untuk penjual/stok)
    // ============================================================
    function toggleNotif(event) {
        if (event) event.stopPropagation();
        const notifDropdown = document.getElementById('notifDropdown');
        if (notifDropdown) {
            notifDropdown.classList.toggle('hidden');
        }
    }

    // Tutup notifikasi penjual saat klik di luar
    document.addEventListener('click', function(event) {
        const notifDropdown = document.getElementById('notifDropdown');
        const notifWrapper = document.getElementById('notifWrapper');
        
        if (notifDropdown && notifWrapper && !notifWrapper.contains(event.target)) {
            if (!notifDropdown.classList.contains('hidden')) {
                notifDropdown.classList.add('hidden');
            }
        }
    });


    // ============================================================
    // VARIABEL GLOBAL
    // ============================================================
    var itemToDelete = null;
    var deleteType   = null;

    function closeDeleteModal() {
        document.getElementById('deleteModal').classList.add('hidden');
        document.getElementById('deleteModal').classList.remove('flex');
        itemToDelete = null;
        deleteType   = null;
    }

    // ============================================================
    // KERANJANG SCRIPT
    // ============================================================
    $(document).ready(function () {

        $.ajaxSetup({
            headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
        });

        // --------------------------------------------------------
        // AUTO DISMISS NOTIFIKASI 3 DETIK
        // --------------------------------------------------------
        setTimeout(function () {
            $('.notif-alert').fadeOut(500, function () { $(this).remove(); });
        }, 3000);

        // --------------------------------------------------------
        // FORMAT RUPIAH
        // --------------------------------------------------------
        function formatRupiah(angka) {
            return parseInt(angka).toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
        }

        // --------------------------------------------------------
        // UPDATE TOTAL (dari semua checkbox yang dicentang) DENGAN DISKON RP 10.000
        // SYARAT: Minimal belanja Rp 200.000
        // --------------------------------------------------------
        function updateTotal() {
            var subtotal = 0;
            $('.select-item:checked').each(function () {
                subtotal += parseInt($(this).data('subtotal') || 0);
            });

            // Nilai dari database via dataset — tidak hardcode & bebas error linting
            const cf = document.getElementById('checkoutForm');
            var diskonNominal    = parseInt(cf?.dataset.diskonNominal || 0);
            var minBelanjaDiskon = parseInt(cf?.dataset.minBelanja || 0);

            var subtotalSetelahDiskon = subtotal;
            var statusDiskon = false;

            if (diskonNominal > 0 && minBelanjaDiskon > 0 && subtotal >= minBelanjaDiskon) {
                subtotalSetelahDiskon = subtotal - diskonNominal;
                statusDiskon = true;
            }

            var total = subtotalSetelahDiskon;

            // Update subtotal
            $('#subtotalDisplay').text('Rp' + formatRupiah(subtotal));

            // Info minimal belanja
            if (statusDiskon || subtotal === 0) {
                $('#minBelanjaInfo').remove();
            } else if (!statusDiskon && subtotal > 0 && minBelanjaDiskon > 0 && subtotal < minBelanjaDiskon) {
                var kurang = minBelanjaDiskon - subtotal;
                var infoHtml = '<div class="bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-700" id="minBelanjaInfo">' +
                            '<div class="flex items-start gap-2">' +
                            '<i class="fas fa-info-circle mt-0.5"></i>' +
                            '<div>' +
                            '<p class="font-medium">Belanja minimal Rp{{ number_format($toko->min_belanja ?? 0, 0, ",", ".") }} dapat diskon Rp{{ number_format($toko->diskon_nominal ?? 0, 0, ",", ".") }}!</p>' +
                            '<p class="text-xs mt-1">Kurang Rp' + formatRupiah(kurang) + ' lagi</p>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                $('#minBelanjaInfo').remove();
                $('.space-y-4').prepend(infoHtml);
            }

            // Tampilkan / update / hapus baris diskon
            if (statusDiskon) {
                if ($('#diskonDisplay').length === 0) {
                    $('#minBelanjaInfo').remove();
                    var diskonHtml = '<div class="flex justify-between items-center text-green-600" id="diskonRow">' +
                                    '<span class="flex items-center gap-2">' +
                                    '<i class="fas fa-tags"></i> Diskon Toko' +
                                    '</span>' +
                                    '<span id="diskonDisplay" class="font-semibold">-Rp' + formatRupiah(diskonNominal) + '</span>' +
                                    '</div>' +
                                    '<div class="flex justify-between items-center border-t border-dashed border-gray-200 pt-2" id="subtotalAfterDiskonRow">' +
                                    '<span class="text-gray-600 flex items-center gap-2">' +
                                    '<i class="fas fa-calculator text-gray-400"></i> Subtotal Setelah Diskon' +
                                    '</span>' +
                                    '<span id="subtotalAfterDiskonDisplay" class="font-semibold text-orange-600">Rp' + formatRupiah(subtotalSetelahDiskon) + '</span>' +
                                    '</div>';
                    $('#diskonRow').remove();
                    $('#subtotalAfterDiskonRow').remove();
                    $('#subtotalDisplay').closest('.flex').after(diskonHtml);
                } else {
                    $('#diskonDisplay').html('-Rp' + formatRupiah(diskonNominal));
                    $('#subtotalAfterDiskonDisplay').text('Rp' + formatRupiah(subtotalSetelahDiskon));
                }
            } else {
                $('#diskonRow').remove();
                $('#subtotalAfterDiskonRow').remove();
            }

            // Update total
            $('#totalDisplay').text('Rp' + formatRupiah(total));
        }

        // --------------------------------------------------------
        // UPDATE FORM CHECKOUT
        // --------------------------------------------------------
        function updateCheckoutForm() {
            var selectedItems = [];
            $('.select-item:checked').each(function () {
                var row      = $(this).closest('tr');
                var produkId = row.data('produk-id');
                var jumlah   = parseInt(row.data('jumlah'));
                var warna    = row.data('warna')  || '';
                var ukuran   = row.data('ukuran') || '';
                if (produkId && jumlah) {
                    selectedItems.push({ produk_id: produkId, jumlah: jumlah, warna: warna, ukuran: ukuran });
                }
            });

            var container = $('#selectedProductsContainer');
            container.empty();
            selectedItems.forEach(function (item, index) {
                container.append(
                    '<input type="hidden" name="items[' + index + '][produk_id]" value="' + item.produk_id + '">' +
                    '<input type="hidden" name="items[' + index + '][jumlah]" value="' + item.jumlah + '">' +
                    '<input type="hidden" name="items[' + index + '][warna]" value="' + item.warna + '">' +
                    '<input type="hidden" name="items[' + index + '][ukuran]" value="' + item.ukuran + '">'
                );
            });
        }

        // --------------------------------------------------------
        // TOMBOL +/- JUMLAH
        // --------------------------------------------------------
        $(document).on('click', '.btn-minus, .btn-plus', function () {
            var btn       = $(this);
            var id        = btn.data('id');
            var row       = btn.closest('tr');
            var isMinus   = btn.hasClass('btn-minus');
            var maxStok   = parseInt(row.data('max-stok') || 99);
            var harga     = parseInt(row.data('harga') || 0);
            var jumlahNow = parseInt(row.data('jumlah') || 1);

            // Hitung jumlah baru
            var jumlahBaru = isMinus ? jumlahNow - 1 : jumlahNow + 1;

            // Validasi batas
            if (jumlahBaru < 1 || jumlahBaru > maxStok) return;

            // Disable kedua tombol sementara (mencegah klik ganda)
            row.find('.btn-minus, .btn-plus').prop('disabled', true);

            // Tampilkan loading di angka
            var displayEl = $('.qty-display-' + id);
            displayEl.html('<i class="fas fa-spinner qty-loading text-gray-400 text-xs"></i>');

            // Kirim AJAX ke server
            $.ajax({
                url:  '/keranjang/' + id,
                type: 'POST',
                data: { _method: 'PATCH', jumlah: jumlahBaru },
                success: function (response) {
                    // Update jumlah di row
                    row.data('jumlah', jumlahBaru);
                    displayEl.text(jumlahBaru);

                    // Update subtotal di row & checkbox
                    var subtotalBaru = harga * jumlahBaru;
                    $('.subtotal-' + id).text('Rp' + formatRupiah(subtotalBaru));
                    row.find('.select-item').data('subtotal', subtotalBaru);

                    // Update tombol minus/plus
                    row.find('.btn-minus').prop('disabled', jumlahBaru <= 1);
                    row.find('.btn-plus').prop('disabled', jumlahBaru >= maxStok);

                    // Recalculate total
                    updateTotal();
                    updateCheckoutForm();
                },
                error: function (xhr) {
                    // Kembalikan nilai lama jika error
                    displayEl.text(jumlahNow);
                    row.find('.btn-minus').prop('disabled', jumlahNow <= 1);
                    row.find('.btn-plus').prop('disabled', jumlahNow >= maxStok);
                    alert('Gagal mengubah jumlah: ' + (xhr.responseJSON ? xhr.responseJSON.message : 'Terjadi kesalahan'));
                }
            });
        });

        // --------------------------------------------------------
        // SELECT ALL
        // --------------------------------------------------------
        $('#selectAll').on('change', function () {
            $('.select-item').prop('checked', $(this).prop('checked'));
            updateTotal();
            updateCheckoutForm();
        });

        $(document).on('change', '.select-item', function () {
            var allChecked = ($('.select-item:checked').length === $('.select-item').length);
            $('#selectAll').prop('checked', allChecked);
            updateTotal();
            updateCheckoutForm();
        });

        // --------------------------------------------------------
        // HAPUS SATUAN
        // --------------------------------------------------------
        $(document).on('click', '.delete-single', function (e) {
            e.preventDefault();
            e.stopPropagation();

            deleteType   = 'single';
            itemToDelete = $(this).data('id');

            var productName = $(this).closest('tr').find('h4').text().trim() || 'produk ini';
            $('#deleteModalText').text('Apakah Anda yakin ingin menghapus "' + productName + '" dari keranjang?');
            $('#deleteModal').removeClass('hidden').addClass('flex');
        });

        // --------------------------------------------------------
        // HAPUS MULTIPLE
        // --------------------------------------------------------
        $('#deleteSelected').on('click', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var jumlahDipilih = $('.select-item:checked').length;
            if (jumlahDipilih === 0) {
                alert('Pilih setidaknya satu item untuk dihapus');
                return;
            }

            deleteType   = 'multiple';
            itemToDelete = null;
            $('#deleteModalText').text('Apakah Anda yakin ingin menghapus ' + jumlahDipilih + ' item dari keranjang?');
            $('#deleteModal').removeClass('hidden').addClass('flex');
        });

        // --------------------------------------------------------
        // KONFIRMASI HAPUS
        // --------------------------------------------------------
        $('#confirmDelete').off('click').on('click', function () {

            if (deleteType === 'single' && itemToDelete) {

                var idHapus = itemToDelete;
                closeDeleteModal();

                $.ajax({
                    url:  '/keranjang-hapus/' + idHapus,
                    type: 'POST',
                    success: function (response) {
                        if (response.success) {
                            $('button.delete-single[data-id="' + idHapus + '"]')
                                .closest('tr')
                                .fadeOut(300, function () {
                                    $(this).remove();
                                    if ($('.cart-item').length === 0) {
                                        location.reload();
                                    } else {
                                        updateTotal();
                                        updateCheckoutForm();
                                    }
                                });
                        } else {
                            alert('Gagal menghapus: ' + (response.message || ''));
                        }
                    },
                    error: function (xhr) {
                        console.error(xhr);
                        alert('Gagal: ' + (xhr.responseJSON ? xhr.responseJSON.message : 'Unknown error'));
                    }
                });

            } else if (deleteType === 'multiple') {

                var selectedIds = [];
                $('.select-item:checked').each(function () {
                    selectedIds.push($(this).val());
                });

                if (selectedIds.length === 0) {
                    closeDeleteModal();
                    return;
                }

                closeDeleteModal();

                $.ajax({
                    url:         '/keranjang-hapus-multiple',
                    type:        'POST',
                    data:        { ids: selectedIds },
                    traditional: true,
                    success: function (response) {
                        if (response.success) {
                            selectedIds.forEach(function (id) {
                                $('input.select-item[value="' + id + '"]')
                                    .closest('tr')
                                    .fadeOut(300, function () {
                                        $(this).remove();
                                        if ($('.cart-item').length === 0) {
                                            location.reload();
                                        } else {
                                            updateTotal();
                                            updateCheckoutForm();
                                            $('#selectAll').prop('checked', false);
                                        }
                                    });
                            });
                        } else {
                            alert('Gagal menghapus: ' + (response.message || ''));
                        }
                    },
                    error: function (xhr) {
                        console.error(xhr);
                        alert('Gagal: ' + (xhr.responseJSON ? xhr.responseJSON.message : 'Unknown error'));
                    }
                });
            }
        });

        // Klik luar modal → tutup
        $('#deleteModal').on('click', function (e) {
            if (e.target.id === 'deleteModal') closeDeleteModal();
        });

        // ESC → tutup modal
        $(document).on('keydown', function (e) {
            if (e.key === 'Escape') closeDeleteModal();
        });

        // --------------------------------------------------------
        // CHECKOUT GUARD
        // --------------------------------------------------------
        $('#checkoutForm').on('submit', function (e) {
            if ($('.select-item:checked').length === 0) {
                e.preventDefault();
                alert('Pilih minimal satu produk untuk checkout');
                return false;
            }
            updateCheckoutForm();
        });

        // Initialize
        updateTotal();
        updateCheckoutForm();
    });
</script>
</body>
</html>