<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Keranjang Belanja - Glow Beauty</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&family=Poppins: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: 'Poppins', '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: #fef2f8; color: #ec489a; }
        .active-nav { background-color: #fef2f8; color: #ec489a; font-weight: 600; }

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

        .btn-primary {
            background: linear-gradient(135deg, #f472b6 0%, #ec489a 100%);
            transition: all 0.3s ease;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(244, 114, 182, 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); }
        }
        
        .bg-gradient-pink {
            background: linear-gradient(135deg, #fdf2f8 0%, #fff1f3 100%);
        }
        
        .border-pink-light {
            border-color: #fbcfe8;
        }
    </style>
</head>

<body class="bg-gradient-pink min-h-screen">

    <!-- NAVBAR -->
    <nav class="bg-white/95 backdrop-blur-md border-b border-pink-light shadow-sm sticky top-0 z-50 w-full">
        <div class="px-4 sm:px-6 lg:px-8 py-3">
            <div class="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-pink-400 to-pink-500 rounded-lg flex items-center justify-center shadow-md">
                        <span class="text-white font-bold text-lg">✨</span>
                    </div>
                    <div>
                        <h1 class="font-bold text-lg text-gray-800">Glow Beauty</h1>
                        <p class="text-xs text-pink-400">Keranjang Belanja Skincare</p>
                    </div>
                </div>

                <div class="flex flex-wrap items-center gap-1">

                    @php
                        $jumlahKeranjang = \App\Models\Keranjang::where('user_id', auth()->id())->count();

                        // Badge Chat untuk user
                        $unreadChatCountUser = 0;
                        $chatsUser = \App\Models\Chat::where('user_id', auth()->id())->get();
                        foreach ($chatsUser as $chatItem) {
                            $unreadChatCountUser += \App\Models\ChatMessage::where('chat_id', $chatItem->id)
                                ->where('sender_id', $chatItem->penjual_id)
                                ->where('is_read', false)
                                ->count();
                        }
                    @endphp

                    <a href="{{ route('dashboard') }}"
                        class="flex items-center gap-2 px-4 py-2 rounded-lg
                        {{ request()->routeIs('dashboard') ? 'bg-pink-100 text-pink-600' : 'text-gray-600 hover:bg-pink-50 hover:text-pink-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-pink-100 text-pink-600' : 'text-gray-600 hover:bg-pink-50 hover:text-pink-600' }}
                        transition">
                        <i class="fas fa-store"></i> Produk Skincare
                    </a>

                    {{-- Keranjang --}}
                    <a href="{{ route('keranjang.index') }}"
                        class="relative flex items-center gap-2 px-4 py-2 rounded-lg
                        {{ request()->routeIs('keranjang.*') ? 'bg-pink-100 text-pink-600' : 'text-gray-600 hover:bg-pink-50 hover:text-pink-600' }}
                        transition">
                        <i class="fas fa-shopping-cart"></i> Keranjang
                        @if($jumlahKeranjang > 0)
                            <span class="absolute -top-1 -right-2 bg-red-500 text-white text-[10px] px-1.5 py-0.5 rounded-full leading-none">
                                {{ $jumlahKeranjang > 99 ? '99+' : $jumlahKeranjang }}
                            </span>
                        @endif
                    </a>

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

                    {{-- Chat --}}
                    <a href="{{ route('chat.index') }}"
                        class="flex items-center gap-2 px-4 py-2 rounded-lg
                        {{ request()->routeIs('chat.*') ? 'bg-pink-100 text-pink-600' : 'text-gray-600 hover:bg-pink-50 hover:text-pink-600' }}
                        transition">
                        <i class="fas fa-comments"></i> Chat
                        @if($unreadChatCountUser > 0)
                            <span class="bg-red-500 text-white text-xs font-bold px-1.5 py-0.5 rounded-full min-w-[18px] text-center">
                                {{ $unreadChatCountUser > 99 ? '99+' : $unreadChatCountUser }}
                            </span>
                        @endif
                    </a>

                </div>

                <!-- USER MENU -->
                <div class="flex items-center gap-2 mt-3 md:mt-0">
                    @if(Auth::user()->role == 'penjual')
                    <div class="relative" id="notifWrapper">
                        <button onclick="toggleNotif(event)" class="relative p-2.5 text-gray-600 hover:text-pink-600 hover:bg-pink-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-pink-100 z-50 overflow-hidden" style="animation: fadeInDown 0.2s ease">
                            <div class="bg-gradient-to-r from-pink-400 to-pink-500 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 Skincare 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-pink-50 rounded-xl transition-all duration-200 border border-transparent hover:border-pink-200 group">
                            <div class="w-9 h-9 bg-gradient-to-br from-pink-400 to-pink-500 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-pink-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-pink-500"></i> Penjual Skincare
                                    @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-pink-500"></i> Customer @endif
                                </p>
                            </div>
                            <i class="fas fa-chevron-down text-sm text-gray-400 group-hover:text-pink-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-pink-400 to-pink-500 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-pink-100 text-pink-600 @elseif(Auth::user()->role == 'admin') bg-purple-100 text-purple-600 @else bg-pink-100 text-pink-600 @endif">
                                            @if(Auth::user()->role == 'penjual') <i class="fas fa-store mr-1"></i> Penjual Skincare
                                            @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-pink-50 text-gray-700 transition group">
                                        <div class="w-8 h-8 bg-pink-100 rounded-lg flex items-center justify-center group-hover:bg-pink-200"><i class="fas fa-store text-pink-600"></i></div>
                                        <div><p class="font-medium">Pengaturan Toko Skincare</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-pink-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 Skincare</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-pink-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-pink-100"><i class="fas fa-user text-gray-500 group-hover:text-pink-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">

        @if(session('success'))
        <div id="toast-success"
            class="fixed bottom-6 right-6 z-50 flex items-center gap-3 bg-white border border-green-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 bg-green-500 rounded-xl flex items-center justify-center flex-shrink-0">
                <i class="fas fa-check text-white text-sm"></i>
            </div>
            <div class="flex-1 min-w-0">
                <p class="font-semibold text-gray-800 text-sm">Berhasil!</p>
                <p class="text-gray-500 text-xs mt-0.5">{{ session('success') }}</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 bg-green-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-success');
                if (toast) {
                    toast.style.animation = 'slideOutRight 0.3s ease forwards';
                    setTimeout(() => toast.remove(), 300);
                }
            }
        </script>
        @endif

        @if(session('error'))
            <div class="notif-alert mb-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg flex items-center justify-between">
                <div class="flex items-center gap-2">
                    <i class="fas fa-exclamation-circle text-red-500"></i>
                    <span>{{ session('error') }}</span>
                </div>
                <button onclick="this.parentElement.remove()" class="text-red-700 hover:text-red-900">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        @endif

        @if(session('warning'))
            <div class="notif-alert mb-4 bg-yellow-100 border border-yellow-400 text-yellow-700 px-4 py-3 rounded-lg flex items-center justify-between">
                <div class="flex items-center gap-2">
                    <i class="fas fa-exclamation-triangle text-yellow-500"></i>
                    <span>{{ session('warning') }}</span>
                </div>
                <button onclick="this.parentElement.remove()" class="text-yellow-700 hover:text-yellow-900">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        @endif

       <!-- HEADER CARD - KERANJANG BELANJA -->
<div class="relative mb-8 overflow-hidden rounded-2xl bg-gradient-to-r from-pink-400 via-pink-500 to-pink-600 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>
        <i class="fas fa-spa text-7xl absolute bottom-10 left-10"></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 Skincare</h2>
            </div>
            <p class="text-pink-100 text-sm ml-[60px]">Kelola produk skincare dalam keranjang belanja Anda</p>
        </div>
        
        {{-- Right Section - Stats --}}
        @if(isset($keranjangs) && count($keranjangs) > 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-pink-200"></i>
                <span class="text-pink-100 text-sm">Item Skincare:</span>
                <span class="font-bold text-white text-lg">{{ count($keranjangs) }}</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 Skincare Kosong
            </span>
        </div>
        @endif
    </div>
</div>

        @if(!isset($keranjangs) || count($keranjangs) === 0)
            <div class="bg-white rounded-xl shadow-lg border border-pink-100 p-12 text-center cart-empty-state w-full">
                <div class="mx-auto w-24 h-24 bg-pink-50 rounded-full flex items-center justify-center mb-6">
                    <i class="fas fa-shopping-cart text-pink-400 text-3xl"></i>
                </div>
                <h3 class="text-xl font-bold text-gray-800 mb-3">Keranjang Skincare Anda Kosong</h3>
                <p class="text-gray-500 mb-8 max-w-md mx-auto">
                    Anda belum menambahkan produk skincare 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 Skincare
                    </a>
                    <a href="{{ route('dashboard') }}"
                       class="px-8 py-3 rounded-lg font-semibold border border-pink-200 text-gray-700 hover:bg-pink-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-pink-100 overflow-hidden">
                        <div class="px-6 py-4 border-b border-pink-100 bg-gradient-to-r from-pink-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-pink-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-shopping-cart text-pink-600"></i>
                                </div>
                                <div>
                                    <h3 class="font-bold text-gray-800 flex items-center gap-2">
                                        <i class="fas fa-list"></i> Produk Skincare dalam Keranjang
                                    </h3>
                                    <p class="text-sm text-gray-500">{{ count($keranjangs) }} 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-pink-600 rounded border-gray-300 focus:ring-pink-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 Skincare
                                        </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($keranjangs 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 Skincare Tidak Ditemukan';
                                            $subtotal    = $item->jumlah * $hargaProduk;
                                            $maxStok     = $item->produk->stok ?? 99;
                                        @endphp

                                        <tr class="cart-item cart-item-hover border-b border-pink-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-pink-600 rounded border-gray-300 focus:ring-pink-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-pink-200"
                                                            alt="{{ $namaProduk }}"
                                                            onerror="imgError(this)">
                                                            <script>
                                                                function imgError(image) {
                                                                    image.onerror = null; 
                                                                    image.src = "{{ asset('images/no-image.png') }}";
                                                                }
                                                            </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-pink-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-pink-50 text-pink-700 text-[10px] font-medium rounded-full border border-pink-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-pink-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-pink-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>
                                              </tr>
                                          
                                    @empty
                                        32
                                            <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 skincare Anda kosong</p>
                                              </tr>
                                          32
                                    @endforelse
                                </tbody>
                             </table>
                        </div>
                    </div>
                </div>

                <!-- CHECKOUT SUMMARY -->
                <div class="lg:col-span-1">
                    <div class="bg-white rounded-xl shadow-lg border border-pink-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 Skincare
                            </h3>
                        </div>

                        @php
                            $ongkir     = ($total ?? 0) >= 200000 ? 0 : 15000;
                            
                            // Diskon Rp 10.000 hanya jika minimal belanja Rp 200.000
                            $diskonNominal = 10000;
                            $minBelanjaDiskon = 200000;
                            
                            if (($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 Rp200.000 dapat diskon Rp10.000!</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 10rb
                                </span>
                                <span id="diskonDisplay" class="font-semibold">
                                    -Rp{{ number_format($diskonNominal, 0, ',', '.') }}
                                </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-pink-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 produk skincare</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-pink-500"></i> Total
                                    </span>
                                    <span id="totalDisplay" class="text-pink-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-pink-600 hover:text-pink-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">
                                @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="submit" 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-pink-600 hover:text-pink-700 text-sm font-medium inline-flex items-center gap-2 transition">
                                    <i class="fas fa-arrow-left"></i> Lanjutkan Belanja Skincare
                                </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-pink-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-pink-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>
// ============================================================
    // USER DROPDOWN TOGGLE
    // ============================================================
    function toggleUserDropdown(event) {
        event.stopPropagation();
        const dropdown = document.getElementById('dropdownMenu');
        const icon = document.getElementById('dropdownIcon');
        
        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)';
        }
    }

    // Tutup dropdown saat klik di luar
    document.addEventListener('click', function(event) {
        const dropdown = document.getElementById('dropdownMenu');
        const userDropdown = document.getElementById('userDropdown');
        
        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)';
            }
        }
    });

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

    // Tutup notifikasi 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);
            });

            // Konfigurasi diskon
            var diskonNominal = 10000;
            var minBelanjaDiskon = 200000;
            
            var subtotalSetelahDiskon = subtotal;
            var statusDiskon = false;
            
            // Cek apakah memenuhi syarat minimal belanja
            if (subtotal >= minBelanjaDiskon) {
                subtotalSetelahDiskon = subtotal - diskonNominal;
                statusDiskon = true;
            }
            
            // Ongkir tidak ditampilkan nominalnya
            var total = subtotalSetelahDiskon;

            // Update tampilan subtotal
            $('#subtotalDisplay').text('Rp' + formatRupiah(subtotal));
            
            // Hapus info minimal belanja jika sudah memenuhi syarat ATAU subtotal 0
            if (statusDiskon || subtotal === 0) {
                $('#minBelanjaInfo').remove();
            } 
            // Tampilkan info hanya jika belum memenuhi syarat dan subtotal > 0
            else if (!statusDiskon && subtotal > 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 Rp200.000 dapat diskon Rp10.000!</p>' +
                            '<p class="text-xs mt-1">Kurang Rp' + formatRupiah(kurang) + ' lagi</p>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                
                // Hapus info lama jika ada, lalu tambahkan yang baru
                $('#minBelanjaInfo').remove();
                $('.space-y-4').prepend(infoHtml);
            }
            
            // Update tampilan diskon (jika ada)
            if (statusDiskon) {
                // Jika sebelumnya tidak ada elemen diskon, tambahkan
                if ($('#diskonDisplay').length === 0) {
                    // Hapus info minimal belanja jika masih ada (double check)
                    $('#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 10rb' +
                                    '</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-pink-600">Rp' + formatRupiah(subtotalSetelahDiskon) + '</span>' +
                                    '</div>';
                    
                    // Hapus row lama jika ada, lalu tambahkan setelah subtotal
                    $('#diskonRow').remove();
                    $('#subtotalAfterDiskonRow').remove();
                    $('#subtotalDisplay').closest('.flex').after(diskonHtml);
                } else {
                    // Update nilai yang sudah ada
                    $('#diskonDisplay').html('-Rp' + formatRupiah(diskonNominal));
                    $('#subtotalAfterDiskonDisplay').text('Rp' + formatRupiah(subtotalSetelahDiskon));
                }
            } else {
                // Hapus elemen diskon jika tidak memenuhi syarat
                $('#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 skincare 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 skincare?');
            $('#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 skincare untuk checkout');
                return false;
            }
            updateCheckoutForm();
        });

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