<x-app-layout>
    <x-slot name="header">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-3xl font-bold text-amber-700">INTERIA</h1>
                <p class="text-stone-600 mt-2 font-medium">Detail Produk</p>
            </div>
        </div>
    </x-slot>

    <style>
        body { background: #ffffff; }

        .glass-card {
            background: white;
            border: 1px solid #e7e2d9;
            box-shadow: 0 20px 40px -15px rgba(120, 80, 50, 0.08);
            border-radius: 1.5rem;
            overflow: hidden;
        }

        .gradient-primary { background: linear-gradient(135deg, #fef9c3 0%, #fed7aa 50%, #fde68a 100%); color: #78350f !important; font-weight: bold; }
        .gradient-primary:hover {
            background: linear-gradient(135deg, #fde68a 0%, #fdba74 50%, #fef9c3 100%);
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(253, 186, 116, 0.3);
        }

        .gradient-secondary { background: linear-gradient(135deg, #fff7ed 0%, #ffedd5 100%); color: #78350f !important; font-weight: bold; }
        .gradient-secondary:hover {
            background: linear-gradient(135deg, #ffedd5 0%, #fed7aa 100%);
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(253, 186, 116, 0.3);
        }

        .price-gradient {
            background: linear-gradient(135deg, #f97316 0%, #fbbf24 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            font-weight: 800;
        }

        .image-thumbnail {
            transition: all 0.3s ease;
            border: 2px solid transparent;
            cursor: pointer;
        }
        .image-thumbnail:hover { transform: scale(1.05); border-color: #fed7aa; box-shadow: 0 8px 25px rgba(253, 186, 116, 0.2); }
        .image-thumbnail.active { border-color: #fed7aa; }

        /* ── Media Upload ── */
        .media-upload-area {
            border: 2px dashed #fde68a;
            border-radius: 1rem;
            padding: 1.5rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
            background: #f8fafc;
        }
        .media-upload-area:hover { border-color: #f97316; background: #fff7ed; }

        .media-preview-item {
            position: relative;
            border-radius: 0.75rem;
            overflow: hidden;
            border: 1px solid #e7e2d9;
        }
        .media-preview-item .remove-btn {
            position: absolute; top: 4px; right: 4px;
            background: rgba(0,0,0,0.6); color: white;
            border-radius: 50%; width: 22px; height: 22px;
            display: flex; align-items: center; justify-content: center;
            cursor: pointer; font-size: 12px; line-height: 1;
        }

        /* ── Stars ── */
        .star-rating { display: flex; gap: 4px; }
        .star-rating .star {
            font-size: 24px; cursor: pointer; color: #d1c4a8;
            transition: color 0.15s, transform 0.15s;
        }
        .star-rating .star:hover,
        .star-rating .star.active { color: #f59e0b; transform: scale(1.1); }

        .star-sm { font-size: 14px !important; cursor: default !important; transform: none !important; }
        .star-sm.active { color: #f59e0b !important; }

        /* ── Review Card ── */
        .review-card {
            border: 1px solid #e7e2d9;
            border-radius: 1rem;
            padding: 1.25rem;
            background: #fdfbf8;
            transition: box-shadow 0.2s;
        }
        .review-card:hover { box-shadow: 0 4px 16px rgba(120,80,50,0.08); }

        .review-media img, .review-media video {
            width: 80px; height: 80px;
            object-fit: cover;
            border-radius: 0.5rem;
            cursor: pointer;
            border: 1px solid #e7e2d9;
            transition: transform 0.2s;
        }
        .review-media img:hover, .review-media video:hover { transform: scale(1.05); }

        /* ── Lightbox ── */
        #lightbox {
            display: none;
            position: fixed; inset: 0;
            background: rgba(0,0,0,0.88);
            z-index: 9999;
            align-items: center;
            justify-content: center;
        }
        #lightbox.show { display: flex; }
        #lightbox-content { max-width: 90vw; max-height: 90vh; border-radius: 1rem; overflow: hidden; }
        #lightbox-content img, #lightbox-content video { max-width: 90vw; max-height: 90vh; object-fit: contain; }
        #lightbox-close { position: absolute; top: 1.5rem; right: 2rem; color: white; font-size: 2rem; cursor: pointer; }

        /* ── Related ── */
        .related-card {
            background: white;
            border: 1px solid #e7e2d9;
            border-radius: 1.25rem;
            overflow: hidden;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .related-card:hover { transform: translateY(-4px); box-shadow: 0 16px 32px -8px rgba(120,80,50,0.15); }
        .related-card img { transition: transform 0.4s ease; }
        .related-card:hover img { transform: scale(1.04); }

        /* ── Rating Bar ── */
        .rating-bar-fill { height: 6px; border-radius: 3px; background: linear-gradient(90deg, #f59e0b, #f97316); }
        .rating-bar-bg   { height: 6px; border-radius: 3px; background: #e7e2d9; }

        /* ── Tab ── */
        .review-tab.active {
            background: linear-gradient(135deg, #fef9c3 0%, #fed7aa 100%);
            color: #78350f !important;
            font-weight: bold;
        }
        .review-tab { transition: all 0.2s; }
    </style>

    <div class="space-y-8">

            {{-- ══════════════════════════════════════════════════════════════
                 MAIN PRODUCT CARD
            ══════════════════════════════════════════════════════════════ --}}
            <div class="glass-card">
                <div class="grid grid-cols-1 lg:grid-cols-2">

                    {{-- LEFT: Image Gallery --}}
                    <div class="bg-white p-8 lg:p-12">
                        @php
                            $images = $product->image;
                            if (is_string($images)) {
                                $images = json_decode($images, true) ?? [];
                            } elseif (!is_array($images)) {
                                $images = [];
                            }
                        @endphp

                        @if(count($images) > 0)
                            <div class="mb-6">
                                <div class="bg-stone-50 rounded-2xl p-6 flex items-center justify-center h-[400px] border border-stone-200">
                                    <img id="mainProductImage"
                                         src="{{ asset('storage/' . $images[0]) }}"
                                         class="h-full w-full object-contain rounded-xl transition-all duration-300 cursor-zoom-in"
                                         alt="{{ $product->product_name }}"
                                         onclick="openLightbox(this.src, 'image')">
                                </div>
                            </div>
                            <div>
                                <h3 class="text-sm font-semibold text-stone-500 uppercase tracking-wider mb-3">Galeri Produk</h3>
                                <div class="flex gap-3 flex-wrap">
                                    @foreach($images as $index => $img)
                                        <img src="{{ asset('storage/' . $img) }}"
                                             class="w-20 h-20 object-cover rounded-xl image-thumbnail {{ $index === 0 ? 'active' : '' }}"
                                             alt="Thumbnail {{ $index + 1 }}">
                                    @endforeach
                                </div>
                            </div>
                        @else
                            <div class="flex items-center justify-center h-[400px] bg-stone-50 rounded-2xl border border-stone-200">
                                <p class="text-stone-400">Tidak ada gambar</p>
                            </div>
                        @endif
                    </div>

                    {{-- RIGHT: Product Info --}}
                    <div class="p-8 lg:p-12 bg-white border-l border-stone-100">

                        {{-- Badges --}}
                        <div class="flex flex-wrap gap-2 mb-4">
                            <span class="px-3 py-1.5 bg-amber-50 text-amber-700 rounded-full text-xs font-semibold border border-amber-200">
                                {{ $product->category->category_name ?? 'Tanpa Kategori' }}
                            </span>
                            <span class="px-3 py-1.5 {{ $product->stock > 0 ? 'bg-emerald-50 text-emerald-700 border-emerald-200' : 'bg-rose-50 text-rose-700 border-rose-200' }} rounded-full text-xs font-semibold border">
                                {{ $product->stock > 0 ? $product->stock . ' stok tersedia' : 'Stok Habis' }}
                            </span>
                        </div>

                        {{-- Name --}}
                        <h1 class="text-3xl font-bold text-stone-900 mb-2 leading-tight">{{ $product->product_name }}</h1>
                        <p class="text-stone-400 text-sm mb-6">Ditambahkan pada {{ $product->created_at->format('d F Y') }}</p>

                        {{-- Rating Summary (static display, calculated from reviews) --}}
                        @php
                            $reviews = $product->reviews ?? collect();
                            $avgRating = $reviews->count() ? round($reviews->avg('rating'), 1) : 0;
                            $totalReviews = $reviews->count();
                        @endphp
                        @if($totalReviews > 0)
                        <div class="flex items-center gap-3 mb-6">
                            <div class="star-rating pointer-events-none">
                                @for($i = 1; $i <= 5; $i++)
                                    <span class="star star-sm {{ $i <= round($avgRating) ? 'active' : '' }}">&#9733;</span>
                                @endfor
                            </div>
                            <span class="text-amber-700 font-bold">{{ $avgRating }}</span>
                            <span class="text-stone-400 text-sm">{{ $totalReviews }} ulasan</span>
                        </div>
                        @endif

                        {{-- Price --}}
                        <div class="mb-6 p-5 bg-stone-50 rounded-2xl border border-stone-200">
                            <p class="text-xs text-stone-500 mb-1 uppercase tracking-wider">Harga</p>
                            <p class="text-4xl font-extrabold price-gradient">Rp {{ number_format($product->price, 0, ',', '.') }}</p>
                        </div>

                        {{-- Description --}}
                        <div class="mb-8">
                            <h3 class="text-base font-bold text-stone-700 mb-3">Deskripsi Produk</h3>
                            <div class="bg-stone-50 rounded-xl p-4 border border-stone-200">
                                <p class="text-stone-600 leading-relaxed whitespace-pre-line text-sm">
                                    {{ $product->description ?? 'Tidak ada deskripsi yang tersedia.' }}
                                </p>
                            </div>
                        </div>

                        {{-- Action Buttons --}}
                        <div class="space-y-3">
                            @if(auth()->check() && !auth()->user()->isAdmin())
                                @if($product->stock > 0)
                                    {{-- Buy Now --}}
                                    <form action="{{ route('order.buyNow') }}" method="POST">
                                        @csrf
                                        <input type="hidden" name="product_id" value="{{ $product->product_id }}">
                                        <button type="submit"
                                            class="w-full gradient-primary text-white font-bold py-3.5 rounded-xl shadow-lg hover:shadow-xl transition duration-200 flex items-center justify-center gap-2">
                                            <i class="fas fa-bolt"></i>
                                            Beli Sekarang
                                        </button>
                                    </form>
                                    {{-- Add to Cart --}}
                                    <form action="{{ route('cart.store') }}" method="POST">
                                        @csrf
                                        <input type="hidden" name="product_id" value="{{ $product->product_id }}">
                                        <button type="submit"
                                            class="w-full bg-amber-50 text-amber-700 border border-amber-300 font-semibold py-3.5 rounded-xl hover:bg-amber-100 transition duration-200 flex items-center justify-center gap-2">
                                            <i class="fas fa-shopping-cart"></i>
                                            Tambah ke Keranjang
                                        </button>
                                    </form>
                                @else
                                    <button disabled class="w-full bg-stone-100 text-stone-400 font-semibold py-3.5 rounded-xl border border-stone-200 cursor-not-allowed">
                                        Stok Habis
                                    </button>
                                @endif
                            @elseif(!auth()->check())
                                <a href="{{ route('login') }}"
                                   class="block w-full gradient-primary text-white font-bold py-3.5 rounded-xl shadow-lg text-center">
                                    <i class="fas fa-sign-in-alt mr-2"></i>Login untuk Membeli
                                </a>
                            @endif

                            {{-- Back Button — subtle, at the bottom --}}
                            <a href="{{ route('product.index') }}"
                               class="block w-full text-center text-stone-400 text-sm hover:text-stone-600 transition py-2">
                                <i class="fas fa-arrow-left mr-1"></i> Kembali ke Daftar Produk
                            </a>
                        </div>

                    </div>{{-- end RIGHT --}}
                </div>
            </div>

            {{-- ══════════════════════════════════════════════════════════════
                 REVIEW SECTION
            ══════════════════════════════════════════════════════════════ --}}
            <div class="glass-card p-8">
                <h2 class="text-2xl font-bold text-stone-800 mb-8 flex items-center gap-3">
                    <span class="text-2xl">⭐</span> Ulasan Pembeli
                </h2>

                {{-- Rating Overview --}}
                @if($totalReviews > 0)
                <div class="grid grid-cols-1 md:grid-cols-3 gap-8 mb-10 p-6 bg-stone-50 rounded-2xl border border-stone-200">
                    {{-- Big Score --}}
                    <div class="flex flex-col items-center justify-center">
                        <p class="text-6xl font-extrabold price-gradient">{{ $avgRating }}</p>
                        <div class="star-rating pointer-events-none my-2">
                            @for($i = 1; $i <= 5; $i++)
                                <span class="star star-sm {{ $i <= round($avgRating) ? 'active' : '' }}">&#9733;</span>
                            @endfor
                        </div>
                        <p class="text-stone-500 text-sm">dari {{ $totalReviews }} ulasan</p>
                    </div>

                    {{-- Bar Chart --}}
                    <div class="md:col-span-2 space-y-2">
                        @for($star = 5; $star >= 1; $star--)
                            @php $count = $reviews->where('rating', $star)->count(); @endphp
                            <div class="flex items-center gap-3">
                                <span class="text-sm text-stone-500 w-8 text-right">{{ $star }}★</span>
                                <div class="flex-1 rating-bar-bg relative">
                                    <div class="rating-bar-fill absolute top-0 left-0"
                                         style="width: {{ $totalReviews ? round(($count/$totalReviews)*100) : 0 }}%"></div>
                                </div>
                                <span class="text-sm text-stone-500 w-6">{{ $count }}</span>
                            </div>
                        @endfor
                    </div>
                </div>
                @endif

                {{-- ── Write Review Form ── --}}
                @auth
                    @if(!auth()->user()->isAdmin())
                        @if($hasPurchased)
                            <div class="mb-10 p-6 bg-amber-50 border border-amber-200 rounded-2xl">
                                <h3 class="text-lg font-bold text-stone-800 mb-5">Tulis Ulasanmu</h3>

                                <form action="{{ route('product.review.store', $product->product_id) }}" method="POST"
                                      enctype="multipart/form-data" id="reviewForm">
                                    @csrf

                                    {{-- Star Rating Input --}}
                                    <div class="mb-5">
                                        <label class="block text-sm font-semibold text-stone-600 mb-2">Rating</label>
                                        <div class="star-rating" id="starInput">
                                            @for($i = 1; $i <= 5; $i++)
                                                <span class="star" data-value="{{ $i }}">&#9733;</span>
                                            @endfor
                                        </div>
                                        <input type="hidden" name="rating" id="ratingValue" value="">
                                        @error('rating') <p class="text-red-500 text-xs mt-1">{{ $message }}</p> @enderror
                                    </div>

                                    {{-- Review Text --}}
                                    <div class="mb-5">
                                        <label class="block text-sm font-semibold text-stone-600 mb-2">Ulasan</label>
                                        <textarea name="comment" rows="4" placeholder="Ceritakan pengalamanmu dengan produk ini..."
                                            class="w-full rounded-xl border border-stone-300 p-3 text-stone-700 text-sm focus:outline-none focus:ring-2 focus:ring-amber-400 bg-white resize-none"></textarea>
                                        @error('comment') <p class="text-red-500 text-xs mt-1">{{ $message }}</p> @enderror
                                    </div>

                                    {{-- Media Upload --}}
                                    <div class="mb-5">
                                        <label class="block text-sm font-semibold text-stone-600 mb-2">
                                            Foto / Video <span class="text-stone-400 font-normal">(opsional, maks 5 file)</span>
                                        </label>

                                        <div class="media-upload-area" id="uploadZone" onclick="document.getElementById('mediaInput').click()">
                                            <i class="fas fa-cloud-upload-alt text-2xl text-amber-400 mb-2"></i>
                                            <p class="text-stone-500 text-sm">Klik atau seret foto/video ke sini</p>
                                            <p class="text-stone-400 text-xs mt-1">JPG, PNG, MP4 — maks 10MB per file</p>
                                        </div>
                                        <input type="file" id="mediaInput" name="media[]" multiple accept="image/*,video/*" class="hidden">

                                        <div id="mediaPreviews" class="grid grid-cols-5 gap-3 mt-3"></div>
                                    </div>

                                    <button type="submit"
                                        class="gradient-primary text-white font-semibold px-8 py-3 rounded-xl shadow-md hover:shadow-lg transition duration-200">
                                        <i class="fas fa-paper-plane mr-2"></i>Kirim Ulasan
                                    </button>
                                </form>
                            </div>
                        @else
                            <div class="mb-8 p-5 bg-stone-50 border border-stone-200 rounded-xl text-center">
                                <p class="text-stone-500 text-sm font-semibold">
                                    Kamu perlu menyelesaikan pesanan baru untuk dapat menulis ulasan pada produk ini.
                                </p>
                            </div>
                        @endif
                    @endif
                @else
                    <div class="mb-8 p-5 bg-stone-50 border border-stone-200 rounded-xl text-center">
                        <p class="text-stone-500 text-sm">
                            <a href="{{ route('login') }}" class="text-amber-700 font-semibold hover:underline">Login</a>
                            untuk menulis ulasan
                        </p>
                    </div>
                @endauth

                {{-- ── Filter Tabs ── --}}
                @if($totalReviews > 0)
                <div class="flex flex-wrap gap-2 mb-6" id="reviewTabs">
                    <button class="review-tab active px-4 py-2 rounded-full text-sm font-semibold bg-stone-100 text-stone-600 border border-stone-200"
                            data-filter="all">Semua ({{ $totalReviews }})</button>
                    @for($star = 5; $star >= 1; $star--)
                        @php $cnt = $reviews->where('rating', $star)->count(); @endphp
                        @if($cnt > 0)
                        <button class="review-tab px-4 py-2 rounded-full text-sm font-semibold bg-stone-100 text-stone-600 border border-stone-200"
                                data-filter="{{ $star }}">
                            {{ $star }}★ ({{ $cnt }})
                        </button>
                        @endif
                    @endfor
                    <button class="review-tab px-4 py-2 rounded-full text-sm font-semibold bg-stone-100 text-stone-600 border border-stone-200"
                            data-filter="media">Ada Foto/Video</button>
                </div>

                {{-- ── Review List ── --}}
                <div id="reviewList" class="space-y-5">
                    @foreach($reviews->sortByDesc('created_at') as $review)
                    <div class="review-card"
                         data-rating="{{ $review->rating }}"
                         data-has-media="{{ ($review->media && count((array)$review->media) > 0) ? '1' : '0' }}">

                        {{-- Header --}}
                        <div class="flex items-start gap-4 mb-3">
                            <div class="w-10 h-10 rounded-full bg-amber-100 flex items-center justify-center text-amber-700 font-bold text-sm shrink-0">
                                {{ strtoupper(substr($review->user->name ?? 'U', 0, 1)) }}
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="font-semibold text-stone-800 text-sm">{{ $review->user->name ?? 'Pengguna' }}</p>
                                <div class="flex items-center gap-2">
                                    <div class="star-rating pointer-events-none">
                                        @for($i = 1; $i <= 5; $i++)
                                            <span class="star star-sm {{ $i <= $review->rating ? 'active' : '' }}">&#9733;</span>
                                        @endfor
                                    </div>
                                    <span class="text-stone-400 text-xs">{{ $review->created_at->diffForHumans() }}</span>
                                </div>
                            </div>
                        </div>

                        {{-- Comment --}}
                        @if($review->comment)
                        <p class="text-stone-700 text-sm leading-relaxed mb-4">{{ $review->comment }}</p>
                        @endif

                        {{-- Media Grid --}}
                        @php $mediaFiles = is_array($review->media) ? $review->media : (json_decode($review->media, true) ?? []); @endphp
                        @if(count($mediaFiles) > 0)
                        <div class="review-media flex flex-wrap gap-2">
                            @foreach($mediaFiles as $file)
                                @php $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION)); @endphp
                                @if(in_array($ext, ['mp4', 'mov', 'webm']))
                                    <video src="{{ asset('storage/' . $file) }}" class="rounded-lg"
                                           onclick="openLightbox('{{ asset('storage/' . $file) }}', 'video')"
                                           muted playsinline></video>
                                @else
                                    <img src="{{ asset('storage/' . $file) }}" class="rounded-lg"
                                         alt="Review media"
                                         onclick="openLightbox('{{ asset('storage/' . $file) }}', 'image')">
                                @endif
                            @endforeach
                        </div>
                        @endif

                        {{-- Admin Reply Display --}}
                        @if($review->admin_reply)
                        <div class="mt-4 p-4 bg-amber-50 rounded-xl border border-amber-100 flex gap-3">
                            <div class="w-8 h-8 rounded-full bg-amber-200 flex items-center justify-center text-amber-800 text-xs shrink-0 mt-0.5">
                                <i class="fas fa-store"></i>
                            </div>
                            <div class="flex-1">
                                <p class="text-xs font-bold text-amber-800 mb-1">Balasan Penjual</p>
                                <p class="text-sm text-stone-700 leading-relaxed">{{ $review->admin_reply }}</p>
                            </div>
                        </div>
                        @endif

                        {{-- Admin Reply Form (Button + Hidden form) --}}
                        @if(auth()->check() && auth()->user()->isAdmin())
                        <div class="mt-4 pt-3 border-t border-stone-100">
                            <button type="button" onclick="toggleReplyForm({{ $review->id }})" class="text-xs font-semibold text-amber-600 hover:text-amber-800 transition">
                                <i class="fas fa-reply mr-1"></i> {{ $review->admin_reply ? 'Edit Balasan' : 'Balas Ulasan' }}
                            </button>
                            <form action="{{ route('admin.review.reply', $review->id) }}" method="POST" id="reply-form-{{ $review->id }}" class="mt-3 hidden">
                                @csrf
                                <textarea name="admin_reply" rows="3" required class="w-full rounded-xl border border-stone-300 p-3 text-sm focus:ring-2 focus:ring-amber-400 focus:outline-none placeholder-stone-400 transition resize-none" placeholder="Ketik balasan untuk ulasan ini...">{{ $review->admin_reply }}</textarea>
                                <div class="flex justify-end gap-2 mt-2">
                                    <button type="button" onclick="toggleReplyForm({{ $review->id }})" class="px-4 py-2 text-xs font-semibold text-stone-600 bg-stone-100 hover:bg-stone-200 rounded-lg transition duration-200">Batal</button>
                                    <button type="submit" class="gradient-primary px-4 py-2 text-xs font-bold text-white rounded-lg shadow-md hover:shadow-lg transition duration-200">Simpan Balasan</button>
                                </div>
                            </form>
                        </div>
                        @endif

                    </div>
                    @endforeach
                </div>
                @else
                    <div class="text-center py-12 text-stone-400">
                        <i class="fas fa-comment-slash text-4xl mb-3"></i>
                        <p>Belum ada ulasan untuk produk ini.</p>
                    </div>
                @endif
            </div>

            {{-- ══════════════════════════════════════════════════════════════
                 RELATED PRODUCTS
            ══════════════════════════════════════════════════════════════ --}}
            @if(isset($relatedProducts) && $relatedProducts->count() > 0)
            <div class="glass-card p-8">
                <div class="flex items-center justify-between mb-6">
                    <h2 class="text-2xl font-bold text-stone-800">Produk Sejenis</h2>
                    <a href="{{ route('product.index', ['category' => $product->category_id]) }}"
                       class="text-amber-700 text-sm font-semibold hover:underline">
                        Lihat Semua <i class="fas fa-arrow-right ml-1"></i>
                    </a>
                </div>

                <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                    @foreach($relatedProducts as $related)
                    @php
                        $relImages = is_array($related->image) ? $related->image : (json_decode($related->image, true) ?? []);
                        $relImg = $relImages[0] ?? null;
                    @endphp
                    <a href="{{ route('product.show', $related->product_id) }}" class="related-card group">
                        <div class="h-40 bg-stone-50 overflow-hidden flex items-center justify-center p-3">
                            @if($relImg)
                                <img src="{{ asset('storage/' . $relImg) }}"
                                     alt="{{ $related->product_name }}"
                                     class="h-full w-full object-contain">
                            @else
                                <div class="text-stone-300 text-3xl"><i class="fas fa-image"></i></div>
                            @endif
                        </div>
                        <div class="p-3">
                            <p class="text-xs text-stone-400 mb-1">{{ $related->category->category_name ?? '' }}</p>
                            <p class="text-stone-800 font-semibold text-sm leading-tight mb-2 line-clamp-2 group-hover:text-amber-700 transition">
                                {{ $related->product_name }}
                            </p>
                            <p class="font-bold text-amber-700 text-sm">
                                Rp {{ number_format($related->price, 0, ',', '.') }}
                            </p>
                            @if($related->stock <= 0)
                                <span class="text-xs text-rose-500 font-medium">Stok Habis</span>
                            @endif
                        </div>
                    </a>
                    @endforeach
                </div>
            </div>
            @endif

    </div>

    {{-- ══════════════════════════════════════════════════════════════
         LIGHTBOX
    ══════════════════════════════════════════════════════════════ --}}
    <div id="lightbox" onclick="closeLightbox(event)">
        <span id="lightbox-close" onclick="closeLightbox()">&times;</span>
        <div id="lightbox-content"></div>
    </div>

    <script>
    // ── Gallery Thumbnails ─────────────────────────────────────────────────────
    document.addEventListener("DOMContentLoaded", function () {
        const mainImage = document.getElementById("mainProductImage");
        const thumbnails = document.querySelectorAll(".image-thumbnail");

        thumbnails.forEach(thumb => {
            thumb.addEventListener("click", function () {
                thumbnails.forEach(t => t.classList.remove("active"));
                this.classList.add("active");
                mainImage.style.opacity = "0";
                mainImage.style.transform = "scale(0.95)";
                setTimeout(() => {
                    mainImage.src = this.getAttribute("src");
                    mainImage.style.opacity = "1";
                    mainImage.style.transform = "scale(1)";
                }, 180);
            });
        });
    });

    // ── Star Rating Input ──────────────────────────────────────────────────────
    const stars = document.querySelectorAll("#starInput .star");
    const ratingInput = document.getElementById("ratingValue");

    stars.forEach(star => {
        star.addEventListener("mouseenter", function () {
            const val = this.dataset.value;
            stars.forEach(s => s.classList.toggle("active", s.dataset.value <= val));
        });
        star.addEventListener("mouseleave", () => {
            const selected = ratingInput.value;
            stars.forEach(s => s.classList.toggle("active", s.dataset.value <= selected));
        });
        star.addEventListener("click", function () {
            ratingInput.value = this.dataset.value;
            stars.forEach(s => s.classList.toggle("active", s.dataset.value <= this.dataset.value));
        });
    });

    // ── Media Upload Preview ───────────────────────────────────────────────────
    const mediaInput = document.getElementById("mediaInput");
    const previews   = document.getElementById("mediaPreviews");
    let uploadedFiles = [];

    if (mediaInput) {
        mediaInput.addEventListener("change", function () {
            const newFiles = Array.from(this.files);
            uploadedFiles = [...uploadedFiles, ...newFiles].slice(0, 5);

            const dt = new DataTransfer();
            uploadedFiles.forEach(f => dt.items.add(f));
            mediaInput.files = dt.files;

            renderPreviews();
        });
    }

    function renderPreviews() {
        previews.innerHTML = "";
        uploadedFiles.forEach((file, idx) => {
            const wrap = document.createElement("div");
            wrap.className = "media-preview-item";

            const removeBtn = document.createElement("div");
            removeBtn.className = "remove-btn";
            removeBtn.innerHTML = "&times;";
            removeBtn.onclick = () => {
                uploadedFiles.splice(idx, 1);
                const dt = new DataTransfer();
                uploadedFiles.forEach(f => dt.items.add(f));
                mediaInput.files = dt.files;
                renderPreviews();
            };

            if (file.type.startsWith("video/")) {
                const vid = document.createElement("video");
                vid.src = URL.createObjectURL(file);
                vid.style.cssText = "width:100%;height:80px;object-fit:cover;";
                vid.muted = true;
                wrap.appendChild(vid);
            } else {
                const img = document.createElement("img");
                img.src = URL.createObjectURL(file);
                img.style.cssText = "width:100%;height:80px;object-fit:cover;";
                wrap.appendChild(img);
            }

            wrap.appendChild(removeBtn);
            previews.appendChild(wrap);
        });
    }

    // ── Review Filter Tabs ─────────────────────────────────────────────────────
    document.querySelectorAll(".review-tab").forEach(btn => {
        btn.addEventListener("click", function () {
            document.querySelectorAll(".review-tab").forEach(b => b.classList.remove("active"));
            this.classList.add("active");

            const filter = this.dataset.filter;
            document.querySelectorAll(".review-card").forEach(card => {
                if (filter === "all") {
                    card.style.display = "";
                } else if (filter === "media") {
                    card.style.display = card.dataset.hasMedia === "1" ? "" : "none";
                } else {
                    card.style.display = card.dataset.rating === filter ? "" : "none";
                }
            });
        });
    });

    // ── Lightbox ───────────────────────────────────────────────────────────────
    function openLightbox(src, type) {
        const lb      = document.getElementById("lightbox");
        const content = document.getElementById("lightbox-content");
        content.innerHTML = "";

        if (type === "video") {
            const vid = document.createElement("video");
            vid.src = src; vid.controls = true; vid.autoplay = true;
            vid.style.cssText = "max-width:90vw;max-height:90vh;";
            content.appendChild(vid);
        } else {
            const img = document.createElement("img");
            img.src = src;
            img.style.cssText = "max-width:90vw;max-height:90vh;object-fit:contain;border-radius:1rem;";
            content.appendChild(img);
        }

        lb.classList.add("show");
        document.body.style.overflow = "hidden";
    }

    function closeLightbox(e) {
        if (!e || e.target === document.getElementById("lightbox") || e.target.id === "lightbox-close") {
            document.getElementById("lightbox").classList.remove("show");
            document.body.style.overflow = "";
        }
    }

    document.addEventListener("keydown", e => { if (e.key === "Escape") closeLightbox({target: document.getElementById("lightbox")}); });

    // ── Reply Form Toggle ──────────────────────────────────────────────────────
    function toggleReplyForm(reviewId) {
        const form = document.getElementById('reply-form-' + reviewId);
        if (form.classList.contains('hidden')) {
            form.classList.remove('hidden');
        } else {
            form.classList.add('hidden');
        }
    }
    </script>
</x-app-layout>