<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Produk Kami - <?php echo e(config('app.name', '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;800&family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        * { font-family: 'Poppins', 'Inter', sans-serif; }

        .product-card {
            transition: all 0.3s ease;
            border: 1px solid #fbcfe8;
            background: white;
        }
        .product-card:hover {
            transform: translateY(-6px);
            box-shadow: 0 20px 25px -5px rgba(244, 114, 182, 0.2);
            border-color: #f9a8d4;
        }

        .line-clamp-2 {
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        /* Rating clickable */
        .rating-btn {
            cursor: pointer;
            transition: all 0.2s ease;
            border-radius: 8px;
            padding: 3px 6px;
            margin: -3px -6px;
            display: inline-flex;
            align-items: center;
            gap: 3px;
            background: none;
            border: none;
        }
        .rating-btn:hover {
            background: #fef2f8;
            transform: scale(1.04);
        }
        .rating-btn:active { transform: scale(0.97); }

        /* Modal animation */
        @keyframes modalIn {
            from { opacity: 0; transform: translate(-50%, -48%) scale(0.96); }
            to   { opacity: 1; transform: translate(-50%, -50%) scale(1); }
        }
        #modalUlasan .modal-box {
            animation: modalIn 0.25s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
        }
        
        .bg-gradient-pink {
            background: linear-gradient(135deg, #fdf2f8 0%, #fff1f3 100%);
        }
        
        .border-pink-light {
            border-color: #fbcfe8;
        }
    </style>
</head>
<body class="bg-gradient-pink">

    <!-- ========== HIDDEN AUTH STATUS ========== -->
    <input type="hidden" id="auth-status" value="<?php echo e(auth()->check() ? '1' : '0'); ?>">
    <input type="hidden" id="login-url" value="<?php echo e(route('login')); ?>">

    <!-- ========== NAVBAR ========== -->
    <nav class="bg-white/95 backdrop-blur-md border-b border-pink-light shadow-sm sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
            <div class="flex justify-between items-center">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-gradient-to-br from-pink-400 to-pink-500 rounded-xl flex items-center justify-center">
                        <span class="text-white font-bold text-lg">✨</span>
                    </div>
                    <div>
                        <h1 class="font-bold text-xl text-gray-800"><?php echo e(config('app.name', 'Glow Beauty')); ?></h1>
                        <p class="text-xs text-pink-400">Skincare & Kecantikan</p>
                    </div>
                </div>

                <div class="flex items-center gap-6">
                    <?php if(auth()->guard()->check()): ?>
                        <div class="relative">
                            <button onclick="toggleDropdown()" class="flex items-center gap-2">
                                <div class="w-8 h-8 bg-gradient-to-br from-pink-400 to-pink-500 rounded-full flex items-center justify-center text-white font-semibold">
                                    <?php echo e(substr(Auth::user()->name, 0, 1)); ?>

                                </div>
                                <span class="hidden md:block text-sm"><?php echo e(Auth::user()->name); ?></span>
                            </button>
                            <div id="dropdownMenu" class="hidden absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-pink-100 py-2">
                                <a href="/dashboard" class="block px-4 py-2 text-gray-700 hover:bg-pink-50">Dashboard</a>
                                <form method="POST" action="<?php echo e(route('logout')); ?>">
                                    <?php echo csrf_field(); ?>
                                    <button type="submit" class="w-full text-left px-4 py-2 text-red-600 hover:bg-red-50">Logout</button>
                                </form>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="flex gap-2">
                            <a href="<?php echo e(route('login')); ?>" class="px-4 py-2 text-pink-600 border border-pink-400 rounded-lg hover:bg-pink-50 transition">Masuk</a>
                            <a href="<?php echo e(route('register')); ?>" class="px-4 py-2 bg-gradient-to-r from-pink-400 to-pink-500 text-white rounded-lg hover:from-pink-500 hover:to-pink-600 transition">Daftar</a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </nav>

    <!-- ========== HERO ========== -->
    <div class="bg-gradient-to-r from-pink-400 to-pink-500 text-white py-14">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="max-w-3xl">
                <div class="inline-flex items-center gap-2 bg-white/20 px-4 py-1.5 rounded-full text-sm font-semibold mb-4">
                    <i class="fas fa-store text-xs"></i>
                    <?php echo e(config('app.name', 'Glow Beauty')); ?> — Skincare & Kecantikan
                </div>
                <h1 class="text-4xl lg:text-5xl font-bold mb-4 leading-tight">
                    Koleksi Skincare Pilihan <br class="hidden lg:block"> Untuk Kulit Sehat & Berseri
                </h1>
                <p class="text-lg text-pink-100 leading-relaxed mb-6">
                    Temukan berbagai produk skincare berkualitas dengan bahan alami yang aman untuk kulit. Semua produk kami telah melalui seleksi ketat untuk memastikan kepuasan belanja Anda. Gratis ongkir untuk pembelian minimal Rp 200.000, dan dapatkan diskon <strong class="text-white">10%</strong> di setiap transaksi!
                </p>
                <div class="flex flex-wrap gap-4 text-sm">
                    <div class="flex items-center gap-2 bg-white/20 px-3 py-2 rounded-xl">
                        <i class="fas fa-shield-alt"></i>
                        <span>100% Original & BPOM</span>
                    </div>
                    <div class="flex items-center gap-2 bg-white/20 px-3 py-2 rounded-xl">
                        <i class="fas fa-truck"></i>
                        <span>Pengiriman Cepat & Aman</span>
                    </div>
                    <div class="flex items-center gap-2 bg-white/20 px-3 py-2 rounded-xl">
                        <i class="fas fa-percent"></i>
                        <span>Diskon 10% Min. Rp 200rb</span>
                    </div>
                    <div class="flex items-center gap-2 bg-white/20 px-3 py-2 rounded-xl">
                        <i class="fas fa-headset"></i>
                        <span>Konsultasi Skincare 24/7</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ========== KONTEN UTAMA ========== -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

        <!-- Tombol Kembali -->
        <div class="flex mb-6">
            <a href="<?php echo e(route('welcome')); ?>"
                class="inline-flex items-center gap-2 text-sm font-semibold text-gray-600 hover:text-pink-600 bg-gray-100 hover:bg-pink-50 px-5 py-2.5 rounded-xl transition-colors border border-gray-200 hover:border-pink-200">
                <i class="fas fa-arrow-left text-xs"></i>
                <span>Kembali ke Beranda</span>
            </a>
        </div>

        <!-- ===== FILTER ===== -->
        <div class="bg-white rounded-xl shadow-sm p-6 mb-8 border border-pink-100">
            <div class="flex flex-col md:flex-row md:items-center gap-4">

                <!-- Search -->
                <div class="flex-1 relative">
                    <input type="text"
                           id="searchProduct"
                           placeholder="Cari produk skincare..."
                           class="w-full pl-10 pr-4 py-3 border border-pink-200 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-pink-500 outline-none">
                    <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                </div>

                <!-- Kategori -->
                <select id="categoryFilter"
                        class="px-4 py-3 border border-pink-200 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-pink-500 outline-none">
                    <option value="">Semua Kategori</option>
                    <?php $__currentLoopData = \App\Models\Kategori::all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $kategori): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($kategori->nama); ?>"><?php echo e($kategori->nama); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>

                <!-- Sort -->
                <select id="sortFilter"
                        class="px-4 py-3 border border-pink-200 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-pink-500 outline-none">
                    <option value="terbaru">Terbaru</option>
                    <option value="termurah">Termurah</option>
                    <option value="termahal">Termahal</option>
                    <option value="nama">Nama A-Z</option>
                    <option value="terlaris">Terlaris 🔥</option>
                </select>
            </div>

            <!-- Info hasil filter -->
            <div id="filterInfo" class="mt-3 text-sm text-gray-500 hidden">
                Menampilkan <span id="totalTampil" class="font-semibold text-pink-600">0</span> produk
                <button onclick="resetFilter()" class="ml-2 text-pink-600 underline hover:text-pink-700">Reset filter</button>
            </div>
        </div>

        <!-- ===== GRID PRODUK ===== -->
        <?php if($produks->isEmpty()): ?>
            <div class="text-center py-16">
                <i class="fas fa-box-open text-pink-200 text-6xl mb-4"></i>
                <h3 class="text-2xl font-bold text-gray-700 mb-2">Belum Ada Produk Skincare</h3>
                <p class="text-gray-500">Produk akan segera hadir!</p>
            </div>
        <?php else: ?>
            <div id="productGrid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">

                <?php $__currentLoopData = $produks; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $p): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <?php
                    // Fix: hindari [, $var] = destructuring yang bermasalah di Blade
                    $firstFoto = null;
                    if ($p->foto) {
                        foreach (explode('|', $p->foto) as $fotoItem) {
                            $fotoItem = trim($fotoItem);
                            if (str_contains($fotoItem, ':')) {
                                $fotoParts = explode(':', $fotoItem, 2);
                                $firstFoto = trim($fotoParts[1]);
                                break;
                            } elseif ($fotoItem) {
                                $firstFoto = $fotoItem;
                                break;
                            }
                        }
                    }

                    $stok         = $p->stok ?? 0;
                    $stokColor    = $stok > 10 ? 'bg-pink-500' : ($stok > 0 ? 'bg-amber-400' : 'bg-red-500');
                    $stokText     = $stok > 0 ? 'Stok ' . $stok : 'Habis';
                    $namaKat      = $p->kategori->nama ?? $p->kategori->nama_kategori ?? 'Skincare';

                    // Selalu hitung dari pesanan nyata, bukan kolom terjual (bisa 0 meski ada transaksi)
                    $terjual      = \App\Models\PesananDetail::where('produk_id', $p->id)
                                        ->whereHas('pesanan', function($q) {
                                            $q->whereIn('status', ['selesai','dikirim','diproses','dibayar']);
                                        })->sum('qty');

                    $rataRating   = round(\App\Models\Ulasan::where('produk_id', $p->id)->avg('bintang') ?? 0, 1);
                    $jumlahUlasan = \App\Models\Ulasan::where('produk_id', $p->id)->count();
                    $tokoInfo     = \App\Models\Toko::where('user_id', $p->user_id)->first();
                    $lokasiToko   = $tokoInfo && $tokoInfo->city ? $tokoInfo->city->name
                                    : ($tokoInfo && $tokoInfo->district ? $tokoInfo->district->name : 'Lokasi tidak tersedia');
                    $warnaArr     = $p->warna  ? array_filter(explode(',', $p->warna))  : [];
                    $ukuranArr    = $p->ukuran ? array_filter(explode(',', $p->ukuran)) : [];
                    $isBestSeller = $terjual > 0;
                    $isNew        = $terjual == 0;
                ?>

                <div class="product-card bg-white rounded-2xl shadow-sm overflow-hidden flex flex-col"
                     data-name="<?php echo e(strtolower($p->nama_produk)); ?>"
                     data-category="<?php echo e($namaKat); ?>"
                     data-price="<?php echo e($p->harga); ?>"
                     data-sold="<?php echo e($terjual); ?>"
                     data-date="<?php echo e($p->id); ?>">

                    <!-- IMAGE AREA -->
                    <a href="<?php echo e(route('produk.public.show', $p->id)); ?>" class="block relative bg-gradient-to-br from-pink-50 to-white overflow-hidden" style="height:280px;">
                        <?php if($firstFoto): ?>
                            <img src="<?php echo e(asset('storage/'.$firstFoto)); ?>"
                                 class="w-full h-full object-contain p-3 hover:scale-105 transition-transform duration-500"
                                 alt="<?php echo e($p->nama_produk); ?>" loading="lazy">
                        <?php else: ?>
                            <div class="w-full h-full flex flex-col items-center justify-center text-gray-200">
                                <i class="fas fa-fill-drip text-6xl mb-2"></i>
                                <span class="text-xs text-gray-300">Tidak ada gambar</span>
                            </div>
                        <?php endif; ?>

                        <!-- Badge kategori -->
                        <span class="absolute top-2 left-2 bg-pink-500 text-white text-[10px] font-semibold px-2.5 py-1 rounded-full shadow-sm">
                            <?php echo e($namaKat); ?>

                        </span>

                        <!-- Badge stok -->
                        <span class="absolute top-2 right-2 <?php echo e($stokColor); ?> text-white text-[10px] font-semibold px-2.5 py-1 rounded-full shadow-sm">
                            <?php echo e($stokText); ?>

                        </span>

                        <!-- Badge NEW / BEST SELLER -->
                        <?php if($isNew): ?>
                            <div class="absolute bottom-2 left-2 flex items-center gap-1 bg-pink-500 text-white text-[10px] font-bold px-3 py-1.5 rounded-full shadow-md">
                                <i class="fas fa-seedling text-[9px]"></i> NEW
                            </div>
                        <?php elseif($isBestSeller): ?>
                            <div class="absolute bottom-2 left-2 flex items-center gap-1 bg-yellow-400 text-white text-[10px] font-bold px-3 py-1.5 rounded-full shadow-md">
                                <i class="fas fa-crown text-[9px]"></i> BEST SELLER
                            </div>
                        <?php endif; ?>
                    </a>

                    <!-- CARD BODY -->
                    <div class="p-4 flex flex-col flex-1">

                        <!-- Nama produk -->
                        <h3 class="font-semibold text-gray-800 text-sm line-clamp-2 mb-2 leading-snug" style="min-height:40px;">
                            <?php echo e($p->nama_produk); ?>

                        </h3>

                        <!-- Varian warna & ukuran — fixed height agar semua card sejajar -->
                        <div class="flex items-center gap-2 mb-3" style="min-height:24px;">
                            <?php if(count($warnaArr) > 0): ?>
                                <span class="flex items-center gap-1 text-[11px] text-gray-500 bg-pink-50 px-2 py-0.5 rounded-full border border-pink-100">
                                    <i class="fas fa-palette text-purple-400 text-[9px]"></i>
                                    <?php echo e(count($warnaArr)); ?> varian
                                </span>
                            <?php endif; ?>
                            <?php if(count($ukuranArr) > 0): ?>
                                <span class="flex items-center gap-1 text-[11px] text-gray-500 bg-pink-50 px-2 py-0.5 rounded-full border border-pink-100">
                                    <i class="fas fa-ruler text-blue-400 text-[9px]"></i>
                                    <?php echo e(count($ukuranArr)); ?> ukuran
                                </span>
                            <?php endif; ?>
                        </div>

                        <!-- Harga & terjual -->
                        <div class="flex items-center justify-between mb-3">
                            <span class="text-lg font-bold text-pink-500">
                                Rp <?php echo e(number_format($p->harga, 0, ',', '.')); ?>

                            </span>
                            <?php if($terjual > 0): ?>
                                <span class="flex items-center gap-1 text-[11px] text-pink-500 bg-pink-50 px-2 py-0.5 rounded-full">
                                    <i class="fas fa-fire text-[9px]"></i>
                                    <?php echo e(number_format($terjual)); ?> terjual
                                </span>
                            <?php else: ?>
                                <span class="flex items-center gap-1 text-[11px] text-gray-400 bg-gray-50 px-2 py-0.5 rounded-full">
                                    <i class="fas fa-fire text-[9px]"></i>
                                    0 terjual
                                </span>
                            <?php endif; ?>
                        </div>

                        <div class="border-t border-pink-100 mb-3"></div>

                        <!-- Rating & lokasi — fixed height -->
                        <div class="flex items-center justify-between mb-2" style="min-height:28px;">
                            <button
                                type="button"
                                class="rating-btn"
                                onclick="bukaModalUlasan(<?php echo e($p->id); ?>, '<?php echo e(addslashes($p->nama_produk)); ?>')"
                                title="Lihat ulasan pembeli"
                            >
                                <?php if($rataRating > 0): ?>
                                    <?php for($star = 1; $star <= 5; $star++): ?>
                                        <?php if($star <= floor($rataRating)): ?>
                                            <i class="fas fa-star text-yellow-400 text-[11px]"></i>
                                        <?php elseif($star - $rataRating < 1): ?>
                                            <i class="fas fa-star-half-alt text-yellow-400 text-[11px]"></i>
                                        <?php else: ?>
                                            <i class="far fa-star text-gray-200 text-[11px]"></i>
                                        <?php endif; ?>
                                    <?php endfor; ?>
                                    <span class="text-[11px] font-semibold text-gray-600 ml-1"><?php echo e($rataRating); ?></span>
                                    <span class="text-[11px] text-pink-400 underline ml-0.5">(<?php echo e($jumlahUlasan); ?> ulasan)</span>
                                <?php else: ?>
                                    <?php for($star = 1; $star <= 5; $star++): ?>
                                        <i class="far fa-star text-gray-200 text-[11px]"></i>
                                    <?php endfor; ?>
                                    <span class="text-[11px] text-gray-400 ml-1 underline">Belum ada ulasan</span>
                                <?php endif; ?>
                            </button>

                            <div class="flex items-center gap-1 text-[11px] text-gray-400">
                                <i class="fas fa-map-marker-alt text-pink-300 text-[10px]"></i>
                                <span class="truncate max-w-[80px]"><?php echo e($lokasiToko); ?></span>
                            </div>
                        </div>

                        <!-- Hint text — fixed height -->
                        <p class="text-[10px] text-gray-300 text-center italic mb-3" style="min-height:16px;">
                            Klik untuk lihat detail &amp; beli produk ini
                        </p>

                        <!-- Spacer mendorong tombol ke bawah -->
                        <div class="flex-1"></div>

                        <!-- Tombol aksi — selalu di bawah -->
                        <div class="flex gap-2 pt-2">
                            <?php if(auth()->guard()->check()): ?>
                                <a href="<?php echo e(route('produk.public.show', $p->id)); ?>"
                                   class="flex-1 flex items-center justify-center gap-2 py-3 bg-white hover:bg-pink-50 border border-pink-400 text-pink-500 rounded-xl text-sm font-semibold transition shadow-sm">
                                    <i class="fas fa-shopping-cart text-xs"></i> Keranjang
                                </a>
                                <a href="<?php echo e(route('produk.public.show', $p->id)); ?>"
                                   class="flex-1 flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-semibold transition shadow-sm
                                       <?php echo e($stok < 1 ? 'bg-gray-200 text-gray-400 cursor-not-allowed' : 'bg-gradient-to-r from-pink-400 to-pink-500 hover:from-pink-500 hover:to-pink-600 text-white'); ?>">
                                    <i class="fas fa-bolt text-xs"></i>
                                    <?php echo e($stok < 1 ? 'Habis' : 'Beli'); ?>

                                </a>
                            <?php else: ?>
                                <a href="<?php echo e(route('produk.public.show', $p->id)); ?>"
                                   class="flex-1 flex items-center justify-center gap-2 py-3 bg-white hover:bg-pink-50 border border-pink-400 text-pink-500 rounded-xl text-sm font-semibold transition shadow-sm">
                                    <i class="fas fa-eye text-xs"></i> Lihat
                                </a>
                                <a href="<?php echo e(route('login')); ?>?redirect=<?php echo e(urlencode(route('produk.public.show', $p->id))); ?>"
                                   class="flex-1 flex items-center justify-center gap-2 py-3 bg-gradient-to-r from-pink-400 to-pink-500 hover:from-pink-500 hover:to-pink-600 text-white rounded-xl text-sm font-semibold transition shadow-sm">
                                    <i class="fas fa-bolt text-xs"></i> Beli
                                </a>
                            <?php endif; ?>
                        </div>

                    </div>
                </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

            </div>

            <!-- Empty state saat filter tidak ada hasil -->
            <div id="emptyState" class="hidden text-center py-16">
                <i class="fas fa-search text-pink-200 text-6xl mb-4"></i>
                <h3 class="text-2xl font-bold text-gray-700 mb-2">Produk Skincare Tidak Ditemukan</h3>
                <p class="text-gray-500">Coba kata kunci atau kategori lain</p>
                <button onclick="resetFilter()" class="mt-4 px-6 py-2 bg-gradient-to-r from-pink-400 to-pink-500 text-white rounded-lg hover:from-pink-500 hover:to-pink-600">
                    Lihat Semua Produk
                </button>
            </div>
        <?php endif; ?>

    </div>

    <!-- ========== MODAL ULASAN ========== -->
    <div id="modalUlasan" class="fixed inset-0 z-[9999]" style="display:none;">
        <!-- Backdrop -->
        <div class="absolute inset-0 bg-black/50 backdrop-blur-sm" onclick="tutupModalUlasan()"></div>

        <!-- Modal Box -->
        <div class="modal-box absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-white rounded-2xl shadow-2xl w-full max-w-2xl mx-4 max-h-[85vh] overflow-hidden z-10 flex flex-col">

            <!-- Header -->
            <div class="bg-gradient-to-r from-pink-400 to-pink-500 p-5 text-white flex-shrink-0">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center">
                            <i class="fas fa-star text-white"></i>
                        </div>
                        <div>
                            <h3 class="text-lg font-bold">Ulasan Pembeli</h3>
                            <p id="modalUlasanProduk" class="text-pink-100 text-sm truncate max-w-md"></p>
                        </div>
                    </div>
                    <button onclick="tutupModalUlasan()" class="w-8 h-8 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center transition">
                        <i class="fas fa-times text-white"></i>
                    </button>
                </div>
            </div>

            <!-- Ringkasan Rating (muncul jika ada ulasan) -->
            <div id="ringkasanRating" class="px-6 py-3 border-b border-gray-100 bg-pink-50 items-center gap-4 flex-shrink-0" style="display:none;">
                <div class="text-center">
                    <div id="nilaiRataRating" class="text-4xl font-bold text-pink-500">0</div>
                    <div id="bintangRingkasan" class="flex items-center gap-0.5 mt-1 justify-center"></div>
                    <div class="text-xs text-gray-500 mt-1">dari <span id="totalUlasanRingkasan">0</span> ulasan</div>
                </div>
                <div class="flex-1 space-y-1" id="distribusiBintang"></div>
            </div>

            <!-- Content -->
            <div class="flex-1 overflow-y-auto p-6">
                <div class="text-center py-8" id="loadingUlasan">
                    <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-pink-600 mb-4"></div>
                    <p class="text-gray-600">Memuat ulasan...</p>
                </div>
                <div id="kontenUlasan" style="display:none;"></div>
            </div>

            <!-- Footer -->
            <div class="border-t border-gray-100 p-4 bg-gray-50 flex-shrink-0 flex items-center justify-between">
                <div class="text-sm text-gray-500">
                    <span id="totalUlasan">0</span> ulasan &bull; Rata-rata
                    <span id="rataUlasan">0</span>
                    <i class="fas fa-star text-yellow-400 text-xs ml-0.5"></i>
                </div>
                <button onclick="tutupModalUlasan()" class="text-xs text-gray-400 hover:text-pink-500 transition px-3 py-1.5 rounded-lg hover:bg-pink-50">
                    Tutup
                </button>
            </div>
        </div>
    </div>

    <!-- ========== SCRIPTS ========== -->
    <script>
        // ===== DROPDOWN NAVBAR =====
        function toggleDropdown() {
            document.getElementById('dropdownMenu').classList.toggle('hidden');
        }
        window.onclick = function(e) {
            if (!e.target.closest('.relative')) {
                document.getElementById('dropdownMenu')?.classList.add('hidden');
            }
        }

        // ===== KEYBOARD CLOSE MODAL =====
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') tutupModalUlasan();
        });

        // ===== FILTER & SORT =====
        const grid        = document.getElementById('productGrid');
        const emptyState  = document.getElementById('emptyState');
        const filterInfo  = document.getElementById('filterInfo');
        const totalTampil = document.getElementById('totalTampil');
        const semuaCard   = Array.from(document.querySelectorAll('.product-card'));

        function filterProduk() {
            const search   = document.getElementById('searchProduct').value.toLowerCase().trim();
            const kategori = document.getElementById('categoryFilter').value;
            const sort     = document.getElementById('sortFilter').value;

            let cardLolos = semuaCard.filter(card => {
                const nama      = card.dataset.name || '';
                const katProduk = card.dataset.category || '';
                if (search && !nama.includes(search)) return false;
                if (kategori && katProduk !== kategori) return false;
                return true;
            });

            if (sort === 'termurah') {
                cardLolos.sort((a, b) => Number(a.dataset.price) - Number(b.dataset.price));
            } else if (sort === 'termahal') {
                cardLolos.sort((a, b) => Number(b.dataset.price) - Number(a.dataset.price));
            } else if (sort === 'nama') {
                cardLolos.sort((a, b) => a.dataset.name.localeCompare(b.dataset.name));
            } else if (sort === 'terlaris') {
                cardLolos.sort((a, b) => Number(b.dataset.sold) - Number(a.dataset.sold));
            } else {
                cardLolos.sort((a, b) => Number(b.dataset.date) - Number(a.dataset.date));
            }

            semuaCard.forEach(card => card.style.display = 'none');
            cardLolos.forEach(card => {
                card.style.display = 'block';
                grid.appendChild(card);
            });

            if (cardLolos.length === 0) {
                emptyState?.classList.remove('hidden');
                grid?.classList.add('hidden');
                filterInfo?.classList.add('hidden');
            } else {
                emptyState?.classList.add('hidden');
                grid?.classList.remove('hidden');
                if (search || kategori) {
                    filterInfo?.classList.remove('hidden');
                    if (totalTampil) totalTampil.textContent = cardLolos.length;
                } else {
                    filterInfo?.classList.add('hidden');
                }
            }
        }

        function resetFilter() {
            document.getElementById('searchProduct').value = '';
            document.getElementById('categoryFilter').value = '';
            document.getElementById('sortFilter').value = 'terbaru';
            filterProduk();
        }

        // ===== CART =====
        function addToCart(productId) {
            fetch('/keranjang', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '<?php echo e(csrf_token()); ?>'
                },
                body: JSON.stringify({ produk_id: productId, quantity: 1 })
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    // Toast notif
                    const toast = document.createElement('div');
                    toast.className = 'fixed bottom-6 right-6 bg-green-500 text-white px-5 py-3 rounded-xl shadow-lg z-[99999] flex items-center gap-2 text-sm font-medium';
                    toast.innerHTML = '<i class="fas fa-check-circle"></i> Produk ditambahkan ke keranjang!';
                    document.body.appendChild(toast);
                    setTimeout(() => toast.remove(), 3000);
                }
            })
            .catch(() => alert('Gagal menambah ke keranjang.'));
        }

        // ===== MODAL ULASAN =====
        function bukaModalUlasan(produkId, namaProduk) {
            document.getElementById('modalUlasan').style.display = 'block';
            document.getElementById('modalUlasanProduk').textContent = namaProduk;
            document.body.style.overflow = 'hidden';

            document.getElementById('loadingUlasan').style.display = 'block';
            document.getElementById('kontenUlasan').style.display  = 'none';
            document.getElementById('ringkasanRating').style.display = 'none';

            fetch(`/api/ulasan/produk/${produkId}`)
                .then(r => r.json())
                .then(data => {
                    document.getElementById('loadingUlasan').style.display = 'none';
                    document.getElementById('kontenUlasan').style.display  = 'block';
                    if (data.success) {
                        tampilkanUlasan(data);
                    } else {
                        document.getElementById('kontenUlasan').innerHTML = emptyUlasanHtml();
                    }
                })
                .catch(() => {
                    document.getElementById('loadingUlasan').style.display = 'none';
                    document.getElementById('kontenUlasan').style.display  = 'block';
                    document.getElementById('kontenUlasan').innerHTML =
                        `<div class="text-center py-12">
                            <div class="w-16 h-16 bg-red-50 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-exclamation-circle text-red-400 text-2xl"></i>
                            </div>
                            <p class="text-red-500 font-medium">Gagal memuat ulasan</p>
                            <p class="text-gray-400 text-sm mt-1">Coba lagi nanti</p>
                        </div>`;
                });
        }

        function tutupModalUlasan() {
            document.getElementById('modalUlasan').style.display = 'none';
            document.body.style.overflow = 'auto';
        }

        function emptyUlasanHtml() {
            return `<div class="text-center py-12">
                        <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-comment-slash text-gray-300 text-2xl"></i>
                        </div>
                        <p class="text-gray-500 font-medium">Belum ada ulasan untuk produk ini</p>
                        <p class="text-gray-400 text-sm mt-1">Jadilah yang pertama memberikan ulasan!</p>
                    </div>`;
        }

        function tampilkanUlasan(data) {
            const konten     = document.getElementById('kontenUlasan');
            const ulasanList = data.ulasan || [];
            const total      = ulasanList.length;
            const rata       = parseFloat(data.rata_rating || 0);

            document.getElementById('totalUlasan').textContent = total;
            document.getElementById('rataUlasan').textContent  = rata.toFixed(1);

            if (total === 0) {
                konten.innerHTML = emptyUlasanHtml();
                return;
            }

            // Ringkasan rating
            const ringkasan = document.getElementById('ringkasanRating');
            ringkasan.style.display = 'flex';
            document.getElementById('nilaiRataRating').textContent       = rata.toFixed(1);
            document.getElementById('totalUlasanRingkasan').textContent  = total;

            let bintangHtmlRingkasan = '';
            for (let i = 1; i <= 5; i++) {
                if (i <= Math.floor(rata))     bintangHtmlRingkasan += '<i class="fas fa-star text-yellow-400 text-sm"></i>';
                else if (i - rata < 1)         bintangHtmlRingkasan += '<i class="fas fa-star-half-alt text-yellow-400 text-sm"></i>';
                else                           bintangHtmlRingkasan += '<i class="far fa-star text-gray-300 text-sm"></i>';
            }
            document.getElementById('bintangRingkasan').innerHTML = bintangHtmlRingkasan;

            // Distribusi bintang
            const dist = {5:0, 4:0, 3:0, 2:0, 1:0};
            ulasanList.forEach(u => { if (dist[u.bintang] !== undefined) dist[u.bintang]++; });
            let distHtml = '';
            for (let b = 5; b >= 1; b--) {
                const persen = total > 0 ? Math.round((dist[b] / total) * 100) : 0;
                distHtml += `
                    <div class="flex items-center gap-2">
                        <span class="text-xs text-gray-500 w-3">${b}</span>
                        <i class="fas fa-star text-yellow-400 text-[10px]"></i>
                        <div class="flex-1 bg-gray-200 rounded-full h-1.5">
                            <div class="bg-yellow-400 h-1.5 rounded-full" style="width:${persen}%"></div>
                        </div>
                        <span class="text-xs text-gray-400 w-6">${dist[b]}</span>
                    </div>`;
            }
            document.getElementById('distribusiBintang').innerHTML = distHtml;

            // Daftar ulasan
            const escHtml = str => {
                const d = document.createElement('div');
                d.appendChild(document.createTextNode(str || ''));
                return d.innerHTML;
            };

            const labelBintang = ['', 'Sangat Buruk', 'Buruk', 'Cukup', 'Bagus', 'Sangat Bagus'];
            const warnaBintang = ['', 'text-red-500', 'text-orange-400', 'text-yellow-400', 'text-blue-500', 'text-green-500'];

            let html = '<div class="space-y-4">';
            ulasanList.forEach(ulasan => {
                const tanggal = new Date(ulasan.created_at).toLocaleDateString('id-ID', {
                    day: 'numeric', month: 'long', year: 'numeric'
                });
                let bintangHtml = '';
                for (let i = 1; i <= 5; i++) {
                    bintangHtml += i <= ulasan.bintang
                        ? '<i class="fas fa-star text-yellow-400 text-sm"></i>'
                        : '<i class="far fa-star text-gray-300 text-sm"></i>';
                }
                const avatar   = escHtml(ulasan.user?.name?.charAt(0)?.toUpperCase() || 'U');
                const namaUser = escHtml(ulasan.user?.name || 'Anonymous');
                const labelVal = labelBintang[ulasan.bintang] || '';
                const warnaVal = warnaBintang[ulasan.bintang] || '';

                html += `
                    <div class="bg-pink-50 rounded-xl p-5 border border-pink-100 hover:border-pink-200 transition">
                        <div class="flex items-start justify-between mb-3">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 bg-gradient-to-br from-pink-100 to-pink-200 rounded-full flex items-center justify-center flex-shrink-0">
                                    <span class="text-pink-600 font-bold text-sm">${avatar}</span>
                                </div>
                                <div>
                                    <p class="font-semibold text-gray-800">${namaUser}</p>
                                    <div class="flex items-center gap-1.5 mt-0.5">
                                        <div class="flex items-center gap-0.5">${bintangHtml}</div>
                                        <span class="text-xs font-medium ${warnaVal}">${labelVal}</span>
                                    </div>
                                </div>
                            </div>
                            <span class="text-xs text-gray-400 flex-shrink-0 ml-2 bg-white px-2 py-0.5 rounded-full border border-pink-100">${tanggal}</span>
                        </div>
                        ${ulasan.komentar
                            ? `<div class="bg-white rounded-lg p-4 border border-pink-100 relative">
                                   <i class="fas fa-quote-left text-pink-200 text-lg absolute top-3 left-3"></i>
                                   <p class="text-gray-700 text-sm leading-relaxed pl-6">${escHtml(ulasan.komentar)}</p>
                               </div>`
                            : `<p class="text-gray-400 text-sm italic text-center py-2">— Tidak ada komentar —</p>`}
                    </div>`;
            });
            html += '</div>';
            konten.innerHTML = html;
        }

        // ===== EVENT LISTENERS =====
        document.getElementById('searchProduct').addEventListener('input', filterProduk);
        document.getElementById('categoryFilter').addEventListener('change', filterProduk);
        document.getElementById('sortFilter').addEventListener('change', filterProduk);

        filterProduk();
    </script>

</body>
</html><?php /**PATH C:\laragon\www\ecommerce\resources\views/produk/public-index.blade.php ENDPATH**/ ?>