@extends('site.layouts.site-layout')
@section('title'){{ $product->title }}@endsection

@section('styles')
<link rel="stylesheet" href="{{ asset('theme/assets/plugin/tagify/tagify.css') }}">
<link rel="stylesheet" href="{{ asset('theme/admin/vendor/libs/sweetalert2/sweetalert2.css') }}">
@endsection

@section('content')

@php
    $requestedVariantId = (int) request()->query('v', 0);
    $defaultVariant = $requestedVariantId
        ? $product->variants->firstWhere('id', $requestedVariantId)
        : null;
    $defaultVariant = $defaultVariant
        ?? $product->variants->firstWhere('is_default', true)
        ?? $product->variants->first();
    $variantGroups  = $product->variants->groupBy('attribute_id');

    // Gallery: featured first, then gallery images
    $galleryImages = collect();
    if ($product->featured_image) {
        $galleryImages->push(['src' => asset('uploads/products/' . $product->featured_image), 'alt' => $product->featured_image_alt ?? $product->title]);
    }
    foreach ($product->images as $img) {
        $galleryImages->push(['src' => asset('uploads/products/' . $img->image), 'alt' => $img->alt ?? $product->title]);
    }
    if ($galleryImages->isEmpty()) {
        $galleryImages->push(['src' => asset('theme/assets/image/product/laptop-1.jpg'), 'alt' => $product->title]);
    }

    // Variant images + slide indices
    $variantImageIndex = [];
    foreach ($product->variants as $v) {
        if ($v->image) {
            $variantImageIndex[$v->id] = $galleryImages->count();
            $galleryImages->push([
                'src' => asset('uploads/products/variants/' . $v->image),
                'alt' => $v->image_alt ?? $v->name ?? $product->title,
            ]);
        }
    }

    $variantsJson = $product->variants->map(fn($v) => [
        'id'             => $v->id,
        'name'           => $v->name,
        'color'          => $v->color,
        'price'          => (float)$v->price,
        'discount_price' => $v->discount_price ? (float)$v->discount_price : null,
        'stock'          => (int)$v->stock,
        'attribute_id'   => $v->attribute_id,
        'image_index'    => $variantImageIndex[$v->id] ?? null,
    ])->keyBy('id')->toJson();

    $breadCategory = $product->categories->first();
    $breadParent   = $breadCategory?->parent;

    $defPrice    = (float)($defaultVariant->price ?? 0);
    $defDiscount = $defaultVariant?->discount_price ? (float)$defaultVariant->discount_price : null;
    $defPct      = ($defDiscount && $defPrice > 0) ? (int) round(($defPrice - $defDiscount) / $defPrice * 100) : 0;
    $defStock    = (int)($defaultVariant->stock ?? 0);
@endphp

<div class="pdx">
    <div class="container-fluid pdx-container">

        {{-- Breadcrumb --}}
        <nav class="pdx-breadcrumb" aria-label="breadcrumb">
            <a href="{{ route('home') }}">خانه</a>
            <span class="sep"><i class="bi bi-chevron-left"></i></span>
            <a href="#">فروشگاه</a>
            @if($breadParent)
                <span class="sep"><i class="bi bi-chevron-left"></i></span>
                <a href="#">{{ $breadParent->name }}</a>
            @endif
            @if($breadCategory)
                <span class="sep"><i class="bi bi-chevron-left"></i></span>
                <a href="{{ route('shop.category', $breadCategory->slug) }}">{{ $breadCategory->name }}</a>
            @endif
            <span class="sep"><i class="bi bi-chevron-left"></i></span>
            <span class="current">{{ $product->title }}</span>
        </nav>

        {{-- ===================== HERO ===================== --}}
        <div class="pdx-card pdx-hero">
            <div class="row g-4">

                {{-- Gallery --}}
                <div class="col-lg-5">
                    <div class="pdx-gallery">
                        <div class="pdx-gallery-tools">
                            <button type="button" class="pdx-tool" data-bs-toggle="modal" data-bs-target="#shareModal" title="اشتراک‌گذاری">
                                <i class="bi bi-share"></i>
                            </button>
                            <button type="button" class="pdx-tool wish-toggle" data-product="{{ $product->id }}" title="افزودن به علاقه‌مندی">
                                <i class="bi {{ auth()->check() && auth()->user()->hasWished($product->id) ? 'bi-heart-fill' : 'bi-heart' }}"></i>
                            </button>
                            <button type="button" class="pdx-tool" title="مقایسه محصول">
                                <i class="bi bi-arrow-left-right"></i>
                            </button>
                        </div>
                        <span class="pdx-off-badge{{ $defPct > 0 ? '' : ' d-none' }}" id="pdxOffBadge">{{ $defPct }}%</span>

                        <div class="swiper product-gallery pdx-gallery-main">
                            <div class="swiper-wrapper" title="برای بزرگنمایی دابل کلیک کنید">
                                @foreach($galleryImages as $gi)
                                <div class="swiper-slide">
                                    <div class="swiper-zoom-container">
                                        <img alt="{{ $gi['alt'] }}" src="{{ $gi['src'] }}" />
                                    </div>
                                </div>
                                @endforeach
                            </div>
                            <div class="swiper-button-next d-none d-lg-flex"></div>
                            <div class="swiper-button-prev d-none d-lg-flex"></div>
                            <div class="swiper-pagination d-none d-lg-block"></div>
                        </div>

                        <div thumbsSlider="" class="swiper product-gallery-thumb pdx-gallery-thumbs">
                            <div class="swiper-wrapper">
                                @foreach($galleryImages as $gi)
                                <div class="swiper-slide">
                                    <img src="{{ $gi['src'] }}" alt="{{ $gi['alt'] }}" />
                                </div>
                                @endforeach
                            </div>
                        </div>
                    </div>
                </div>

                {{-- Info --}}
                <div class="col-lg-4">
                    <h1 class="pdx-title">{{ $product->title }}</h1>
                    @if($product->title_en)
                        <div class="pdx-title-en">{{ $product->title_en }}</div>
                    @endif

                    <div class="pdx-chips">
                        @if($product->brand)
                            <a href="{{ route('shop.brand', $product->brand) }}" class="pdx-chip">
                                <i class="bi bi-award"></i> {{ $product->brand->name }}
                            </a>
                        @endif
                        @if($breadCategory)
                            <a href="{{ route('shop.category', $breadCategory) }}" class="pdx-chip">
                                <i class="bi bi-tag"></i> {{ $breadCategory->name }}
                            </a>
                        @endif
                        <span class="pdx-rating"><i class="bi bi-star-fill"></i> {{ number_format($product->rating, 1) }} <span class="pdx-rating-count">({{ $reviews->count() }} نظر)</span></span>
                    </div>

                    {{-- Variant selector --}}
                    @if($product->type === 'variable' && $variantGroups->isNotEmpty())
                        <div class="pdx-sep"></div>
                        @foreach($variantGroups as $attrId => $groupVariants)
                            @php
                                $groupAttr = $attrId ? $product->attributes->firstWhere('id', $attrId) : null;
                                $groupLabel = $groupAttr ? 'انتخاب ' . $groupAttr->name : 'انتخاب متغیر';
                            @endphp
                            <div class="pdx-variant-group">
                                <h6>{{ $groupLabel }}</h6>
                                <div class="pdx-variants">
                                    @foreach($groupVariants as $variant)
                                        <input type="radio" class="btn-check" name="variant_group_{{ $attrId }}"
                                            id="variant_{{ $variant->id }}" autocomplete="off"
                                            data-variant-id="{{ $variant->id }}"
                                            {{ $variant->id === $defaultVariant?->id ? 'checked' : '' }}>
                                        <label class="pdx-variant-label" for="variant_{{ $variant->id }}">
                                            @if($variant->color && $variant->color !== '#696cff')
                                                <svg class="dot" width="16" height="16" aria-hidden="true">
                                                    <circle cx="8" cy="8" r="7" fill="{{ $variant->color }}" stroke="rgba(0,0,0,.1)" stroke-width="1"/>
                                                </svg>
                                            @endif
                                            {{ $variant->name }}
                                        </label>
                                    @endforeach
                                </div>
                            </div>
                        @endforeach
                    @endif

                    {{-- Short features --}}
                    @if($product->features)
                        <div class="pdx-sep"></div>
                        <div class="pdx-section-label">ویژگی‌های شاخص</div>
                        <div class="pdx-feature-html">{!! $product->features !!}</div>
                    @endif

                    <div class="pdx-sep"></div>
                    <ul class="pdx-guarantees">
                        <li><span class="ic"><i class="bi bi-shield-check"></i></span> {{ $product->warranty ?: 'گارانتی اصالت و سلامت فیزیکی کالا' }}</li>
                        <li><span class="ic"><i class="bi bi-truck"></i></span> ارسال سریع به سراسر کشور</li>
                    </ul>
                </div>

                {{-- Buy box --}}
                <div class="col-lg-3">
                    <div class="pdx-buybox">
                        <div class="pdx-guarantee-mini">
                            <i class="bi bi-patch-check-fill"></i>
                            <span>فروش و ارسال توسط فروشگاه</span>
                        </div>

                        {{-- Stock --}}
                        <div id="product-stock-wrap">
                            @if($defaultVariant && $defStock > 0)
                                <div class="pdx-stock" id="pdxStockRow">
                                    <span class="stock-dot"></span>
                                    <span id="product-stock-text">{{ $defStock }} عدد موجود در انبار</span>
                                </div>
                            @else
                                <div class="pdx-stock out" id="pdxStockRow">
                                    <span class="stock-dot"></span>
                                    <span id="product-stock-text">ناموجود</span>
                                </div>
                            @endif
                        </div>

                        {{-- Price --}}
                        <div class="pdx-price-block">
                            <div id="product-old-price-wrap" class="{{ $defDiscount ? '' : 'd-none' }}">
                                <p class="pdx-old-price" id="product-old-price">{{ number_format($defPrice) }} تومان</p>
                            </div>
                            <p class="pdx-new-price" id="product-new-price">
                                @if($defPrice)
                                    {{ number_format($defDiscount ?? $defPrice) }} <span class="unit">تومان</span>
                                @else
                                    تماس بگیرید
                                @endif
                            </p>
                        </div>

                        {{-- Add to cart --}}
                        <form action="{{ route('cart.add') }}" method="POST" id="addToCartForm">
                            @csrf
                            <input type="hidden" name="variant_id" id="selectedVariantId" value="{{ $defaultVariant?->id }}">
                            <input type="hidden" name="qty" id="selectedQty" value="1">
                            <div class="pdx-buy-row">
                                <div class="pdx-stepper">
                                    <button type="button" class="pdx-step" data-step="up" aria-label="افزایش">+</button>
                                    <input type="text" id="productQtyInput" class="pdx-step-input" value="1" inputmode="numeric" autocomplete="off">
                                    <button type="button" class="pdx-step" data-step="down" aria-label="کاهش">&minus;</button>
                                </div>
                                <button type="submit" id="addToCartBtn" class="pdx-add-btn main-color-one-bg"
                                    {{ ($defaultVariant && $defStock <= 0) ? 'disabled' : '' }}>
                                    <i class="bi bi-basket font-18 text-white"></i>
                                    <span class="text-white">{{ ($defaultVariant && $defStock <= 0) ? 'ناموجود' : 'افزودن به سبد' }}</span>
                                </button>
                            </div>
                        </form>
                        <div id="addToCartError" class="pdx-add-error d-none"></div>

                        @if(!empty($installmentGateways))
                        <div class="pdx-installment-boxes">
                            @foreach($installmentGateways as $gw)
                            <div class="pdx-installment-box">
                                @if(!empty($gw['checkout_logo']))
                                <img src="{{ asset($gw['checkout_logo']) }}" alt="{{ $gw['name'] }}" class="pdx-installment-logo">
                                @else
                                <span class="pdx-installment-logo-fallback">
                                    <i class="bi {{ $gw['checkout_icon'] ?? 'bi-credit-card' }}"></i>
                                </span>
                                @endif
                                <div class="pdx-installment-text">
                                    <div class="pdx-installment-title">امکان خرید اقساطی با «{{ $gw['name'] }}»</div>
                                </div>
                            </div>
                            @endforeach
                        </div>
                        @endif
                    </div>
                </div>

            </div>
        </div>

        {{-- ===================== CONTENT TABS ===================== --}}
        <div class="pdx-card pdx-content">
            <div class="pdx-tabs" id="pdxTabs">
                <button class="pdx-tab-btn active" data-target="pdxTabDesc">توضیحات کالا</button>
                <button class="pdx-tab-btn" data-target="pdxTabSpecs">مشخصات</button>
                <button class="pdx-tab-btn" data-target="pdxTabReviews" id="productComment">دیدگاه‌ها</button>
            </div>

            {{-- Description --}}
            <div class="pdx-tab-body pdx-pane" id="pdxTabDesc">
                <h2 class="pdx-h">معرفی محصول</h2>
                @php
                    $descText = strip_tags($product->description ?? '');
                    $isLong   = mb_strlen($descText) > 500;
                @endphp
                @if($product->description)
                    <div class="pdx-desc-body{{ $isLong ? ' collapsed' : '' }}" id="prodDescBody">
                        {!! $product->description !!}
                    </div>
                    @if($isLong)
                        <button class="pdx-more-btn" id="prodDescMoreBtn"><i class="bi bi-plus-circle me-1"></i> مشاهده بیشتر</button>
                    @endif
                @else
                    <p class="text-muted">توضیحاتی برای این محصول ثبت نشده است.</p>
                @endif
            </div>

            {{-- Specs --}}
            <div class="pdx-tab-body pdx-pane d-none" id="pdxTabSpecs">
                <h2 class="pdx-h">مشخصات فنی</h2>
                @php
                    $specAttrs = $product->attributes->where('show_in_specs', true)->sortBy('sort_order');
                @endphp
                @if($specAttrs->isNotEmpty())
                    <div class="pdx-specs">
                        @foreach($specAttrs as $attr)
                        <div class="pdx-spec-row">
                            <div class="pdx-spec-key">{{ $attr->name }}</div>
                            <div class="pdx-spec-val">{{ implode('، ', $attr->valuesList()) }}</div>
                        </div>
                        @endforeach
                    </div>
                @else
                    <p class="text-muted">مشخصاتی برای این محصول ثبت نشده است.</p>
                @endif
            </div>

            {{-- Reviews --}}
            <div class="pdx-tab-body pdx-pane d-none" id="pdxTabReviews">
                @php
                    $aggregatedPros  = $reviews->flatMap(fn($r) => $r->pros ?? [])->filter()->countBy()->sortDesc()->keys()->take(6)->all();
                    $aggregatedCons  = $reviews->flatMap(fn($r) => $r->cons ?? [])->filter()->countBy()->sortDesc()->keys()->take(6)->all();
                    $totalReviews    = $reviews->count();
                    $ratingCounts    = [5=>0,4=>0,3=>0,2=>0,1=>0];
                    foreach ($reviews as $_r) { $ratingCounts[(int)$_r->rating] = ($ratingCounts[(int)$_r->rating] ?? 0) + 1; }
                @endphp

                <div class="pdx-review-head">
                    <h2 class="pdx-h mb-0">دیدگاه کاربران ({{ $totalReviews }})</h2>
                    <button type="button" class="pdx-btn-review" id="btnAddReview">
                        <i class="bi bi-plus-circle"></i> ثبت دیدگاه
                    </button>
                </div>

                @if(session('review_success'))
                <div class="alert alert-success">{{ session('review_success') }}</div>
                @endif

                {{-- Review form --}}
                @auth
                    @if($hasPurchased && !$hasReviewed)
                    <div id="review-form-section" class="d-none">
                        <div class="pdx-review-form">
                            <h6 class="fw-bold mb-3">دیدگاه خود را بنویسید</h6>
                            <form action="{{ route('product.review', $product) }}" method="POST">
                                @csrf
                                @if($errors->has('review'))
                                <div class="alert alert-danger">{{ $errors->first('review') }}</div>
                                @endif
                                <div class="mb-3">
                                    <label class="form-label fw-bold small">امتیاز شما <span class="text-danger">*</span></label>
                                    <div>
                                        <fieldset class="rating">
                                            <input type="radio" id="star5" name="rating" value="5" {{ old('rating') == 5 ? 'checked' : '' }} /><label for="star5"></label>
                                            <input type="radio" id="star4" name="rating" value="4" {{ old('rating') == 4 ? 'checked' : '' }} /><label for="star4"></label>
                                            <input type="radio" id="star3" name="rating" value="3" {{ old('rating') == 3 ? 'checked' : '' }} /><label for="star3"></label>
                                            <input type="radio" id="star2" name="rating" value="2" {{ old('rating') == 2 ? 'checked' : '' }} /><label for="star2"></label>
                                            <input type="radio" id="star1" name="rating" value="1" {{ old('rating') == 1 ? 'checked' : '' }} /><label for="star1"></label>
                                        </fieldset>
                                    </div>
                                    @error('rating')<div class="text-danger small mt-1">{{ $message }}</div>@enderror
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold small">متن دیدگاه <span class="text-danger">*</span></label>
                                    <textarea class="form-control" name="body" rows="4" placeholder="نظر خود را بنویسید...">{{ old('body') }}</textarea>
                                    @error('body')<div class="text-danger small mt-1">{{ $message }}</div>@enderror
                                </div>
                                <button type="submit" class="pdx-btn-review"><i class="bi bi-send"></i> ثبت دیدگاه</button>
                            </form>
                        </div>
                    </div>
                    @endif
                @endauth

                {{-- AI Summary --}}
                @if($totalReviews > 0)
                <div class="pdx-summary">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <h6 class="fw-bold mb-0">خلاصه دیدگاه خریداران</h6>
                        <span class="pdx-summary-badge"><i class="bi bi-stars"></i> هوش مصنوعی</span>
                    </div>
                    <div class="row gy-3 align-items-center">
                        <div class="col-auto text-center">
                            <div class="pdx-avg">{{ number_format($product->rating, 1) }}</div>
                            <div class="mt-1">
                                @for($i = 1; $i <= 5; $i++)
                                <i class="bi {{ $i <= round($product->rating) ? 'bi-star-fill' : 'bi-star' }} pdx-star pdx-star-sm"></i>
                                @endfor
                            </div>
                            <div class="text-muted small mt-1">از {{ $totalReviews }} دیدگاه</div>
                        </div>
                        <div class="col">
                            @foreach([5,4,3,2,1] as $star)
                            @php $cnt = $ratingCounts[$star]; $pct = $totalReviews > 0 ? round($cnt / $totalReviews * 100) : 0; @endphp
                            <div class="d-flex align-items-center gap-2 mb-1">
                                <span class="small text-muted pdx-bar-label">{{ $star }} <i class="bi bi-star-fill pdx-star pdx-star-xs"></i></span>
                                <div class="pdx-bar"><div class="pdx-bar-fill review-rating-bar-fill" data-width="{{ $pct }}"></div></div>
                                <span class="small text-muted pdx-bar-count">{{ $cnt }}</span>
                            </div>
                            @endforeach
                        </div>
                    </div>
                    @if(count($aggregatedPros) > 0 || count($aggregatedCons) > 0)
                    <div class="row gy-2 mt-2">
                        @if(count($aggregatedPros) > 0)
                        <div class="col-md-6">
                            @foreach($aggregatedPros as $pro)
                            <span class="pdx-point pro"><i class="bi bi-check-circle-fill"></i> {{ $pro }}</span>
                            @endforeach
                        </div>
                        @endif
                        @if(count($aggregatedCons) > 0)
                        <div class="col-md-6">
                            @foreach($aggregatedCons as $con)
                            <span class="pdx-point con"><i class="bi bi-dash-circle-fill"></i> {{ $con }}</span>
                            @endforeach
                        </div>
                        @endif
                    </div>
                    @endif
                </div>
                @endif

                {{-- Individual reviews --}}
                @forelse($reviews as $review)
                <div class="pdx-review">
                    <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
                        <div class="d-flex align-items-center gap-2">
                            <div class="pdx-review-avatar"><img src="{{ asset('theme/assets/image/user.png') }}" alt=""></div>
                            <div>
                                <h6 class="mb-0 fw-bold font-14">{{ trim(($review->user->first_name ?? '') . ' ' . ($review->user->last_name ?? '')) ?: 'کاربر' }}</h6>
                                <span class="text-muted small">{{ \App\Models\Order::toJalaliString($review->created_at) }}</span>
                            </div>
                        </div>
                        <div>
                            @for($i = 1; $i <= 5; $i++)
                            <i class="bi {{ $i <= $review->rating ? 'bi-star-fill' : 'bi-star' }} pdx-star pdx-star-sm"></i>
                            @endfor
                        </div>
                    </div>
                    <p class="mt-3 mb-0 text-muted font-14 pdx-review-text">{{ $review->body }}</p>
                    @if(!empty($review->pros) || !empty($review->cons))
                    <div class="mt-3 d-flex flex-wrap gap-4">
                        @if(!empty($review->pros))
                        <div>
                            <div class="fw-bold small mb-2 pdx-pros-label">نقاط قوت</div>
                            @foreach($review->pros as $pro)<span class="pdx-tag pro">{{ $pro }}</span> @endforeach
                        </div>
                        @endif
                        @if(!empty($review->cons))
                        <div>
                            <div class="fw-bold small mb-2 text-danger">نقاط ضعف</div>
                            @foreach($review->cons as $con)<span class="pdx-tag con">{{ $con }}</span> @endforeach
                        </div>
                        @endif
                    </div>
                    @endif
                </div>
                @empty
                <p class="text-muted">هنوز دیدگاهی برای این محصول ثبت نشده است.</p>
                @endforelse
            </div>
        </div>

        {{-- ===================== SIMILAR PRODUCTS ===================== --}}
        @if($similarProducts->isNotEmpty())
        <div class="pdx-card pdx-content pdx-similar pdx-similar-card hp-products">
            <div class="hp-head">
                <h5 class="hp-head-title"><span class="hp-accent">محصولات</span> مشابه</h5>
                @if($similarViewAllUrl)
                    <a href="{{ $similarViewAllUrl }}" class="hp-head-more">مشاهده همه <i class="bi bi-chevron-double-left"></i></a>
                @endif
            </div>
            <div class="swiper product-slider-swiper">
                <div class="swiper-wrapper">
                    @foreach($similarProducts as $sp)
                        @php
                            $spVariant     = $sp->defaultVariant() ?: $sp->variants->first();
                            $spPrice       = $spVariant ? (float) $spVariant->price : 0;
                            $spFinal       = ($spVariant && $spVariant->discount_price) ? (float) $spVariant->discount_price : $spPrice;
                            $spHasDiscount = $spVariant && $spVariant->discount_price && $spVariant->discount_price < $spVariant->price;
                            $spDiscPct     = ($spHasDiscount && $spPrice > 0) ? round((1 - $spFinal / $spPrice) * 100) : 0;
                            $spSecondImage = $sp->images->first();
                            $spImgBase     = 'uploads/products/';
                            $spInStock     = $sp->isInStock();
                        @endphp
                        <div class="swiper-slide">
                            <div class="product-box hp-product-card {{ $spInStock ? '' : 'out-of-stock' }}">
                                <div class="product-timer">
                                    @if($spDiscPct > 0)
                                        <div class="timer-label">
                                            <span>{{ $spDiscPct }}% تخفیف</span>
                                        </div>
                                    @else
                                        <span></span>
                                    @endif
                                    <div class="product-header-btn">
                                        <a href="" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="مقایسه"><i class="bi bi-shuffle"></i></a>
                                        <a href="javascript:void(0)" class="wish-toggle" data-product="{{ $sp->id }}" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="علاقه‌مندی"><i class="bi {{ auth()->check() && auth()->user()->hasWished($sp->id) ? 'bi-heart-fill' : 'bi-heart' }}"></i></a>
                                        <a href="{{ route('product.show', $sp->slug) }}" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="مشاهده سریع"><i class="bi bi-eye"></i></a>
                                    </div>
                                </div>
                                <a href="{{ route('product.show', $sp->slug) }}">
                                    <div class="product-image">
                                        @if($sp->featured_image)
                                            <img src="{{ asset($spImgBase . $sp->featured_image) }}" loading="lazy" alt="{{ $sp->featured_image_alt ?? $sp->title }}" class="img-fluid one-image">
                                            <img src="{{ $spSecondImage ? asset($spImgBase . $spSecondImage->image) : asset($spImgBase . $sp->featured_image) }}" loading="lazy" alt="{{ $sp->title }}" class="img-fluid two-image">
                                        @else
                                            <img src="{{ asset('theme/assets/image/product/wach1.jpg') }}" loading="lazy" alt="{{ $sp->title }}" class="img-fluid one-image">
                                            <img src="{{ asset('theme/assets/image/product/wach1.jpg') }}" loading="lazy" alt="{{ $sp->title }}" class="img-fluid two-image">
                                        @endif
                                    </div>
                                </a>
                                <div class="product-title d-flex justify-content-between align-items-start">
                                    <div class="title">
                                        <a href="{{ route('product.show', $sp->slug) }}">
                                            <p class="text-overflow-2">{{ $sp->title }}</p>
                                        </a>
                                        @if($sp->title_en)
                                            <span class="text-overflow-1">{{ $sp->title_en }}</span>
                                        @endif
                                    </div>
                                    @if($sp->rating)
                                        <div class="count-rating text-end">
                                            <span>{{ number_format($sp->rating, 1) }}</span>
                                            <i class="bi bi-star-fill"></i>
                                        </div>
                                    @endif
                                </div>
                                <div class="product-action">
                                    <div class="price">
                                        @if($spVariant && $spPrice > 0)
                                            @if($spHasDiscount)
                                                <p class="new-price mb-0">{{ number_format($spFinal) }} تومان</p>
                                                <p class="old-price mt-0">{{ number_format($spPrice) }} تومان</p>
                                            @else
                                                <p class="new-price">{{ number_format($spPrice) }} تومان</p>
                                            @endif
                                        @else
                                            <p class="new-price">تماس بگیرید</p>
                                        @endif
                                    </div>
                                    <div class="link">
                                        @if($spInStock)
                                            <a href="{{ route('product.show', $sp->slug) }}" class="btn border-0 rounded-3 main-color-one-bg">
                                                <i class="bi bi-basket text-white"></i>
                                                <span class="text-white">خرید</span>
                                            </a>
                                        @else
                                            <span class="btn border-0 rounded-3 btn-out-of-stock disabled" aria-disabled="true">
                                                <i class="bi bi-x-circle"></i>
                                                <span>ناموجود</span>
                                            </span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
                <div class="swiper-button-next"></div>
                <div class="swiper-button-prev"></div>
            </div>
        </div>
        @endif

    </div>
</div>

{{-- Share modal --}}
<div class="modal fade" id="shareModal" tabindex="-1" aria-labelledby="shareModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content pdx-share-modal">
            <div class="modal-header">
                <h6 class="modal-title" id="shareModalLabel">اشتراک‌گذاری</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p class="font-14 my-2">این کالا را با دوستان خود به اشتراک بگذارید!</p>
                <button type="button" class="btn d-block text-center main-color-one-bg w-100" id="liveToastBtn">
                    <i class="bi bi-clipboard text-white me-1"></i> کپی کردن لینک
                </button>
                <div class="row mt-3 gy-3">
                    <div class="col-3"><a href="#" class="btn rounded-circle pdx-share-btn pdx-share-whatsapp"><i class="bi bi-whatsapp font-20"></i></a></div>
                    <div class="col-3"><a href="#" class="btn rounded-circle pdx-share-btn pdx-share-twitter"><i class="bi bi-twitter font-20"></i></a></div>
                    <div class="col-3"><a href="#" class="btn rounded-circle pdx-share-btn pdx-share-facebook"><i class="bi bi-facebook font-20"></i></a></div>
                    <div class="col-3"><a href="#" class="btn rounded-circle pdx-share-btn pdx-share-pinterest"><i class="bi bi-pinterest font-20"></i></a></div>
                </div>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script src="{{ asset('theme/admin/vendor/libs/sweetalert2/sweetalert2.js') }}"></script>
<script src="{{ asset('theme/assets/plugin/tagify/jQuery.tagify.min.js') }}"></script>
<script>
// expose variant data globally
window.variants = {!! $variantsJson !!};
window.currentMaxStock = {{ $defStock }};
</script>

<script>
/* ---------- Custom tabs ---------- */
$(function () {
    $('#pdxTabs .pdx-tab-btn').on('click', function () {
        var target = $(this).data('target');
        $('#pdxTabs .pdx-tab-btn').removeClass('active');
        $(this).addClass('active');
        $('.pdx-pane').addClass('d-none');
        $('#' + target).removeClass('d-none');
        if (target === 'pdxTabReviews') animateRatingBars();
    });
});

/* ---------- Description more/less ---------- */
document.addEventListener('DOMContentLoaded', function () {
    var btn  = document.getElementById('prodDescMoreBtn');
    var body = document.getElementById('prodDescBody');
    var fade = document.getElementById('prodDescFade');
    if (!btn) return;
    btn.addEventListener('click', function () {
        body.classList.remove('collapsed');
        if (fade) fade.classList.add('d-none');
        btn.classList.add('d-none');
    });
});

/* ---------- Rating bars animation ---------- */
function animateRatingBars() {
    document.querySelectorAll('.review-rating-bar-fill').forEach(function (el) {
        el.style.width = (el.dataset.width || '0') + '%';
    });
}

/* ---------- Reviews (add button) ---------- */
$(function () {
    var reviewState = {
        isGuest:      {{ auth()->guest() ? 'true' : 'false' }},
        hasPurchased: {{ $hasPurchased ? 'true' : 'false' }},
        hasReviewed:  {{ $hasReviewed ? 'true' : 'false' }},
    };

    @if($errors->any() && $hasPurchased && !$hasReviewed)
    (function () {
        var formSection = document.getElementById('review-form-section');
        if (formSection) formSection.classList.remove('d-none');
        $('#productComment').click();
    })();
    @endif

    @if(session('review_success'))
    $('#productComment').click();
    @endif

    $('#btnAddReview').on('click', function () {
        if (reviewState.isGuest) {
            Swal.fire({
                icon: 'info', title: 'ورود به حساب کاربری',
                text: 'لطفا برای ثبت دیدگاه وارد حساب کاربری خود شوید.',
                confirmButtonText: 'ورود', showCancelButton: true, cancelButtonText: 'بستن', reverseButtons: true,
                customClass: { confirmButton: 'btn btn-primary mx-1', cancelButton: 'btn btn-outline-secondary mx-1' }, buttonsStyling: false,
            }).then(function (r) { if (r.isConfirmed) window.location.href = '{{ route("login") }}'; });
        } else if (!reviewState.hasPurchased) {
            Swal.fire({ icon: 'warning', title: 'خرید محصول الزامی است', text: 'ثبت دیدگاه تنها برای محصولات خریداری‌شده امکان‌پذیر است.',
                confirmButtonText: 'باشه', customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false });
        } else if (reviewState.hasReviewed) {
            Swal.fire({ icon: 'info', title: 'دیدگاه شما ثبت شده است', text: 'شما قبلا دیدگاه خود را ثبت کرده‌اید.',
                confirmButtonText: 'باشه', customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false });
        } else {
            var formSection = document.getElementById('review-form-section');
            if (formSection) { formSection.classList.remove('d-none'); formSection.scrollIntoView({ behavior: 'smooth', block: 'center' }); }
        }
    });

    $('.commentTags').tagify();
});

/* ---------- Variant switching ---------- */
$(function () {
    var variants = window.variants || {};

    function updateVariant(variantId) {
        var v = variants[variantId];
        if (!v) return;

        // price
        var newPriceEl = document.getElementById('product-new-price');
        var oldPriceEl = document.getElementById('product-old-price');
        var oldWrapEl  = document.getElementById('product-old-price-wrap');
        if (newPriceEl) {
            var displayPrice = v.discount_price !== null ? v.discount_price : v.price;
            newPriceEl.innerHTML = displayPrice
                ? displayPrice.toLocaleString('fa-IR') + ' <span class="unit">تومان</span>'
                : 'تماس بگیرید';
        }
        if (oldPriceEl && oldWrapEl) {
            if (v.discount_price !== null) {
                oldPriceEl.textContent = v.price.toLocaleString('fa-IR') + ' تومان';
                oldWrapEl.classList.remove('d-none');
            } else {
                oldWrapEl.classList.add('d-none');
            }
        }

        // discount badge
        var badge = document.getElementById('pdxOffBadge');
        if (badge) {
            if (v.discount_price !== null && v.price > 0) {
                var pct = Math.round((v.price - v.discount_price) / v.price * 100);
                badge.textContent = pct + '%';
                if (pct > 0) badge.classList.remove('d-none');
                else badge.classList.add('d-none');
            } else {
                badge.classList.add('d-none');
            }
        }

        // stock
        var stockRow = document.getElementById('pdxStockRow');
        var stockEl  = document.getElementById('product-stock-text');
        if (stockEl) {
            if (v.stock > 0) {
                stockEl.textContent = v.stock + ' عدد در انبار';
                if (stockRow) stockRow.classList.remove('out');
            } else {
                stockEl.textContent = 'ناموجود';
                if (stockRow) stockRow.classList.add('out');
            }
        }

        // add to cart button
        var $addBtn = $('#addToCartBtn');
        if (v.stock <= 0) $addBtn.prop('disabled', true).find('span').text('ناموجود');
        else              $addBtn.prop('disabled', false).find('span').text('افزودن به سبد');

        // max stock + clamp
        window.currentMaxStock = v.stock;
        if (typeof window.clampQty === 'function') window.clampQty();

        // gallery slide
        var idx = (v.image_index !== null && v.image_index !== undefined) ? v.image_index : 0;
        if (typeof proThumbswiper !== 'undefined') proThumbswiper.slideTo(idx);
        if (typeof proSwiper      !== 'undefined') proSwiper.slideTo(idx);
    }

    document.querySelectorAll('.btn-check[data-variant-id]').forEach(function (radio) {
        radio.addEventListener('change', function () {
            if (this.checked) {
                updateVariant(this.dataset.variantId);
                var vidEl = document.getElementById('selectedVariantId');
                if (vidEl) vidEl.value = this.dataset.variantId;
            }
        });
        if (radio.checked) updateVariant(radio.dataset.variantId);
    });
});

/* ---------- Quantity stepper + add to cart ---------- */
$(function () {
    var $qty = $('#productQtyInput');

    window.clampQty = function () {
        var max = window.currentMaxStock || 0;
        var val = parseInt($qty.val(), 10);
        if (isNaN(val) || val < 1) val = 1;
        if (max > 0 && val > max) val = max;
        $qty.val(val);
        $('.pdx-step[data-step=up]').prop('disabled', max > 0 && val >= max);
        $('.pdx-step[data-step=down]').prop('disabled', val <= 1);
    };

    $('.pdx-step').on('click', function () {
        var dir = $(this).data('step');
        var val = parseInt($qty.val(), 10) || 1;
        val += (dir === 'up') ? 1 : -1;
        $qty.val(val);
        window.clampQty();
    });

    $qty.on('input change keyup', function () {
        $('#addToCartError').addClass('d-none').text('');
        window.clampQty();
        resetAddToCartBtn();
    });

    window.clampQty();

    function currentStock() {
        var vid = $('#selectedVariantId').val();
        return (vid && window.variants[vid]) ? window.variants[vid].stock : 1;
    }

    function resetAddToCartBtn() {
        var $btn = $('#addToCartBtn');
        if (currentStock() <= 0) $btn.prop('disabled', true).find('span').text('ناموجود');
        else                     $btn.prop('disabled', false).find('span').text('افزودن به سبد');
    }
    window.resetAddToCartBtn = resetAddToCartBtn;

    $('#addToCartForm').on('submit', function (e) {
        e.preventDefault();
        $('#selectedQty').val($qty.val());

        var $form = $(this);
        var $btn  = $('#addToCartBtn');
        var $err  = $('#addToCartError');

        $btn.prop('disabled', true).find('span').text('در حال افزودن...');
        $err.addClass('d-none').text('');

        $.post($form.attr('action'), $form.serialize())
            .done(function (d) {
                if (d.count !== undefined) {
                    $('.header-cart-counter').text(d.count).toggleClass('d-none', d.count <= 0);
                }
                Swal.fire({
                    icon: 'success', title: 'محصول به سبد خرید افزوده شد',
                    showCancelButton: true, confirmButtonText: 'رفتن به سبد خرید', cancelButtonText: 'بستن', reverseButtons: true,
                    customClass: { confirmButton: 'btn btn-primary mx-1', cancelButton: 'btn btn-outline-secondary mx-1' }, buttonsStyling: false,
                }).then(function (r) { if (r.isConfirmed) window.location.href = '{{ route("cart.index") }}'; });
            })
            .fail(function (xhr) {
                var msg = (xhr.responseJSON && xhr.responseJSON.message) ? xhr.responseJSON.message : 'خطایی رخ داد.';
                $err.removeClass('d-none').text(msg);
            })
            .always(function () { resetAddToCartBtn(); });
    });
});

/* ---------- Default variant image ---------- */
@php
    $defaultId       = optional($defaultVariant)->id;
    $defaultImgIndex = ($defaultId && isset($variantImageIndex[$defaultId])) ? $variantImageIndex[$defaultId] : null;
@endphp
@if($defaultImgIndex !== null)
if (typeof proThumbswiper !== 'undefined') proThumbswiper.slideTo({{ $defaultImgIndex }});
if (typeof proSwiper      !== 'undefined') proSwiper.slideTo({{ $defaultImgIndex }});
@endif
</script>
@endsection
