




<?php $__env->startSection('title', $product->name . ' - ' . \App\Models\Setting::get('site_name', 'KiyoKart')); ?>
<?php
    $siteName = \App\Models\Setting::get('site_name', 'KiyoKart');
    $productDescription = trim(strip_tags($product->short_desc ?: $product->long_desc ?: ''));
    $productDescription = $productDescription !== '' ? \Illuminate\Support\Str::limit($productDescription, 160) : ('Buy ' . $product->name . ' at ' . $siteName . '.');
    $productImageUrl = $product->getImageUrlForContext('detail') ?? url('assets/images/logo.png');
    $defaultShippingDays = \App\Models\Setting::get('default_shipping_days');
    $initialShippingDays = $product->shipping_days ?? $defaultShippingDays;
?>
<?php $__env->startSection('meta_description', $productDescription); ?>
<?php $__env->startSection('meta_keywords', implode(', ', array_filter([$product->name, optional($product->category)->name, $siteName, 'buy online']))); ?>
<?php $__env->startSection('canonical_url', route('product.show', $product->slug)); ?>
<?php $__env->startSection('og_title', $product->name . ' - ' . $siteName); ?>
<?php $__env->startSection('og_description', $productDescription); ?>
<?php $__env->startSection('og_image', $productImageUrl); ?>
<?php $__env->startSection('twitter_title', $product->name . ' - ' . $siteName); ?>
<?php $__env->startSection('twitter_description', $productDescription); ?>
<?php $__env->startSection('twitter_image', $productImageUrl); ?>

<?php $__env->startPush('styles'); ?>
<link rel="stylesheet" href="<?php echo e(asset('css/homepage.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('css/product-gallery.css')); ?>">
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<!-- Page Header -->
 <section class="breadcrumb-bar">
    <div class="container breadcrumb-inner">
        <div class="breadcrumb-left">
            <a href="<?php echo e(route('product.search')); ?>" class="text-white">All Products</a>
            <span>/</span>
            <a href="<?php echo e(route('collections.show', $product->category->slug)); ?>" class="text-white"><?php echo e($product->category->name); ?></a>
            <span>/</span>
            <span class="current"><?php echo e($product->name); ?></span>
        </div>
    </div>
</section>

<!-- Product Detail Section -->
<section class="product-detail-section">
    <div class="container">
        <div class="row g-4">
            <!-- Product Slideshow -->
            <div class="col-md-6">
                <?php
                    // Collect all media (main image + additional images + videos) for slideshow
                    $allMedia = collect();
                    if (($product->image_path || $product->image) && $product->product_type !== 'variant') {
                        $allMedia->push((object) [
                            'type' => 'image',
                            'path' => $product->image_path,
                            'url' => $product->getImageUrlForContext('detail'),
                            'thumb_url' => $product->getImageUrlForContext('thumb'),
                            'id' => 'main',
                            'variant_id' => null,
                        ]);
                    }
                    if ($product->media) {
                        $product->media->each(function ($media) use ($allMedia) {
                            $mediaUrl = storage_url($media->file_path, $media->updated_at ? (string) $media->updated_at->timestamp : null);
                            $allMedia->push((object) [
                                'type' => $media->type,
                                'path' => $media->file_path,
                                'url' => $mediaUrl,
                                'thumb_url' => $mediaUrl,
                                'id' => $media->id,
                                'variant_id' => null,
                            ]);
                        });
                    }
                    if (is_null($product->parent_id) && $product->product_type === 'variant' && $product->variants) {
                        $product->variants->where('is_active', true)->each(function ($variant) use ($allMedia) {
                            if ($variant->image_path || $variant->image) {
                                $allMedia->push((object) [
                                    'type' => 'image',
                                    'path' => $variant->image_path,
                                    'url' => $variant->getImageUrlForContext('detail'),
                                    'thumb_url' => $variant->getImageUrlForContext('thumb'),
                                    'id' => 'variant-' . $variant->id,
                                    'variant_id' => $variant->id,
                                ]);
                            }
                        });
                    }
                ?>

                <?php if($allMedia->count() > 0): ?>
                    <div class="product-slideshow-container">
                        <!-- Thumbnail Navigation (left side) -->
                        <?php if($allMedia->count() > 1): ?>
                            <div class="slideshow-thumbnails slideshow-thumbnails-left">
                                <?php $__currentLoopData = $allMedia; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $media): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <div class="slideshow-thumbnail <?php echo e($index === 0 ? 'active' : ''); ?>" 
                                         data-slide-index="<?php echo e($index); ?>"
                                         data-variant-id="<?php echo e($media->variant_id ?? ''); ?>">
                                        <?php if($media->type === 'image'): ?>
                                            <img src="<?php echo e($media->thumb_url ?? $media->url ?? storage_url($media->path)); ?>"
                                                 alt="Thumbnail <?php echo e($index + 1); ?>"
                                                 loading="lazy"
                                                 decoding="async">
                                        <?php else: ?>
                                            <div class="thumbnail-video">
                                                <video src="<?php echo e(asset('storage/' . $media->path)); ?>" 
                                                       muted
                                                       preload="none">
                                                </video>
                                                <i class="bi bi-play-circle-fill"></i>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </div>
                        <?php endif; ?>

                        <!-- Main Slideshow -->
                        <div class="product-slideshow-wrapper bg-white rounded shadow-sm p-3 position-relative">
                            <div class="product-slideshow" id="productSlideshow">
                                <?php $__currentLoopData = $allMedia; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $media): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <div class="slideshow-slide <?php echo e($index === 0 ? 'active' : ''); ?>" 
                                         data-slide-index="<?php echo e($index); ?>"
                                         data-variant-id="<?php echo e($media->variant_id ?? ''); ?>">
                                        <?php if($media->type === 'image'): ?>
                                            <img src="<?php echo e($media->url ?? storage_url($media->path)); ?>"
                                                 class="img-fluid rounded slideshow-media slideshow-media-image" 
                                                 alt="<?php echo e($product->name); ?>"
                                                 loading="<?php echo e($index === 0 ? 'eager' : 'lazy'); ?>"
                                                 decoding="async">
                                        <?php else: ?>
                                            <video src="<?php echo e(asset('storage/' . $media->path)); ?>" 
                                                   class="img-fluid rounded slideshow-media slideshow-media-video" 
                                                   controls
                                                   preload="<?php echo e($index === 0 ? 'auto' : 'metadata'); ?>">
                                                Your browser does not support the video tag.
                                            </video>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </div>

                            <!-- Navigation Arrows -->
                            <?php
                                    $wishlistProductId = $product->id;
                                    $inWishlistPdp = auth()->check() && \App\Helpers\ProductHelper::getWishlistProductIds()->contains($wishlistProductId);
                                ?>
                                <?php if(auth()->guard()->check()): ?>
                                <div class="product-detail-wishlist-wrap">
                                    <form action="<?php echo e(route('wishlist.toggle', $wishlistProductId)); ?>" method="POST" class="wishlist-form d-inline" data-product-id="<?php echo e($wishlistProductId); ?>">
                                        <?php echo csrf_field(); ?>
                                        <button type="submit" class="btn product-detail-wishlist-btn wishlist-btn <?php echo e($inWishlistPdp ? 'in-wishlist' : ''); ?>" title="<?php echo e($inWishlistPdp ? 'Remove from wishlist' : 'Add to wishlist'); ?>" aria-label="Wishlist">
                                            <i class="bi bi-heart<?php echo e($inWishlistPdp ? '-fill' : ''); ?>"></i>
                                        </button>
                                    </form>
                                </div>
                                <?php else: ?>
                                <div class="product-detail-wishlist-wrap">
                                    <a href="<?php echo e(route('login')); ?>?redirect=<?php echo e(urlencode(request()->url())); ?>" class="btn product-detail-wishlist-btn" title="Login to add to wishlist" aria-label="Wishlist">
                                        <i class="bi bi-heart"></i>
                                    </a>
                                </div>
                                <?php endif; ?>
                            <?php if($allMedia->count() > 1): ?>
                                <button class="slideshow-nav slideshow-prev" id="slideshowPrev">
                                    <i class="bi bi-chevron-left"></i>
                                </button>
                                <button class="slideshow-nav slideshow-next" id="slideshowNext">
                                    <i class="bi bi-chevron-right"></i>
                                </button>

                                <!-- Slide Indicators -->
                                <div class="slideshow-indicators">
                                    <?php $__currentLoopData = $allMedia; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $media): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <span class="slideshow-indicator <?php echo e($index === 0 ? 'active' : ''); ?>" 
                                              data-slide-index="<?php echo e($index); ?>"></span>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="product-image-container bg-white rounded shadow-sm p-3">
                        <div class="bg-light rounded d-flex align-items-center justify-content-center product-image-placeholder">
                            <i class="bi bi-image text-muted product-image-placeholder-icon"></i>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Product Info -->
            <div class="col-md-6">
                <div class="product-info-container product-detail-modern">
                    <!-- Badge (category / tag) -->
                    <div class="product-detail-badge-wrap mb-2">
                        <span class="product-detail-badge"><?php echo e($product->category->name ?? 'Product'); ?></span>
                        <?php if($product->is_featured): ?>
                            <span class="product-detail-badge product-detail-badge-featured">Featured</span>
                        <?php endif; ?>
                    </div>

                    <!-- Title -->
                    <h1 class="product-detail-title mb-2"><?php echo e($product->name); ?></h1>

                    <!-- Rating -->
                    <?php if($product->rating_count > 0): ?>
                        <div class="product-detail-rating mb-3">
                            <?php if (isset($component)) { $__componentOriginalfa87e49ca3cdf62358bbc468aaf3394b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalfa87e49ca3cdf62358bbc468aaf3394b = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.star-rating','data' => ['rating' => $product->avg_rating,'size' => 'lg']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('star-rating'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['rating' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($product->avg_rating),'size' => 'lg']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalfa87e49ca3cdf62358bbc468aaf3394b)): ?>
<?php $attributes = $__attributesOriginalfa87e49ca3cdf62358bbc468aaf3394b; ?>
<?php unset($__attributesOriginalfa87e49ca3cdf62358bbc468aaf3394b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalfa87e49ca3cdf62358bbc468aaf3394b)): ?>
<?php $component = $__componentOriginalfa87e49ca3cdf62358bbc468aaf3394b; ?>
<?php unset($__componentOriginalfa87e49ca3cdf62358bbc468aaf3394b); ?>
<?php endif; ?>
                            <span class="product-detail-rating-text"><?php echo e(number_format($product->avg_rating, 1)); ?> (<?php echo e($product->rating_count); ?> <?php echo e(Str::plural('review', $product->rating_count)); ?>)</span>
                        </div>
                    <?php endif; ?>

                    <!-- Price -->
                    <div class="product-detail-price-block mb-2">
                        <?php if(is_null($product->parent_id) && $product->product_type === 'variant' && $product->variants && $product->variants->isNotEmpty()): ?>
                            <?php
                                $variantPrices = $product->variants->where('is_active', true)->pluck('price')->filter();
                                $minPrice = $variantPrices->min();
                                $maxPrice = $variantPrices->max();
                            ?>
                            <span class="product-detail-price" id="productPrice">
                                <?php if($minPrice == $maxPrice): ?>
                                    ₹<?php echo e(number_format($minPrice, 2)); ?>

                                <?php else: ?>
                                    ₹<?php echo e(number_format($minPrice, 2)); ?>

                                <?php endif; ?>
                                <?php if($minPrice != $maxPrice): ?>
                                    <span class="product-detail-price-range" id="productPriceRange"> – ₹<?php echo e(number_format($maxPrice, 2)); ?></span>
                                <?php endif; ?>
                            </span>
                            
                            <small class="product-detail-price-note mt-1" id="priceNote">(Select variant to see exact price)</small>
                            <div id="selectedVariantInfo" class="selected-variant-info mt-1">
                                <span id="selectedVariantStock"></span>
                                <div id="selectedVariantImage" style="display: none;">
                                    <img src="" alt="Variant" class="variant-image-preview" id="variantImagePreview">
                                </div>
                            </div>
                        <?php else: ?>
                            <span class="product-detail-price" id="productPrice">₹<?php echo e(number_format($product->price, 2)); ?></span>
                            <span class="product-detail-mrp text-muted text-decoration-line-through" id="productMrp" style="<?php echo e(!$product->mrp || $product->mrp <= $product->price ? 'display: none;' : ''); ?>">₹<?php echo e(number_format($product->mrp ?? 0, 2)); ?></span>
                            <?php if($product->mrp && $product->mrp > $product->price): ?>
                                <span class="badge badge-discount ms-2"><?php echo e(round((($product->mrp - $product->price) / $product->mrp) * 100)); ?>% OFF</span>
                            <?php endif; ?>

                            <div class="col-12 mb-2">
                                <div class="product-detail-item">
                                    <?php $onlineStock = $product->onlineAvailableStock(); ?>
                                    <?php if($onlineStock > 0): ?>
                                        <strong class="text-success">
                                            <i class="bi bi-check-circle-fill"></i> In Stock (<?php echo e($onlineStock); ?>)
                                        </strong>
                                        <div class="small text-muted mt-1">
                                            <a href="<?php echo e(route('stores.index')); ?>" class="text-decoration-none">Check store availability</a>
                                        </div>
                                    <?php else: ?>
                                        <strong class="text-danger">
                                            <i class="bi bi-x-circle-fill"></i> Out of Stock
                                        </strong>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Unit -->
                    <?php if($product->unit): ?>
                        <p class="product-detail-unit mb-2"><span class="text-muted">Unit:</span> <?php echo e(ucfirst($product->unit->name)); ?></p>
                    <?php endif; ?>

                    <p class="product-detail-unit mb-2" id="productShippingDaysWrap" style="<?php echo e(is_null($initialShippingDays) || $initialShippingDays === '' ? 'display: none;' : ''); ?>">
                        <span class="text-muted">Shipping:</span>
                        <span id="productShippingDays">
                            <?php if(!is_null($initialShippingDays) && $initialShippingDays !== ''): ?>
                                <?php echo e($initialShippingDays); ?> day<?php echo e((int) $initialShippingDays === 1 ? '' : 's'); ?>

                            <?php endif; ?>
                        </span>
                    </p>

                    <!-- Short description -->
                    <?php if($product->short_desc): ?>
                        <p class="product-detail-desc mb-4"><?php echo e($product->short_desc); ?></p>
                    <?php endif; ?>

                    <!-- Variant selection -->
                    <?php if(is_null($product->parent_id) && $product->product_type === 'variant' && $product->variants && $product->variants->isNotEmpty()): ?>
                        <?php
                            $activeVariants = $product->variants->where('is_active', true);
                            $attributes = collect();
                            foreach ($activeVariants as $variant) {
                                foreach ($variant->attributeValues as $attrValue) {
                                    $attrName = $attrValue->attribute->name;
                                    if (!$attributes->has($attrName)) {
                                        $attributes[$attrName] = collect();
                                    }
                                    $exists = $attributes[$attrName]->contains(fn($item) => $item['id'] == $attrValue->id);
                                    if (!$exists) {
                                        $attributes[$attrName]->push([
                                            'id' => $attrValue->id,
                                            'value' => $attrValue->value,
                                            'attribute_id' => $attrValue->attribute_id
                                        ]);
                                    }
                                }
                            }
                        ?>
                        <div class="product-detail-variants mb-4" id="variantSelectionCard">
                            <?php if($attributes->isNotEmpty()): ?>
                                <?php $__currentLoopData = $attributes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $attrName => $attrValues): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <div class="product-detail-variant-group mb-3">
                                        <div class="product-detail-variant-label" data-attr-name="<?php echo e($attrName); ?>">
                                            <?php echo e($attrName); ?> <span class="product-detail-variant-value" data-attr-name="<?php echo e($attrName); ?>">—</span>
                                        </div>
                                        <div class="product-detail-variant-btns d-flex flex-wrap gap-2">
                                            <?php $__currentLoopData = $attrValues; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $attrValue): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <button type="button"
                                                        class="product-detail-variant-btn variant-attr-btn <?php echo e($attrName == 'Color' ? 'color-variant-btn' : ''); ?>"
                                                        data-attribute-id="<?php echo e($attrValue['attribute_id']); ?>"
                                                        data-attribute-value-id="<?php echo e($attrValue['id']); ?>"
                                                        data-attribute-name="<?php echo e($attrName); ?>"
                                                        data-attribute-value="<?php echo e($attrValue['value']); ?>"
                                                        <?php if($attrName == 'Color'): ?> style="background:<?php echo e(getColorCode($attrValue['value'])); ?>" <?php endif; ?>
                                                        title="<?php echo e($attrName); ?>: <?php echo e($attrValue['value']); ?>">
                                                    <?php if($attrName != 'Color'): ?> <?php echo e($attrValue['value']); ?> <?php endif; ?>
                                                </button>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </div>
                                    </div>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            <?php endif; ?>
                            <div id="noVariantSelected" class="product-detail-variant-msg text-danger small" style="display: none;">
                                Please select all options above.
                            </div>
                            <div id="noVariantExists" class="product-detail-variant-msg text-danger small" style="display: none;">
                                Selected variant does not exist.
                            </div>
                            <div id="variantOutOfStock" class="product-detail-variant-msg text-danger small" style="display: none;">
                                Selected variant is out of stock.
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Add to Cart form (includes Quantity) -->
                    <div class="mb-4" id="addToCartSection">
                        <form action="<?php echo e(route('cart.store')); ?>" method="POST" id="addToCartForm">
                            <?php echo csrf_field(); ?>
                            <input type="hidden" name="update_existing" value="1">
                            <?php if(is_null($product->parent_id) && $product->product_type === 'variant'): ?>
                                <input type="hidden" name="product_id" id="selectedProductId" value="">
                            <?php else: ?>
                                <input type="hidden" name="product_id" value="<?php echo e($product->id); ?>">
                            <?php endif; ?>
                            <div class="product-detail-qty-wrap mb-3">
                                <label class="product-detail-qty-label">Quantity</label>
                                <div class="product-detail-qty-controls">
                                    <button type="button" class="product-detail-qty-btn" id="qtyMinus" aria-label="Decrease quantity">
                                        <i class="bi bi-dash"></i>
                                    </button>
                                    <input type="number" name="qty" id="qty" value="<?php echo e((is_null($product->parent_id) && $product->product_type === 'variant') ? 1 : max(1, $cartQuantity ?? 1)); ?>" min="1"
                                           max="<?php echo e((is_null($product->parent_id) && $product->product_type === 'variant') ? 1 : max(1, min(100, $product->onlineAvailableStock()))); ?>"
                                           class="product-detail-qty-input" aria-label="Quantity">
                                    <button type="button" class="product-detail-qty-btn" id="qtyPlus" aria-label="Increase quantity">
                                        <i class="bi bi-plus"></i>
                                    </button>
                                </div>
                            </div>
                            <button type="submit"
                                    class="btn btn-secondary product-detail-addcart"
                                    id="addToCartBtn"
                                    <?php if((is_null($product->parent_id) && $product->product_type === 'variant') || $product->onlineAvailableStock() <= 0): ?> disabled <?php endif; ?>>
                                <i class="bi bi-cart-plus"></i> Add to Cart
                            </button>
                        </form>
                    </div>

                    <!-- Share -->
                    <div class="product-detail-share">
                        <span class="product-detail-share-label">Share</span>
                        <div class="product-detail-share-icons">
                            <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo e(urlencode(route('product.show', $product->slug))); ?>" target="_blank" rel="noopener" class="product-detail-share-icon" title="Facebook"><i class="bi bi-facebook"></i></a>
                            <a href="https://twitter.com/intent/tweet?url=<?php echo e(urlencode(route('product.show', $product->slug))); ?>" target="_blank" rel="noopener" class="product-detail-share-icon" title="X">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-twitter-x" viewBox="0 0 16 16">
                                    <path d="M12.6.75h2.454l-5.36 6.142L16 15.25h-4.937l-3.867-5.07-4.425 5.07H.316l5.733-6.57L0 .75h5.063l3.495 4.633L12.601.75Zm-.86 13.028h1.36L4.323 2.145H2.865z"/>
                                </svg>
                            </a>
                            <a href="https://www.linkedin.com/sharing/share-offsite/?url=<?php echo e(urlencode(route('product.show', $product->slug))); ?>" target="_blank" rel="noopener" class="product-detail-share-icon" title="LinkedIn"><i class="bi bi-linkedin"></i></a>
                            <a href="https://wa.me/?text=<?php echo e(urlencode(route('product.show', $product->slug))); ?>" target="_blank" rel="noopener" class="product-detail-share-icon" title="WhatsApp"><i class="bi bi-whatsapp"></i></a>
                        </div>
                    </div>

                    <!-- Description Section -->
                    <?php if($product->long_desc): ?>
                        <div class="card mt-4" style="border: 1px solid #e5e7eb;">
                            <div class="card-body">
                                <h5 class="card-title mb-3 variant-selection-title">
                                    <i class="bi bi-file-text"></i> Description
                                </h5>
                                <div class="product-description">
                                    <?php echo nl2br(e($product->long_desc)); ?>

                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Related / Recent Products Section (always shown; recent when no related) -->
<section class="related-products-section py-5 bg-light">
    <div class="container">
        <div class="section-header mb-5">
            <h2 class="section-title"><?php echo e($relatedSectionTitle ?? 'Related Products'); ?></h2>
            <p class="section-subtitle"><?php echo e($relatedSectionSubtitle ?? 'You might also like'); ?></p>
        </div>
        <?php if($relatedProducts->count()): ?>
        <div class="row g-4">
            <?php $__currentLoopData = $relatedProducts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $related): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <div class="col-6 col-md-4 col-lg-3">
                    <?php echo $__env->make('partials.product-card', ['product' => $related], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </div>
        <?php else: ?>
        <p class="text-muted mb-0">No products to show at the moment.</p>
        <?php endif; ?>
    </div>
</section>

<!-- Reviews Section -->
<section class="reviews-section py-2">
    <div class="container">
        <div class="row">
            <div class="col-12">
                <!-- Review Form -->
                <?php echo $__env->make('partials.review-form', ['product' => $product], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

                <!-- Reviews List (only when there are reviews) -->
                <?php if($reviews->count() > 0): ?>
                    <?php echo $__env->make('partials.review-list', ['reviews' => $reviews, 'product' => $product], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<?php $__env->startPush('scripts'); ?>
<script src="<?php echo e(asset('js/product-gallery.js')); ?>"></script>

<?php if(is_null($product->parent_id) && $product->product_type === 'variant' && $product->variants && $product->variants->isNotEmpty()): ?>
<?php
$variantsData = $product->variants->where('is_active', true)->map(function ($variant) {
    return [
        'id' => $variant->id,
        'sku' => $variant->sku,
        'price' => (float) $variant->price,
        'mrp' => $variant->mrp ? (float) $variant->mrp : null,
        'current_stock' => (int) $variant->onlineAvailableStock(),
        'shipping_days' => $variant->shipping_days,
        'image_path' => $variant->image_path,
        'attribute_value_ids' => $variant->attributeValues->pluck('id')->toArray(),
        'variation_name' => $variant->variation_name,
    ];
})->values();
?>

<script>
(function () {

    const variants = <?php echo json_encode($variantsData, 15, 512) ?>;
    const initialVariantId = <?php echo e((int) ($initialVariantId ?? 0)); ?>;
    const cartQuantities = <?php echo json_encode($variantCartQuantities ?? [], 15, 512) ?>;
    const defaultShippingDays = <?php echo json_encode($defaultShippingDays, 15, 512) ?>;
    const productShippingDays = <?php echo json_encode($product->shipping_days, 15, 512) ?>;

    const selectedAttributes = {};
    let selectedVariant = null;

    const totalAttributesCount = document.querySelectorAll(
        '.product-detail-variant-group'
    ).length;

    const addToCartBtn = document.getElementById('addToCartBtn');
    const productIdInput = document.getElementById('selectedProductId');
    const qtyInput = document.getElementById('qty');

    /* ===============================
        ATTRIBUTE BUTTON CLICK
    ================================ */
    document.querySelectorAll('.variant-attr-btn').forEach(btn => {
        btn.addEventListener('click', function () {

            const attributeId = this.dataset.attributeId;
            const valueId = parseInt(this.dataset.attributeValueId);

            // Reset same attribute buttons
            document.querySelectorAll(`[data-attribute-id="${attributeId}"]`)
                .forEach(b => {
                    b.classList.remove('active');
                });

            // Toggle selection
            if (selectedAttributes[attributeId] === valueId) {
                delete selectedAttributes[attributeId];
            } else {
                this.classList.add('active');
                selectedAttributes[attributeId] = valueId;
            }

            // Update "Attr — value" labels
            document.querySelectorAll('.product-detail-variant-value').forEach(span => {
                const name = span.dataset.attrName;
                const btn = document.querySelector('.variant-attr-btn[data-attribute-name="' + name + '"].active');
                span.textContent = btn ? '— ' + btn.dataset.attributeValue : '—';
            });

            updateVariantSelection();
        });
    });

    /* ===============================
        VARIANT MATCHING
    ================================ */
    function updateVariantSelection() {

        const selectedValueIds = Object.values(selectedAttributes);

        // Nothing selected
        if (selectedValueIds.length === 0) {
            resetVariantUI();
            return;
        }

        // Partial selection
        if (selectedValueIds.length < totalAttributesCount) {
            showSelectAllMessage();
            return;
        }

        // Find exact variant
        selectedVariant = variants.find(variant =>
            selectedValueIds.every(id =>
                variant.attribute_value_ids.includes(id)
            )
        );

        if (selectedVariant) {
            applyVariant(selectedVariant);
        } else {
            showNoVariantMessage();
        }
    }

    /* ===============================
        APPLY VARIANT
    ================================ */
    function applyVariant(variant) {

        hideAllAlerts();

        // Set product ID to variant's ID (variant is now a Product)
        if (productIdInput) {
            productIdInput.value = variant.id;
        }

        // Price
        let priceHtml = `₹${variant.price.toFixed(2)}`;
        if (variant.mrp && variant.mrp > variant.price) {
            const discount = Math.round(((variant.mrp - variant.price) / variant.mrp) * 100);
            priceHtml += `
                <span class="text-muted text-decoration-line-through ms-2">₹${variant.mrp.toFixed(2)}</span>
                <span class="badge bg-success ms-2">${discount}% OFF</span>
            `;
        }
        document.getElementById('productPrice').innerHTML = priceHtml;
        document.getElementById('priceNote').style.display = 'none';
        const rangeEl = document.getElementById('productPriceRange');
        if (rangeEl) rangeEl.style.display = 'none';


        // Stock
        if (variant.current_stock > 0) {
            document.getElementById('selectedVariantStock').innerHTML =
                `<strong class="text-success">
                    <i class="bi bi-check-circle-fill"></i> In Stock (${variant.current_stock})
                </strong>`;
            enableCart();
        } else {
            document.getElementById('selectedVariantStock').innerHTML =
                `<span class="badge bg-danger">Out of Stock</span>`;
            disableCart();
            document.getElementById('variantOutOfStock').style.display = 'block';
        }

        // Variant name
        // document.getElementById('selectedVariantName').innerText =
        //     variant.variation_name || variant.sku;

        // Quantity - use cart quantity if variant is in cart, otherwise default to 1
        qtyInput.max = Math.max(1, variant.current_stock);
        const cartQty = cartQuantities[variant.id] || 0;
        qtyInput.value = cartQty > 0 ? Math.min(cartQty, variant.current_stock) : 1;

        // Image
        if (variant.image_path) {
            document.getElementById('variantImagePreview').src =
                `<?php echo e(asset('storage')); ?>/${variant.image_path}`;
            document.getElementById('selectedVariantImage').style.display = 'none';
            switchToVariantImage(variant.id);
        } else {
            document.getElementById('selectedVariantImage').style.display = 'none';
        }

        document.getElementById('selectedVariantInfo').style.display = 'block';

        const shippingEl = document.getElementById('productShippingDays');
        const shippingWrapEl = document.getElementById('productShippingDaysWrap');
        if (shippingEl && shippingWrapEl) {
            let effectiveShippingDays = variant.shipping_days;
            if (effectiveShippingDays === null || effectiveShippingDays === '') {
                effectiveShippingDays = productShippingDays;
            }
            if (effectiveShippingDays === null || effectiveShippingDays === '') {
                effectiveShippingDays = defaultShippingDays;
            }
            if (effectiveShippingDays !== null && effectiveShippingDays !== '') {
                const shippingInt = parseInt(effectiveShippingDays, 10);
                shippingEl.textContent = `${shippingInt} day${shippingInt === 1 ? '' : 's'}`;
                shippingWrapEl.style.display = '';
            } else {
                shippingEl.textContent = '';
                shippingWrapEl.style.display = 'none';
            }
        }
    }

    /* ===============================
        IMAGE SWITCH
    ================================ */
    function switchToVariantImage(variantId) {
        const slides = document.querySelectorAll('.slideshow-slide');
        slides.forEach((slide, index) => {
            if (parseInt(slide.dataset.variantId) === variantId) {
                if (window.productGalleryShowSlide) {
                    window.productGalleryShowSlide(index);
                }
            }
        });
    }

    /* ===============================
        UI HELPERS
    ================================ */
    function resetVariantUI() {
        hideAllAlerts();
        disableCart();
        if (productIdInput) {
            productIdInput.value = '';
        }
    }

    function showSelectAllMessage() {
        hideAllAlerts();
        document.getElementById('noVariantSelected').style.display = 'block';
        disableCart();
    }

    function showNoVariantMessage() {
        hideAllAlerts();
        document.getElementById('noVariantExists').style.display = 'block';
        disableCart();
    }

    function hideAllAlerts() {
        document.getElementById('selectedVariantInfo').style.display = 'none';
        document.getElementById('noVariantSelected').style.display = 'none';
        document.getElementById('variantOutOfStock').style.display = 'none';
        document.getElementById('noVariantExists').style.display = 'none';
    }

    function enableCart() {
        addToCartBtn.disabled = false;
        addToCartBtn.classList.remove('addcart-disabled');
    }

    function disableCart() {
        addToCartBtn.disabled = true;
        addToCartBtn.classList.add('addcart-disabled');
    }

    /* ===============================
        INITIAL VARIANT FROM URL
    ================================ */
    if (initialVariantId > 0) {
        const initialVariant = variants.find(v => v.id === initialVariantId);
        if (initialVariant) {
            initialVariant.attribute_value_ids.forEach(function(attrValueId) {
                const btn = document.querySelector('.variant-attr-btn[data-attribute-value-id="' + attrValueId + '"]');
                if (btn) {
                    const attributeId = btn.dataset.attributeId;
                    const valueId = parseInt(btn.dataset.attributeValueId, 10);
                    selectedAttributes[attributeId] = valueId;
                    document.querySelectorAll('[data-attribute-id="' + attributeId + '"]').forEach(function(b) {
                        b.classList.remove('active');
                    });
                    btn.classList.add('active');
                }
            });
            document.querySelectorAll('.product-detail-variant-value').forEach(function(span) {
                const name = span.dataset.attrName;
                const b = document.querySelector('.variant-attr-btn[data-attribute-name="' + name + '"].active');
                span.textContent = b ? '— ' + b.dataset.attributeValue : '—';
            });
            applyVariant(initialVariant);
        }
    }

})();
</script>
<?php endif; ?>

<script>
(function () {
    const qtyInput = document.getElementById('qty');
    const qtyMinus = document.getElementById('qtyMinus');
    const qtyPlus = document.getElementById('qtyPlus');
    if (!qtyInput || !qtyMinus || !qtyPlus) return;
    function clamp() {
        const min = parseInt(qtyInput.min, 10) || 1;
        const max = parseInt(qtyInput.max, 10) || 999;
        let v = parseInt(qtyInput.value, 10) || min;
        v = Math.max(min, Math.min(max, v));
        qtyInput.value = v;
    }
    qtyMinus.addEventListener('click', function () {
        const min = parseInt(qtyInput.min, 10) || 1;
        let v = parseInt(qtyInput.value, 10) || 1;
        if (v > min) { qtyInput.value = v - 1; clamp(); }
    });
    qtyPlus.addEventListener('click', function () {
        const max = parseInt(qtyInput.max, 10) || 999;
        let v = parseInt(qtyInput.value, 10) || 1;
        if (v < max) { qtyInput.value = v + 1; clamp(); }
    });
    qtyInput.addEventListener('change', clamp);
})();
</script>

<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/shivajewellers_uat/resources/views/product/show.blade.php ENDPATH**/ ?>