<x-app-layout>
    <style>
        body, #app, main { background-color: #FAF7F2 !important; }
        .min-h-screen { background-color: #FAF7F2 !important; }
    </style>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>

    <style>
        .swiper-pagination-bullet { 
            width: 4px; 
            height: 4px; 
            background: #fff; 
            opacity: 0.5; 
            transition: all 0.3s; 
        }
        .swiper-pagination-bullet-active { 
            width: 14px; 
            border-radius: 4px; 
            background: #f59e0b !important; 
            opacity: 1; 
        }
        input[type=number]::-webkit-inner-spin-button, 
        input[type=number]::-webkit-outer-spin-button { opacity: 1; }
        .swal2-popup { 
            border-radius: 1.5rem !important; 
            padding: 1.5rem !important; 
            font-family: inherit; 
        }
        .swal2-title { 
            font-weight: 800 !important; 
            color: #2c1a0e !important; 
        }
        .swal2-styled.swal2-confirm { 
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%) !important; 
            border-radius: 0.75rem !important; 
            padding: 0.7rem 1.5rem !important; 
            font-weight: 700 !important; 
            box-shadow: 0 4px 12px rgba(245,158,11,0.3) !important;
        }
        .swal2-styled.swal2-cancel { 
            border-radius: 0.75rem !important; 
            padding: 0.7rem 1.5rem !important; 
            font-weight: 700 !important; 
            background: #6b4c31 !important;
        }
        [x-cloak] { display: none !important; }
        .product-card:hover .btn-cart { 
            transform: translateY(0); 
            opacity: 1; 
        }
        .btn-cart { 
            transform: translateY(10px); 
            opacity: 0; 
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); 
        }
        .no-spinners::-webkit-outer-spin-button, 
        .no-spinners::-webkit-inner-spin-button { 
            -webkit-appearance: none; 
            margin: 0; 
        }
        .no-spinners { 
            -moz-appearance: textfield; 
        }
        .pagination .page-item.active .page-link {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            border-color: #d97706;
            color: white;
        }
        .pagination .page-link {
            color: #8c6a4a;
            border-radius: 0.75rem;
            margin: 0 3px;
        }
        .pagination .page-link:hover {
            background-color: #fef3c7;
            color: #d97706;
        }
    </style>

    <div class="max-w-7xl mx-auto p-4 sm:p-6 lg:p-8 min-h-screen" x-data="stockManager()">

        {{-- Header Section --}}
        <div class="flex flex-col md:flex-row md:items-end justify-between gap-6 mb-8 lg:mb-12">
            <div class="space-y-2">
                <div class="flex items-center gap-2 text-sm text-[#8c6a4a]">
                    <i class="fas fa-boxes"></i>
                    <span>Manajemen Produk</span>
                </div>
                <h1 class="text-3xl sm:text-4xl font-extrabold text-[#2c1a0e] tracking-tight">
                    @if(auth()->user()->role === 'admin')
                        Inventory <span class="text-[#f59e0b]">Pro</span>
                    @else
                        Koleksi <span class="text-[#f59e0b]">Barang</span>
                    @endif
                </h1>
                <p class="text-sm text-[#8c6a4a] max-w-md leading-relaxed">
                    Total {{ $products->total() }} produk tersedia
                </p>
            </div>

            <div class="flex flex-wrap items-center gap-3">
                <form action="{{ route('products.index') }}" method="GET" class="flex flex-col sm:flex-row gap-3 w-full sm:w-auto">
                    {{-- Kategori --}}
                    <div class="relative">
                        <select name="category_id" onchange="this.form.submit()" 
                            class="appearance-none pl-5 pr-10 py-3.5 rounded-xl border-none bg-white shadow-sm ring-1 ring-[#e0d3c2] focus:ring-2 focus:ring-[#f59e0b]/50 transition-all w-full sm:w-48 text-sm font-bold text-[#2c1a0e] cursor-pointer">
                            <option value="">Semua Kategori</option>
                            @foreach($categories as $category)
                                <option value="{{ $category->id }}" {{ request('category_id') == $category->id ? 'selected' : '' }}>
                                    {{ $category->name }}
                                </option>
                            @endforeach
                        </select>
                        <i class="fas fa-chevron-down absolute right-4 top-1/2 -translate-y-1/2 text-[#c9b59b] pointer-events-none text-xs"></i>
                    </div>

                    {{-- Search --}}
                    <div class="relative group">
                        <input type="text" name="search" value="{{ request('search') }}" 
                            placeholder="Cari nama produk..." 
                            class="pl-12 {{ request('search') ? 'pr-20' : 'pr-6' }} py-3.5 rounded-xl border-none bg-white shadow-sm ring-1 ring-[#e0d3c2] focus:ring-2 focus:ring-[#f59e0b]/50 transition-all w-full sm:w-64 text-sm font-medium text-[#2c1a0e]">
                        <i class="fas fa-search absolute left-4 top-1/2 -translate-y-1/2 text-[#c9b59b] group-focus-within:text-[#f59e0b] transition-colors"></i>
                        @if(request('search'))
                            <a href="{{ route('products.index', request()->only('category_id')) }}" class="absolute right-4 top-1/2 -translate-y-1/2 text-[#c9b59b] hover:text-red-500 transition-colors">
                                <i class="fas fa-times-circle"></i>
                            </a>
                        @endif
                    </div>

                    @if(auth()->user()->role !== 'admin')
                    {{-- Sort - hanya untuk user --}}
                    <div class="relative">
                        <select name="sort" onchange="this.form.submit()"
                            class="appearance-none pl-5 pr-10 py-3.5 rounded-xl border-none bg-white shadow-sm ring-1 ring-[#e0d3c2] focus:ring-2 focus:ring-[#f59e0b]/50 transition-all w-full sm:w-44 text-sm font-bold text-[#2c1a0e] cursor-pointer">
                            <option value="">Urutkan</option>
                            <option value="price_asc"  {{ request('sort') == 'price_asc'  ? 'selected' : '' }}>Harga: Termurah</option>
                            <option value="price_desc" {{ request('sort') == 'price_desc' ? 'selected' : '' }}>Harga: Termahal</option>
                            <option value="newest"     {{ request('sort') == 'newest'     ? 'selected' : '' }}>Terbaru</option>
                            <option value="rating"     {{ request('sort') == 'rating'     ? 'selected' : '' }}>Rating Tertinggi</option>
                        </select>
                        <i class="fas fa-sort absolute right-4 top-1/2 -translate-y-1/2 text-[#c9b59b] pointer-events-none text-xs"></i>
                    </div>

                    {{-- Reset filter --}}
                    @if(request()->anyFilled(['search','category_id','sort']))
                        <a href="{{ route('products.index') }}" 
                           class="px-4 py-3.5 rounded-xl bg-[#fef3c7] text-[#d97706] border border-[#fde68a] text-sm font-bold hover:bg-[#fde68a] transition-all flex items-center gap-2">
                            <i class="fas fa-undo text-xs"></i>
                            <span class="hidden sm:inline">Reset</span>
                        </a>
                    @endif
                    @endif
                </form>
                
                @if(auth()->user()->role === 'admin')
                    <div class="h-10 w-[1px] bg-[#e0d3c2] mx-1 hidden md:block"></div>
                    <a href="{{ route('products.create') }}" class="px-6 py-3.5 bg-gradient-to-r from-[#f59e0b] to-[#d97706] text-white rounded-xl font-bold text-sm hover:from-[#d97706] hover:to-[#b45309] hover:-translate-y-0.5 transition-all shadow-md shadow-[#f59e0b]/20 flex items-center gap-2">
                        <i class="fas fa-plus text-xs"></i>
                        <span class="hidden sm:inline">Tambah Produk</span>
                    </a>
                @endif
            </div>
        </div>

        {{-- Main Content --}}
        @if(auth()->user()->role === 'admin')
            {{-- Hapus overflow-hidden di sini --}}
            <div class="bg-white rounded-2xl shadow-lg border border-[#e0d3c2]">
                {{-- Tambahkan overflow-visible agar dropdown bisa keluar dari area tabel --}}
                <div class="overflow-x-auto overflow-y-visible">
                    <table class="w-full text-left">
                        <thead>
                            <tr class="bg-[#fef3c7] border-b border-[#e0d3c2]">
                                <th class="px-4 sm:px-6 lg:px-8 py-5 text-[10px] font-black uppercase text-[#8c6a4a] tracking-widest">Informasi Produk</th>
                                <th class="px-4 sm:px-6 py-5 text-[10px] font-black uppercase text-[#8c6a4a] tracking-widest text-center">Status</th>
                                <th class="px-4 sm:px-6 py-5 text-[10px] font-black uppercase text-[#8c6a4a] tracking-widest text-center">Stok Varian</th>
                                <th class="px-4 sm:px-6 py-5 text-[10px] font-black uppercase text-[#8c6a4a] tracking-widest text-center">Harga Dasar</th>
                                <th class="px-4 sm:px-6 lg:px-8 py-5 text-[10px] font-black uppercase text-[#8c6a4a] tracking-widest text-right">Aksi</th>
                             </tr>
                        </thead>
                        <tbody class="divide-y divide-[#f0e7dc]">
                            @forelse($products as $product)
                            <tr id="product-{{ $product->id }}" class="hover:bg-[#fef9f0] transition-all duration-300 group">
                                <td class="px-4 sm:px-6 lg:px-8 py-5">
                                    <div class="flex items-center gap-4">
                                        <div class="w-14 h-14 rounded-xl overflow-hidden bg-[#fef3c7] border border-[#e0d3c2] flex-shrink-0 shadow-sm">
                                            <img src="{{ asset('storage/'.$product->images->first()?->image) }}" 
                                                 onerror="this.src='https://ui-avatars.com/api/?name={{ urlencode($product->name) }}&background=FEF3C7&color=8C6A4A'"
                                                 class="w-full h-full object-cover">
                                        </div>
                                        <div>
                                            <p class="font-bold text-[#2c1a0e] tracking-tight text-base mb-0.5">{{ $product->name }}</p>
                                            <span class="inline-block px-2 py-0.5 rounded-lg bg-[#fef3c7] text-[9px] font-black text-[#d97706] uppercase tracking-wider">
                                                {{ $product->category->name ?? 'Uncategorized' }}
                                            </span>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-4 sm:px-6 py-5 text-center">
                                    <div x-data="{ open: false }" class="relative inline-block text-left">
                                        <button @click="open = !open" type="button" 
                                            class="flex items-center gap-2 mx-auto px-4 py-2 rounded-xl text-[10px] font-black uppercase transition-all duration-300 hover:shadow-md {{ $product->status === 'active' ? 'bg-emerald-50 text-emerald-600 border border-emerald-100' : 'bg-slate-100 text-slate-400 border border-slate-200' }}">
                                            <span class="relative flex h-2 w-2">
                                                @if($product->status === 'active')
                                                    <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                                                @endif
                                                <span class="relative inline-flex rounded-full h-2 w-2 {{ $product->status === 'active' ? 'bg-emerald-500' : 'bg-slate-400' }}"></span>
                                            </span>
                                            {{ $product->status === 'active' ? 'Aktif' : 'Draft' }}
                                            <i class="fas fa-chevron-down text-[8px] transition-transform duration-300" :class="open ? 'rotate-180' : ''"></i>
                                        </button>

                                        <div x-show="open" 
                                            @click.away="open = false"
                                            x-transition:enter="transition ease-out duration-100"
                                            x-transition:enter-start="transform opacity-0 scale-95"
                                            x-transition:enter-end="transform opacity-100 scale-100"
                                            {{-- Ubah mt-2 menjadi bottom-full mb-2 agar muncul ke atas dan tidak terpotong --}}
                                            class="absolute z-[100] bottom-full mb-2 w-32 rounded-xl bg-white shadow-xl border border-gray-100 left-1/2 -translate-x-1/2 overflow-hidden"
                                            style="display: none;">
                                            
                                            <form action="{{ route('products.toggleStatus', $product->id) }}" method="POST" class="space-y-1">
                                                @csrf
                                                @method('PATCH')
                                                
                                                <button type="submit" name="status" value="active"
                                                    @if($product->status === 'active') disabled @endif
                                                    class="w-full text-left px-3 py-2.5 rounded-xl text-[10px] font-bold uppercase flex items-center gap-2.5 transition-all {{ $product->status === 'active' ? 'bg-emerald-50 text-emerald-600 opacity-50 cursor-default' : 'text-[#8c6a4a] hover:bg-[#fef3c7] hover:text-[#d97706]' }}">
                                                    <i class="fas fa-check-circle text-xs"></i>
                                                    Publish Aktif
                                                </button>

                                                <div class="h-[1px] bg-[#f0e7dc] mx-2"></div>

                                                <button type="submit" name="status" value="inactive"
                                                    @if($product->status === 'inactive') disabled @endif
                                                    class="w-full text-left px-3 py-2.5 rounded-xl text-[10px] font-bold uppercase flex items-center gap-2.5 transition-all {{ $product->status === 'inactive' ? 'bg-slate-50 text-slate-400 opacity-50 cursor-default' : 'text-[#8c6a4a] hover:bg-[#fef3c7] hover:text-[#d97706]' }}">
                                                    <i class="fas fa-file-alt text-xs"></i>
                                                    Simpan Draft
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-4 sm:px-6 py-5 text-center">
                                    <button type="button" @click="openModal({{ $product->id }}, '{{ addslashes($product->name) }}', {{ $product->variants->toJson() }})"
                                            class="group/btn flex items-center gap-3 mx-auto px-5 py-2.5 bg-[#fef9f0] border border-[#e0d3c2] rounded-xl hover:border-[#f59e0b] hover:bg-[#fff5e6] transition-all shadow-sm">
                                        <div class="flex flex-col items-center">
                                            <span class="text-[9px] font-black text-[#8c6a4a] uppercase leading-none group-hover/btn:text-[#d97706] mb-1">Total Stok</span>
                                            <span class="text-sm font-black text-[#2c1a0e] group-hover/btn:text-[#f59e0b]">
                                                {{ $product->variants->sum('stock') }} <span class="text-[10px] font-medium text-[#8c6a4a] lowercase">pcs</span>
                                            </span>
                                        </div>
                                        <div class="w-6 h-6 rounded-lg bg-white border border-[#e0d3c2] flex items-center justify-center group-hover/btn:bg-[#f59e0b] group-hover/btn:border-[#f59e0b] transition-all">
                                            <i class="fas fa-edit text-[10px] text-[#8c6a4a] group-hover/btn:text-white"></i>
                                        </div>
                                    </button>
                                </td>
                                <td class="px-4 sm:px-6 py-5 text-center font-bold text-[#2c1a0e]">
                                    <span class="text-xs text-[#8c6a4a] font-medium mr-0.5">Rp</span>{{ number_format($product->base_price, 0, ',', '.') }}
                                </td>
                                <td class="px-4 sm:px-6 lg:px-8 py-5 text-right">
                                    <div class="flex justify-end gap-2">
                                        <a href="{{ route('products.edit', $product) }}" class="w-9 h-9 flex items-center justify-center bg-white border border-[#e0d3c2] text-[#8c6a4a] rounded-xl hover:border-[#f59e0b] hover:text-[#f59e0b] transition-all shadow-sm">
                                            <i class="fas fa-pen text-xs"></i>
                                        </a>
                                        <button type="button" onclick="confirmDelete({{ $product->id }})" class="w-9 h-9 flex items-center justify-center bg-white border border-[#e0d3c2] text-[#8c6a4a] rounded-xl hover:border-red-500 hover:text-red-500 transition-all shadow-sm">
                                            <i class="fas fa-trash text-xs"></i>
                                        </button>
                                        <form id="delete-form-{{ $product->id }}" action="{{ route('products.destroy', $product) }}" method="POST" class="hidden">
                                            @csrf @method('DELETE')
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="5" class="py-20 text-center text-[#8c6a4a] font-medium italic">
                                    <i class="fas fa-box-open text-3xl mb-3 opacity-30 block"></i>
                                    Data tidak ditemukan.
                                </td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        @else
            @if($products->isEmpty())
                {{-- Empty State --}}
                <div class="flex flex-col items-center justify-center py-24 bg-white rounded-2xl border border-[#e0d3c2] shadow-sm">
                    <div class="w-24 h-24 bg-[#fef3c7] rounded-full flex items-center justify-center mb-6">
                        <i class="fas fa-box-open text-[#f59e0b] text-4xl"></i>
                    </div>
                    <h3 class="text-xl font-bold text-[#2c1a0e] mb-2">Produk Tidak Ditemukan</h3>
                    <p class="text-[#8c6a4a] text-sm mb-6 text-center max-w-xs">Coba ubah kata kunci atau filter kategori yang kamu gunakan.</p>
                    <a href="{{ route('products.index') }}" class="px-6 py-3 bg-gradient-to-r from-[#f59e0b] to-[#d97706] text-white rounded-xl font-bold text-sm hover:from-[#d97706] hover:to-[#b45309] transition-all shadow-md">
                        Lihat Semua Produk
                    </a>
                </div>
            @else
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 lg:gap-8">
                @foreach($products as $product)
                @php
                    $totalStock = $product->variants->sum('stock');
                    $isNew = $product->created_at->diffInDays(now()) <= 14;
                    $reviewCount = $product->reviews_count ?? $product->reviews->count();
                    $avgRating = $product->reviews_avg_rating ?? 0;
                @endphp
                    <div class="product-card group bg-white rounded-2xl p-4 shadow-md hover:shadow-xl hover:shadow-[#f59e0b]/10 transition-all duration-500 border border-[#e0d3c2] flex flex-col relative" 
                        x-data="{ 
                            isWishlisted: {{ Auth::user() && Auth::user()->wishlists()->where('product_id', $product->id)->exists() ? 'true' : 'false' }},
                            loading: false,
                            toggleWishlist() {
                                if (this.loading) return;
                                this.loading = true;
                                fetch('{{ route('wishlist.toggle', $product->id) }}', {
                                    method: 'POST',
                                    headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
                                })
                                .then(res => res.json())
                                .then(data => {
                                    this.isWishlisted = (data.status === 'added');
                                    Swal.fire({ toast: true, position: 'top-end', icon: 'success', title: data.message, showConfirmButton: false, timer: 2000 });
                                })
                                .catch(err => console.error(err))
                                .finally(() => this.loading = false);
                            }
                        }">
                        
                        {{-- Wishlist Button --}}
                        <button @click="toggleWishlist()" 
                                class="absolute top-5 right-5 z-20 w-10 h-10 rounded-full flex items-center justify-center transition-all duration-300 shadow-md backdrop-blur-sm"
                                :class="isWishlisted ? 'bg-red-50 border-red-100 text-red-500' : 'bg-white/80 border border-white/30 text-[#8c6a4a] hover:text-red-500'">
                            <i class="fa-heart transition-transform duration-300" :class="[isWishlisted ? 'fas scale-110' : 'far hover:scale-110', loading ? 'animate-pulse' : '']"></i>
                        </button>

                        {{-- Badges --}}
                        <div class="absolute top-5 left-5 z-20 flex flex-col gap-1.5">
                            @if($avgRating >= 4.5)
                                <span class="bg-[#d97706] text-white px-2.5 py-1 rounded-lg font-black text-[9px] uppercase tracking-[0.12em] shadow-lg flex items-center gap-1">
                                    <i class="fas fa-crown text-[8px]"></i> Top
                                </span>
                            @endif
                            @if($isNew)
                                <span class="bg-emerald-500 text-white px-2.5 py-1 rounded-lg font-black text-[9px] uppercase tracking-[0.12em] shadow-lg flex items-center gap-1">
                                    <i class="fas fa-sparkles text-[8px]"></i> Baru
                                </span>
                            @endif
                            @if($totalStock <= 0)
                                <span class="bg-[#2c1a0e] text-white px-2.5 py-1 rounded-lg font-black text-[9px] uppercase tracking-[0.12em] shadow-lg">
                                    Habis
                                </span>
                            @elseif($totalStock <= 5)
                                <span class="bg-rose-500 text-white px-2.5 py-1 rounded-lg font-black text-[9px] uppercase tracking-[0.12em] shadow-lg flex items-center gap-1">
                                    <i class="fas fa-fire text-[8px]"></i> Sisa {{ $totalStock }}
                                </span>
                            @endif
                        </div>

                        {{-- Image Swiper --}}
                        <a href="{{ route('products.show', $product) }}" class="relative aspect-[4/5] w-full rounded-xl overflow-hidden mb-4 bg-[#fef3c7] block">
                            @if($totalStock <= 0)
                                <div class="absolute inset-0 z-10 bg-[#2c1a0e]/50 backdrop-blur-[2px] flex items-center justify-center">
                                    <span class="bg-white text-[#2c1a0e] px-4 py-2 rounded-xl font-black text-[10px] uppercase tracking-widest shadow-xl">Stok Habis</span>
                                </div>
                            @endif

                            <div class="swiper productSwiper h-full">
                                <div class="swiper-wrapper">
                                    @forelse($product->images as $image)
                                        <div class="swiper-slide">
                                            <img src="{{ asset('storage/'.$image->image) }}" class="w-full h-full object-cover transform group-hover:scale-110 transition-transform duration-1000" onerror="this.src='https://placehold.co/600x800?text=Furniture+Loka'">
                                        </div>
                                    @empty
                                        <div class="swiper-slide flex items-center justify-center bg-[#fef3c7]">
                                            <i class="fas fa-image text-[#c9b59b] text-4xl"></i>
                                        </div>
                                    @endforelse
                                </div>
                                <div class="swiper-pagination !bottom-4"></div>
                            </div>
                        </a>

                        {{-- Info --}}
                        <div class="px-1 flex-grow flex flex-col">
                            {{-- Kategori + Rating --}}
                            <div class="flex items-center justify-between mb-2">
                                <span class="px-2.5 py-1 rounded-lg bg-[#fef3c7] text-[9px] font-black text-[#d97706] uppercase tracking-wider">
                                    {{ $product->category->name ?? 'General' }}
                                </span>
                                <div class="flex items-center gap-1 bg-[#fef3c7] px-2 py-1 rounded-lg">
                                    <i class="fas fa-star text-[9px] text-[#d97706]"></i>
                                    <span class="text-[11px] font-black text-[#2c1a0e] leading-none">{{ number_format($avgRating, 1) }}</span>
                                    <span class="text-[9px] text-[#8c6a4a]">({{ $reviewCount }})</span>
                                </div>
                            </div>

                            {{-- Nama --}}
                            <h2 class="text-base font-bold text-[#2c1a0e] leading-tight group-hover:text-[#f59e0b] transition-colors line-clamp-2 min-h-[2.8rem] mb-2">
                                {{ $product->name }}
                            </h2>

                            {{-- Warna varian tersedia --}}
                            @if($product->variants->count() > 0)
                                <div class="flex items-center gap-1.5 mb-3">
                                    <span class="text-[9px] text-[#8c6a4a] font-bold uppercase">Varian:</span>
                                    <div class="flex gap-1 flex-wrap">
                                        @foreach($product->variants->take(4) as $v)
                                            <span class="text-[9px] font-bold px-2 py-0.5 rounded-full bg-[#faf7f2] border border-[#e0d3c2] text-[#6b4c31]">{{ $v->color }}</span>
                                        @endforeach
                                        @if($product->variants->count() > 4)
                                            <span class="text-[9px] font-bold px-2 py-0.5 rounded-full bg-[#faf7f2] border border-[#e0d3c2] text-[#8c6a4a]">+{{ $product->variants->count() - 4 }}</span>
                                        @endif
                                    </div>
                                </div>
                            @endif

                            {{-- Harga + Tombol --}}
                            <div class="mt-auto flex items-center justify-between border-t border-[#f0e7dc] pt-3 pb-1">
                                <div>
                                    <p class="text-[10px] font-bold text-[#8c6a4a] uppercase tracking-widest mb-0.5">Harga</p>
                                    <p class="text-lg font-black text-[#2c1a0e] tracking-tighter">
                                        <span class="text-xs font-medium mr-0.5">Rp</span>{{ number_format($product->base_price, 0, ',', '.') }}
                                    </p>
                                </div>
                                <a href="{{ route('products.show', $product) }}" 
                                    class="flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-[#f59e0b] to-[#d97706] text-white rounded-xl hover:from-[#d97706] hover:to-[#b45309] hover:-translate-y-1 transition-all shadow-md shadow-[#f59e0b]/30 text-[11px] font-black uppercase tracking-wide {{ $totalStock <= 0 ? 'opacity-50 pointer-events-none' : '' }}">
                                    <i class="fas fa-bag-shopping text-[10px]"></i>
                                    <span>Beli</span>
                                </a>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
            @endif
        @endif

        {{-- QUICK STOCK MODAL --}}
        <div x-show="modalOpen" x-cloak class="fixed inset-0 z-[100] overflow-y-auto flex items-center justify-center p-4 bg-[#2c1a0e]/60 backdrop-blur-sm">
            <div class="bg-white w-full max-w-md rounded-2xl p-6 shadow-2xl relative" @click.away="modalOpen = false" x-transition>
                <button @click="modalOpen = false" class="absolute top-5 right-5 text-[#c9b59b] hover:text-[#2c1a0e] transition-colors">
                    <i class="fas fa-times text-lg"></i>
                </button>
                <div class="mb-6 text-center">
                    <h3 class="text-2xl font-black text-[#2c1a0e] leading-tight" x-text="selectedProductName"></h3>
                    <div class="mt-2 inline-flex items-center gap-2 px-3 py-1 bg-[#fef3c7] text-[#d97706] rounded-full text-[10px] font-bold uppercase tracking-widest">Update Stok Cepat</div>
                </div>
                <div class="space-y-6">
                    <div class="space-y-3">
                        <label class="text-[10px] font-black uppercase text-[#8c6a4a] tracking-widest text-center block">Pilih Varian Produk</label>
                        <div class="grid grid-cols-2 gap-3">
                            <template x-for="variant in variants" :key="variant.id">
                                <button @click="activeVariantId = variant.id" 
                                        :class="activeVariantId === variant.id ? 'bg-gradient-to-r from-[#f59e0b] to-[#d97706] border-[#d97706] text-white shadow-lg shadow-[#f59e0b]/30' : 'bg-white border-[#e0d3c2] text-[#2c1a0e] hover:border-[#f59e0b]'"
                                        class="p-4 rounded-xl border-2 transition-all text-center relative overflow-hidden group">
                                    <p class="text-[10px] font-black uppercase tracking-widest opacity-70 mb-1" x-text="variant.color || variant.name || 'Varian'"></p>
                                    <p class="text-sm font-bold"><span x-text="variant.stock"></span> <span class="text-[10px] opacity-60">pcs</span></p>
                                    <template x-if="activeVariantId === variant.id">
                                        <div class="absolute top-1 right-2 text-[10px]"><i class="fas fa-check-circle"></i></div>
                                    </template>
                                </button>
                            </template>
                        </div>
                    </div>
                    <div class="space-y-3 pt-4 border-t border-[#f0e7dc]">
                        <div class="flex flex-col items-center mb-2">
                            <label class="text-[10px] font-black uppercase text-[#8c6a4a] tracking-widest text-center block">Update Stok (+/-)</label>
                        </div>
                        <div class="flex flex-row items-center gap-3 bg-[#fef9f0] p-2 rounded-xl border border-[#e0d3c2]">
                            <button type="button" @click="adjustment--" class="w-14 h-14 shrink-0 bg-white text-red-500 rounded-xl shadow-sm hover:bg-red-50 transition-all flex items-center justify-center border border-[#e0d3c2]">
                                <i class="fas fa-minus text-xs"></i>
                            </button>
                            <div class="flex-1">
                                <input type="number" x-model="adjustment" class="w-full bg-transparent border-none text-center text-4xl font-black text-[#f59e0b] focus:ring-0 no-spinners p-0">
                            </div>
                            <button type="button" @click="adjustment++" class="w-14 h-14 shrink-0 bg-white text-emerald-500 rounded-xl shadow-sm hover:bg-emerald-50 transition-all flex items-center justify-center border border-[#e0d3c2]">
                                <i class="fas fa-plus text-xs"></i>
                            </button>
                        </div>
                    </div>
                    <button @click="submitUpdate" :disabled="!activeVariantId || loading" class="w-full py-4 bg-gradient-to-r from-[#f59e0b] to-[#d97706] text-white rounded-xl font-black hover:from-[#d97706] hover:to-[#b45309] transition-all flex items-center justify-center gap-3 disabled:opacity-50 shadow-md shadow-[#f59e0b]/20">
                        <span x-show="!loading">Simpan Perubahan</span>
                        <i x-show="loading" class="fas fa-circle-notch animate-spin"></i>
                    </button>
                </div>
            </div>
        </div>

        <div class="mt-12 flex justify-center">
            {{ $products->appends(request()->query())->links() }}
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const swipers = document.querySelectorAll('.productSwiper');
            swipers.forEach(el => {
                new Swiper(el, {
                    effect: 'fade',
                    fadeEffect: { crossFade: true },
                    pagination: { el: el.querySelector('.swiper-pagination'), clickable: true, dynamicBullets: true },
                });
            });
        });

        function stockManager() {
            return {
                modalOpen: false, 
                loading: false, 
                selectedProductName: '', 
                variants: [], 
                activeVariantId: null, 
                adjustment: 0,
                openModal(id, name, variants) {
                    this.selectedProductName = name;
                    this.variants = typeof variants === 'string' ? JSON.parse(variants) : variants;
                    if (this.variants && this.variants.length > 0) {
                        this.activeVariantId = this.variants[0].id;
                    }
                    this.adjustment = 0; 
                    this.modalOpen = true;
                },
                submitUpdate() {
                    if(this.adjustment == 0) return;
                    this.loading = true;
                    fetch("{{ route('stock.quickUpdate') }}", {
                        method: "POST",
                        headers: { 
                            "Content-Type": "application/json", 
                            "X-CSRF-TOKEN": "{{ csrf_token() }}", 
                            "Accept": "application/json" 
                        },
                        body: JSON.stringify({ 
                            product_variant_id: this.activeVariantId, 
                            adjustment: this.adjustment 
                        })
                    })
                    .then(async res => {
                        const data = await res.json();
                        if (!res.ok) throw new Error(data.message || 'Terjadi kesalahan');
                        return data;
                    })
                    .then((data) => { 
                        Swal.fire({ icon: 'success', title: 'Berhasil!', text: data.message, timer: 1500 });
                        setTimeout(() => window.location.reload(), 1500);
                    })
                    .catch(err => Swal.fire({ icon: 'error', title: 'Error', text: err.message }))
                    .finally(() => this.loading = false);
                }
            }
        }

        function confirmDelete(productId) {
            Swal.fire({
                title: 'Hapus Produk?',
                text: "Data tidak bisa dikembalikan!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ef4444',
                cancelButtonColor: '#6b4c31',
                confirmButtonText: 'Ya, Hapus!',
                cancelButtonText: 'Batal',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    document.getElementById('delete-form-' + productId).submit();
                }
            });
        }
    </script>
</x-app-layout>