@extends('layouts.app')

@section('breadcrumb')
    {{ $product->name }}
@endsection


@php
    $siteName = \App\Models\Setting::get('site_name', 'Shaa Jewels');
    $productPageTitle = \Illuminate\Support\Str::limit($product->name . ' | Buy Online | ' . $siteName, 64);
@endphp
@section('title', $productPageTitle)
@php
    $productDescription = trim(strip_tags($product->short_desc ?: $product->long_desc ?: ''));
    $productDescription = $productDescription !== '' ? \Illuminate\Support\Str::limit($productDescription, 160) : ('Buy ' . $product->name . ' online at ' . $siteName . '.');
    $productImageUrl = $product->image['large'] ?? $product->image['original'] ?? ($product->image_path ? asset('storage/' . $product->image_path) : url('assets/images/logo.png'));
    $defaultShippingDays = \App\Models\Setting::get('default_shipping_days');
    $initialShippingDays = $product->shipping_days ?? $defaultShippingDays;

    $gaItemProduct = $product;
    if (is_null($product->parent_id) && $product->product_type === 'variant' && $product->variants && $product->variants->isNotEmpty()) {
        $gaVariantCandidate = $product->variants->where('is_active', true)->firstWhere('id', (int) ($initialVariantId ?? 0));
        if (!$gaVariantCandidate) {
            $gaVariantCandidate = $product->variants->where('is_active', true)->first();
        }
        if ($gaVariantCandidate) {
            $gaItemProduct = $gaVariantCandidate;
        }
    }

    $gaViewItemPayload = [
        'currency' => 'INR',
        'value' => (float) ($gaItemProduct->price ?? 0),
        'items' => [[
            'item_id' => (string) ($gaItemProduct->sku ?: $gaItemProduct->id),
            'item_name' => (string) ($gaItemProduct->name ?? $product->name),
            'item_category' => (string) optional($product->category)->name,
            'price' => (float) ($gaItemProduct->price ?? 0),
        ]],
    ];

    $gaVariantLookup = [];
    if (is_null($product->parent_id) && $product->product_type === 'variant' && $product->variants && $product->variants->isNotEmpty()) {
        $gaVariantLookup = $product->variants
            ->where('is_active', true)
            ->mapWithKeys(function ($variant) {
                return [
                    (string) $variant->id => [
                        'item_id' => (string) ($variant->sku ?: $variant->id),
                        'item_name' => (string) ($variant->name ?: $variant->variation_name ?: ''),
                        'price' => (float) $variant->price,
                    ],
                ];
            })
            ->toArray();
    }

    $schemaItemProduct = $gaItemProduct;
    $schemaPrice = (float) ($schemaItemProduct->price ?? 0);
    $schemaSku = (string) ($schemaItemProduct->sku ?: (string) $schemaItemProduct->id);
    $schemaAvailability = ((int) ($schemaItemProduct->current_stock ?? 0) > 0)
        ? 'https://schema.org/InStock'
        : 'https://schema.org/OutOfStock';
    $productSchema = [
        '@context' => 'https://schema.org',
        '@type' => 'Product',
        'name' => (string) $product->name,
        'description' => $productDescription,
        'image' => [$productImageUrl],
        'sku' => $schemaSku,
        'brand' => [
            '@type' => 'Brand',
            'name' => $siteName,
        ],
        'offers' => [
            '@type' => 'Offer',
            'url' => route('product.show', $product->slug),
            'priceCurrency' => 'INR',
            'price' => $schemaPrice,
            'availability' => $schemaAvailability,
        ],
    ];
    if ((int) ($product->rating_count ?? 0) > 0 && (float) ($product->avg_rating ?? 0) > 0) {
        $productSchema['aggregateRating'] = [
            '@type' => 'AggregateRating',
            'ratingValue' => (string) $product->avg_rating,
            'reviewCount' => (string) $product->rating_count,
        ];
    }
    $productSchemaJson = json_encode(
        $productSchema,
        JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT
    );
@endphp
@section('meta_description', $productDescription)
@section('meta_keywords', implode(', ', array_filter([$product->name, optional($product->category)->name, $siteName, 'buy online', 'imitation jewellery India'])))
@section('canonical_url', route('product.show', $product->slug))
@section('og_type', 'product')
@section('og_title', $productPageTitle)
@section('og_description', $productDescription)
@section('og_image', $productImageUrl)
@section('twitter_title', $productPageTitle)
@section('twitter_description', $productDescription)
@section('twitter_image', $productImageUrl)

@push('head')
@if(!empty($productSchemaJson))
<script type="application/ld+json">{!! $productSchemaJson !!}</script>
@endif
@endpush

@push('styles')
<link rel="stylesheet" href="{{ asset('css/homepage.css') }}">
<link rel="stylesheet" href="{{ asset('css/product-gallery.css') }}">
@endpush

@section('content')
<!-- Page Header -->
<!-- <section class="page-header py-4 mb-4" style="background: var(--color-primary); color: white;">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h1 class="mb-2" style="font-size: 2.5rem; font-weight: 700;">{{ strtoupper($product->name) }}</h1>
                    @if($product->barcode)
                        <p class="mb-0" style="font-size: 1.1rem; opacity: 0.9;">Barcode: {{ $product->barcode }}</p>
                    @endif
            </div>
            <div class="col-md-4 text-end">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb justify-content-end mb-0" style="background: transparent;">
                        <li class="breadcrumb-item"><a href="{{ route('home') }}" style="color: rgba(255,255,255,0.8);">Home</a></li>
                            <li class="breadcrumb-item"><a href="{{ route('collections.show', $product->category->slug) }}" style="color: rgba(255,255,255,0.8);">{{ $product->category->name }}</a></li>
                        <li class="breadcrumb-item active" style="color: white;">{{ $product->name }}</li>
                    </ol>
                </nav>
            </div>
        </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; use large URL when product has image variants
                    $allMedia = collect();
                    if ($product->image_path || $product->image) {
                        $mainUrl = $product->image['large'] ?? $product->image['original'] ?? asset('storage/' . $product->image_path);
                        $allMedia->push((object)['type' => 'image', 'path' => $product->image_path, 'url' => $mainUrl, 'id' => 'main', 'variant_id' => null]);
                    }
                    if ($product->media) {
                        $product->media->each(function($media) use ($allMedia) {
                            $allMedia->push((object)['type' => $media->type, 'path' => $media->file_path, 'url' => asset('storage/' . $media->file_path), '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) {
                                $variantUrl = $variant->image['large'] ?? $variant->image['original'] ?? asset('storage/' . $variant->image_path);
                                $allMedia->push((object)['type' => 'image', 'path' => $variant->image_path, 'url' => $variantUrl, 'id' => 'variant-' . $variant->id, 'variant_id' => $variant->id]);
                            }
                        });
                    }
                @endphp

                @if($allMedia->count() > 0)
                    <div class="product-slideshow-container">
                        <!-- Thumbnail Navigation (left side) -->
                        @if($allMedia->count() > 1)
                            <div class="slideshow-thumbnails slideshow-thumbnails-left">
                                @foreach($allMedia as $index => $media)
                                    <div class="slideshow-thumbnail {{ $index === 0 ? 'active' : '' }}" 
                                         data-slide-index="{{ $index }}"
                                         data-variant-id="{{ $media->variant_id ?? '' }}">
                                        @if($media->type === 'image')
                                            <img src="{{ $media->url ?? asset('storage/' . $media->path) }}" 
                                                 alt="Thumbnail {{ $index + 1 }}"
                                                 loading="lazy"
                                                 decoding="async">
                                        @else
                                            <div class="thumbnail-video">
                                                <video src="{{ asset('storage/' . $media->path) }}" 
                                                       muted
                                                       preload="none">
                                                </video>
                                                <i class="bi bi-play-circle-fill"></i>
                                            </div>
                                        @endif
                                    </div>
                                @endforeach
                            </div>
                        @endif

                        <!-- Main Slideshow -->
                        <div class="product-slideshow-wrapper bg-white rounded shadow-sm p-3 position-relative">
                            <div class="product-slideshow" id="productSlideshow">
                                @foreach($allMedia as $index => $media)
                                    <div class="slideshow-slide {{ $index === 0 ? 'active' : '' }}" 
                                         data-slide-index="{{ $index }}"
                                         data-variant-id="{{ $media->variant_id ?? '' }}">
                                        @if($media->type === 'image')
                                            <img src="{{ $media->url ?? asset('storage/' . $media->path) }}" 
                                                 class="img-fluid rounded slideshow-media slideshow-media-image" 
                                                 alt="{{ $product->name }}"
                                                 loading="{{ $index === 0 ? 'eager' : 'lazy' }}"
                                                 decoding="async">
                                        @else
                                            <video src="{{ asset('storage/' . $media->path) }}" 
                                                   class="img-fluid rounded slideshow-media slideshow-media-video" 
                                                   controls
                                                   preload="{{ $index === 0 ? 'auto' : 'metadata' }}">
                                                Your browser does not support the video tag.
                                            </video>
                                        @endif
                                    </div>
                                @endforeach
                            </div>

                            <!-- Navigation Arrows -->
                            @php
                                    $wishlistProductId = $product->id;
                                    $inWishlistPdp = auth()->check() && \App\Helpers\ProductHelper::getWishlistProductIds()->contains($wishlistProductId);
                                @endphp
                                @auth
                                <div class="product-detail-wishlist-wrap">
                                    <form action="{{ route('wishlist.toggle', $wishlistProductId) }}" method="POST" class="wishlist-form d-inline" data-product-id="{{ $wishlistProductId }}">
                                        @csrf
                                        <button type="submit" class="btn product-detail-wishlist-btn wishlist-btn {{ $inWishlistPdp ? 'in-wishlist' : '' }}" title="{{ $inWishlistPdp ? 'Remove from wishlist' : 'Add to wishlist' }}" aria-label="Wishlist">
                                            <i class="bi bi-heart{{ $inWishlistPdp ? '-fill' : '' }}"></i>
                                        </button>
                                    </form>
                                </div>
                                @else
                                <div class="product-detail-wishlist-wrap">
                                    <a href="{{ route('login') }}?redirect={{ 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>
                                @endauth
                            @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">
                                    @foreach($allMedia as $index => $media)
                                        <span class="slideshow-indicator {{ $index === 0 ? 'active' : '' }}" 
                                              data-slide-index="{{ $index }}"></span>
                                    @endforeach
                                </div>
                            @endif
                        </div>
                    </div>
                @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>
                @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">{{ $product->category->name ?? 'Product' }}</span>
                        @if($product->is_featured)
                            <span class="product-detail-badge product-detail-badge-featured">Featured</span>
                        @endif
                    </div>

                    <!-- Title -->
                    <h1 class="product-detail-title mb-2">{{ $product->name }}</h1>

                    <!-- Rating -->
                    @if($product->rating_count > 0)
                        <div class="product-detail-rating mb-3">
                            <x-star-rating :rating="$product->avg_rating" size="lg" />
                            <span class="product-detail-rating-text">{{ number_format($product->avg_rating, 1) }} ({{ $product->rating_count }} {{ Str::plural('review', $product->rating_count) }})</span>
                        </div>
                    @endif

                    <!-- Price -->
                    <div class="product-detail-price-block mb-2">
                        @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();
                            @endphp
                            <span class="product-detail-price" id="productPrice">
                                @if($minPrice == $maxPrice)
                                    ₹{{ number_format($minPrice, 2) }}
                                @else
                                    ₹{{ number_format($minPrice, 2) }}
                                @endif
                                @if($minPrice != $maxPrice)
                                    <span class="product-detail-price-range" id="productPriceRange"> – ₹{{ number_format($maxPrice, 2) }}</span>
                                @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>
                        @else
                            <span class="product-detail-price" id="productPrice">₹{{ number_format($product->price, 2) }}</span>
                            <span class="product-detail-mrp text-muted text-decoration-line-through" id="productMrp" style="{{ !$product->mrp || $product->mrp <= $product->price ? 'display: none;' : '' }}">₹{{ number_format($product->mrp ?? 0, 2) }}</span>
                            @if($product->mrp && $product->mrp > $product->price)
                                <span class="badge badge-discount ms-2">{{ round((($product->mrp - $product->price) / $product->mrp) * 100) }}% OFF</span>
                            @endif

                            <div class="col-12 mb-2">
                                <div class="product-detail-item">
                                    @if($product->current_stock > 0)
                                        <strong class="text-success">
                                            <i class="bi bi-check-circle-fill"></i> In Stock ({{ $product->current_stock }})
                                        </strong>
                                    @else
                                        <strong class="text-danger">
                                            <i class="bi bi-x-circle-fill"></i> Out of Stock
                                        </strong>
                                    @endif
                                </div>
                            </div>
                        @endif
                    </div>

                    <!-- Unit -->
                    @if($product->unit)
                        <p class="product-detail-unit mb-2"><span class="text-muted">Unit:</span> {{ ucfirst($product->unit->name) }}</p>
                    @endif

                    <p class="product-detail-unit mb-2" id="productShippingDaysWrap" style="{{ is_null($initialShippingDays) || $initialShippingDays === '' ? 'display: none;' : '' }}">
                        <span class="text-muted">Shipping:</span>
                        <span id="productShippingDays">
                            @if(!is_null($initialShippingDays) && $initialShippingDays !== '')
                                {{ $initialShippingDays }} day{{ (int) $initialShippingDays === 1 ? '' : 's' }}
                            @endif
                        </span>
                    </p>

                    <!-- Short description -->
                    @if($product->short_desc)
                        <p class="product-detail-desc mb-4">{{ $product->short_desc }}</p>
                    @endif

                    <!-- Variant selection -->
                    @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
                                        ]);
                                    }
                                }
                            }
                        @endphp
                        <div class="product-detail-variants mb-4" id="variantSelectionCard">
                            @if($attributes->isNotEmpty())
                                @foreach($attributes as $attrName => $attrValues)
                                    <div class="product-detail-variant-group mb-3">
                                        <div class="product-detail-variant-label" data-attr-name="{{ $attrName }}">
                                            {{ $attrName }} <span class="product-detail-variant-value" data-attr-name="{{ $attrName }}">—</span>
                                        </div>
                                        <div class="product-detail-variant-btns d-flex flex-wrap gap-2">
                                            @foreach($attrValues as $attrValue)
                                                <button type="button"
                                                        class="product-detail-variant-btn variant-attr-btn"
                                                        data-attribute-id="{{ $attrValue['attribute_id'] }}"
                                                        data-attribute-value-id="{{ $attrValue['id'] }}"
                                                        data-attribute-name="{{ $attrName }}"
                                                        data-attribute-value="{{ $attrValue['value'] }}">
                                                    {{ $attrValue['value'] }}
                                                </button>
                                            @endforeach
                                        </div>
                                    </div>
                                @endforeach
                            @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>
                    @endif

                    <!-- Add to Cart form (includes Quantity) -->
                    <div class="mb-4" id="addToCartSection">
                        <form action="{{ route('cart.store') }}" method="POST" id="addToCartForm">
                            @csrf
                            <input type="hidden" name="update_existing" value="1">
                            @if(is_null($product->parent_id) && $product->product_type === 'variant')
                                <input type="hidden" name="product_id" id="selectedProductId" value="">
                            @else
                                <input type="hidden" name="product_id" value="{{ $product->id }}">
                            @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="{{ (is_null($product->parent_id) && $product->product_type === 'variant') ? 1 : max(1, $cartQuantity ?? 1) }}" min="1"
                                           max="{{ (is_null($product->parent_id) && $product->product_type === 'variant') ? 1 : max(1, $product->current_stock > 100 ? 100 : $product->current_stock) }}"
                                           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"
                                    @if((is_null($product->parent_id) && $product->product_type === 'variant') || $product->current_stock <= 0) disabled @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={{ 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={{ 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={{ 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={{ 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 -->
                    @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">
                                    {!! nl2br(e($product->long_desc)) !!}
                                </div>
                            </div>
                        </div>
                    @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">{{ $relatedSectionTitle ?? 'Related Products' }}</h2>
            <p class="section-subtitle">{{ $relatedSectionSubtitle ?? 'You might also like' }}</p>
        </div>
        @if($relatedProducts->count())
        <div class="row g-4">
            @foreach($relatedProducts as $related)
                <div class="col-6 col-md-4 col-lg-3">
                    @include('partials.product-card', ['product' => $related])
                </div>
            @endforeach
        </div>
        @else
        <p class="text-muted mb-0">No products to show at the moment.</p>
        @endif
    </div>
</section>

<!-- Reviews Section -->
<section class="reviews-section py-2">
    <div class="container">
        <div class="row">
            <div class="col-12">
                <!-- Review Form -->
                @include('partials.review-form', ['product' => $product])

                <!-- Reviews List (only when there are reviews) -->
                @if($reviews->count() > 0)
                    @include('partials.review-list', ['reviews' => $reviews, 'product' => $product])
                @endif
            </div>
        </div>
    </div>
</section>

@push('scripts')
<script src="{{ asset('js/product-gallery.js') }}"></script>

@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->current_stock,
        'shipping_days' => $variant->shipping_days,
        'image_path' => $variant->image_path,
        'attribute_value_ids' => $variant->attributeValues->pluck('id')->toArray(),
        'variation_name' => $variant->variation_name,
    ];
})->values();
@endphp

<script>
(function () {

    const variants = @json($variantsData);
    const initialVariantId = {{ (int) ($initialVariantId ?? 0) }};
    const cartQuantities = @json($variantCartQuantities ?? []);
    const defaultShippingDays = @json($defaultShippingDays);
    const productShippingDays = @json($product->shipping_days);

    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 =
                `{{ 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>
@endif

{{-- GA4: Track product detail page view (view_item) --}}
<x-analytics.ga-events eventName="view_item" :eventData="$gaViewItemPayload" />

<script>
// GA4: Track add-to-cart submissions from product detail page.
(function () {
    const addToCartForm = document.getElementById('addToCartForm');
    if (!addToCartForm) {
        return;
    }

    const productName = @json($product->name);
    const productCategory = @json(optional($product->category)->name);
    const defaultItemId = @json((string) ($product->sku ?: $product->id));
    const defaultPrice = @json((float) ($product->price ?? 0));
    const isVariantParent = @json((bool) (is_null($product->parent_id) && $product->product_type === 'variant'));
    const variantLookup = @json($gaVariantLookup);

    addToCartForm.addEventListener('submit', function () {
        const qtyInput = document.getElementById('qty');
        const qty = Math.max(1, parseInt(qtyInput ? qtyInput.value : '1', 10) || 1);

        let itemId = defaultItemId;
        let itemName = productName;
        let price = defaultPrice;

        if (isVariantParent) {
            const selectedInput = document.getElementById('selectedProductId');
            const selectedVariantId = selectedInput ? String(selectedInput.value || '') : '';
            const selectedVariant = variantLookup[selectedVariantId];
            if (selectedVariant) {
                itemId = selectedVariant.item_id || selectedVariantId;
                itemName = selectedVariant.item_name || productName;
                price = Number(selectedVariant.price || 0);
            }
        }

        window.kkTrack('event', 'add_to_cart', {
            currency: 'INR',
            value: Number((price * qty).toFixed(2)),
            items: [{
                item_id: itemId,
                item_name: itemName,
                item_category: productCategory,
                price: price,
                quantity: qty,
            }],
        });
    });
})();
</script>

<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>

@endpush
@endsection
