@extends('site.layouts.site-layout')

@section('title', isset($currentBrand) && $currentBrand
    ? $currentBrand->name
    : (isset($currentCategory) && $currentCategory ? $currentCategory->name : 'فروشگاه'))

@php
    $shopUrl = isset($currentBrand) && $currentBrand
        ? route('shop.brand', $currentBrand->slug)
        : (isset($currentCategory) && $currentCategory
            ? route('shop.category', $currentCategory->slug)
            : route('shop'));
    $baseShopUrl = route('shop');
@endphp

@section('styles')
<link rel="stylesheet" href="{{ asset('theme/assets/plugin/nouislider/nouislider.min.css') }}">
<style>
    .shop-sidebar { position: sticky; top: 20px; }
    .shop-cat-indent-1 { padding-right: 16px; }
    .shop-cat-indent-2 { padding-right: 32px; }
    .shop-cat-indent-3 { padding-right: 48px; }
    .shop-cat-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }
    .shop-cat-row .form-check { margin-bottom: 0; }
    .shop-empty { padding: 60px 20px; text-align: center; color: #aaa; }
    .shop-empty i { font-size: 64px; display: block; margin-bottom: 16px; }
    .pagination .page-link { color: var(--main-color-one); }
    .pagination .page-item.active .page-link { background-color: var(--main-color-one); border-color: var(--main-color-one); color: #fff; }
</style>
@endsection

@section('content')

@if((isset($currentCategory) && $currentCategory) || (isset($currentBrand) && $currentBrand))
<div class="bread-crumb pt-3">
    <div class="container-fluid">
        <div class="content-box">
            <div class="container-fluid">
                <nav aria-label="breadcrumb" class="my-lg-0 my-2">
                    <ol class="breadcrumb mb-0">
                        <li class="breadcrumb-item"><a href="{{ route('home') }}" class="font-14 text-muted">خانه</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('shop') }}" class="font-14 text-muted">فروشگاه</a></li>
                        @if(isset($currentBrand) && $currentBrand)
                            <li class="breadcrumb-item"><a href="{{ route('brands.index') }}" class="font-14 text-muted">برندها</a></li>
                            <li class="breadcrumb-item active main-color-one-color font-14" aria-current="page">{{ $currentBrand->name }}</li>
                        @else
                        @php $parentChain = []; $p = $currentCategory->parent; while($p) { array_unshift($parentChain, $p); $p = $p->parent; } @endphp
                        @foreach($parentChain as $p)
                            <li class="breadcrumb-item"><a href="{{ route('shop.category', $p->slug) }}" class="font-14 text-muted">{{ $p->name }}</a></li>
                        @endforeach
                        <li class="breadcrumb-item active main-color-one-color font-14" aria-current="page">{{ $currentCategory->name }}</li>
                        @endif
                    </ol>
                </nav>
            </div>
        </div>
    </div>
</div>
@endif

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

        <form method="GET" action="{{ $shopUrl }}" id="shopForm">

            {{-- Single set of price hidden inputs shared by both desktop/mobile sliders --}}
            <input type="hidden" id="shopPriceMin" name="price_min" value="{{ $priceMin }}">
            <input type="hidden" id="shopPriceMax" name="price_max" value="{{ $priceMax > 0 ? $priceMax : $maxPrice }}">

            {{-- Mobile filter button + offcanvas --}}
            <div class="custom-filter d-lg-none d-block">
                <button class="btn btn-filter-float border-0 main-color-two-bg shadow-box px-3 rounded-3 position-fixed"
                    style="z-index:999;bottom:80px;" type="button"
                    data-bs-toggle="offcanvas" data-bs-target="#offcanvasShopFilter"
                    aria-controls="offcanvasShopFilter">
                    <i class="bi bi-funnel font-20 fw-bold text-white"></i>
                    <span class="d-block font-14 text-white">فیلتر</span>
                </button>

                <div class="offcanvas offcanvas-start" tabindex="-1" id="offcanvasShopFilter"
                    aria-labelledby="offcanvasShopFilterLabel">
                    <div class="offcanvas-header">
                        <h5 class="offcanvas-title" id="offcanvasShopFilterLabel">فیلتر ها</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                    </div>
                    <div class="offcanvas-body">
                        @include('site.partials.shop-filters', ['prefix' => 'mobile'])
                    </div>
                </div>
            </div>
            {{-- /Mobile filter --}}

            <div class="row gy-3">

                {{-- Desktop sidebar --}}
                <div class="col-lg-3 d-lg-block d-none">
                    <div class="shop-sidebar">
                        @include('site.partials.shop-filters', ['prefix' => 'desktop'])
                    </div>
                </div>
                {{-- /Desktop sidebar --}}

                {{-- Product grid --}}
                <div class="col-lg-9">

                    {{-- Sort bar --}}
                    <div class="category-sort mb-3">
                        <div class="content-box">
                            <div class="container-fluid">
                                <div class="d-flex align-items-center flex-wrap gap-2">
                                    @if(isset($currentBrand) && $currentBrand)
                                    <div class="me-3">
                                        <h5 class="font-16 mb-0">
                                            @if($currentBrand->image)
                                                <img src="{{ asset('uploads/brands/' . $currentBrand->image) }}" alt="{{ $currentBrand->name }}" class="shop-brand-thumb me-1">
                                            @else
                                                <i class="bi bi-award main-color-one-color me-1"></i>
                                            @endif
                                            {{ $currentBrand->name }}
                                        </h5>
                                    </div>
                                    <span class="text-muted">|</span>
                                    @elseif(isset($currentCategory) && $currentCategory)
                                    <div class="me-3">
                                        <h5 class="font-16 mb-0">
                                            @if($currentCategory->icon)<i class="bi bi-{{ $currentCategory->icon }} main-color-one-color me-1"></i>@endif
                                            {{ $currentCategory->name }}
                                        </h5>
                                    </div>
                                    <span class="text-muted">|</span>
                                    @endif
                                    <div class="ms-lg-0 ms-0 me-3">
                                        <h5 class="font-16 mb-0">مرتب سازی:</h5>
                                    </div>
                                    <div class="d-flex flex-wrap gap-2">
                                        @foreach([
                                            'default'        => 'پیشفرض',
                                            'popular'        => 'محبوب‌ترین',
                                            'best_sellers'   => 'پرفروش‌ترین',
                                            'newest'         => 'جدیدترین',
                                            'cheapest'       => 'ارزان‌ترین',
                                            'most_expensive' => 'گران‌ترین',
                                        ] as $val => $label)
                                        @php
                                            $currentParams = array_merge(request()->except(['sort', 'page']), ['sort' => $val]);
                                            $sortUrl = $shopUrl . '?' . http_build_query($currentParams);
                                        @endphp
                                        <a href="{{ $sortUrl }}"
                                            class="btn btn-sm rounded-pill sort-btn {{ $sort === $val ? 'main-color-one-bg text-white border-0' : 'btn-outline-secondary' }}">
                                            {{ $label }}
                                        </a>
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    {{-- /Sort bar --}}

                    {{-- Product grid --}}
                    <div class="category-items">
                        @if($products->isEmpty())
                        <div class="shop-empty">
                            <i class="bi bi-search"></i>
                            <p class="font-18 mt-2">محصولی یافت نشد.</p>
                            <a href="{{ $shopUrl }}" class="btn-outline-site">پاک کردن فیلترها</a>
                        </div>
                        @else
                        <div class="row g-3">
                            @foreach($products as $product)
                            @php
                                $variant     = $product->defaultVariant() ?: $product->variants->first();
                                $price       = $variant ? (float)$variant->price : 0;
                                $finalPrice  = ($variant && $variant->discount_price) ? (float)$variant->discount_price : $price;
                                $hasDiscount = $variant && $variant->discount_price && $variant->discount_price < $variant->price;
                                $discPct     = ($hasDiscount && $price > 0) ? round((1 - $finalPrice / $price) * 100) : 0;
                                $img1        = $product->featured_image ? asset('uploads/products/' . $product->featured_image) : null;
                                $img2obj     = $product->images->skip(1)->first();
                                $img2Url     = $img2obj ? asset('uploads/products/' . $img2obj->image) : $img1;
                                $inStock     = $product->isInStock();
                            @endphp
                            <div class="col-12 col-md-6 col-lg-4">
                                <div class="product-box {{ $inStock ? '' : 'out-of-stock' }}">
                                    <div class="product-timer">
                                        <div class="timer-label">
                                            @if($hasDiscount && $discPct > 0)
                                            <span>{{ $discPct }}% تخفیف</span>
                                            @endif
                                        </div>
                                        <div class="product-header-btn">
                                            <a href="javascript:void(0)" class="wish-toggle"
                                                data-product="{{ $product->id }}"
                                                data-bs-toggle="tooltip" data-bs-placement="top"
                                                data-bs-title="علاقه‌مندی">
                                                <i class="bi {{ auth()->check() && auth()->user()->hasWished($product->id) ? 'bi-heart-fill' : 'bi-heart' }}"></i>
                                            </a>
                                            <a href="{{ route('product.show', $product->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', $product->slug) }}">
                                        <div class="product-image">
                                            @if($img1)
                                            <img src="{{ $img1 }}" loading="lazy" alt="{{ $product->title }}" class="img-fluid one-image">
                                            <img src="{{ $img2Url ?? $img1 }}" loading="lazy" alt="{{ $product->title }}" class="img-fluid two-image">
                                            @else
                                            <img src="{{ asset('theme/assets/image/default-product.png') }}" loading="lazy" alt="{{ $product->title }}" class="img-fluid one-image">
                                            <img src="{{ asset('theme/assets/image/default-product.png') }}" loading="lazy" alt="{{ $product->title }}" class="img-fluid two-image">
                                            @endif
                                        </div>
                                    </a>
                                    <div class="product-title">
                                        <div class="title">
                                            <p class="text-overflow-1">{{ $product->title }}</p>
                                            @if($product->title_en)
                                            <span class="text-muted text-overflow-1">{{ $product->title_en }}</span>
                                            @endif
                                        </div>
                                        <div class="rating">
                                            <div class="number">
                                                @if($product->variants->count() > 1)
                                                <span class="text-muted font-12">{{ $product->variants->count() }} تنوع</span>
                                                @endif
                                            </div>
                                            <div class="icon"><i class="bi bi-star-fill"></i></div>
                                        </div>
                                    </div>
                                    <div class="product-action">
                                        <div class="price">
                                            @if($price > 0)
                                                @if($hasDiscount)
                                                <p class="new-price">{{ number_format($finalPrice) }} تومان</p>
                                                <p class="old-price">{{ number_format($price) }} تومان</p>
                                                @else
                                                <p class="new-price">{{ number_format($price) }} تومان</p>
                                                @endif
                                            @else
                                            <p class="new-price text-muted">تماس بگیرید</p>
                                            @endif
                                        </div>
                                        <div class="link">
                                            @if($inStock)
                                            <a href="{{ route('product.show', $product->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>

                        {{-- Pagination --}}
                        @if($products->hasPages())
                        <div class="my-paginate my-4">
                            <nav>
                                <ul class="pagination flex-wrap justify-content-center">
                                    {{-- Previous --}}
                                    @if($products->onFirstPage())
                                    <li class="page-item disabled"><span class="page-link rounded-3">قبلی</span></li>
                                    @else
                                    <li class="page-item"><a class="page-link rounded-3" href="{{ $products->previousPageUrl() }}">قبلی</a></li>
                                    @endif

                                    {{-- Pages --}}
                                    @foreach($products->getUrlRange(1, $products->lastPage()) as $page => $url)
                                    <li class="page-item {{ $products->currentPage() === $page ? 'active' : '' }}">
                                        <a class="page-link rounded-3" href="{{ $url }}">{{ $page }}</a>
                                    </li>
                                    @endforeach

                                    {{-- Next --}}
                                    @if($products->hasMorePages())
                                    <li class="page-item"><a class="page-link rounded-3" href="{{ $products->nextPageUrl() }}">بعدی</a></li>
                                    @else
                                    <li class="page-item disabled"><span class="page-link rounded-3">بعدی</span></li>
                                    @endif
                                </ul>
                            </nav>
                        </div>
                        @endif
                        @endif
                    </div>
                    {{-- /Product grid --}}

                </div>
                {{-- /Product grid col --}}

            </div>{{-- /row --}}

        </form>

    </div>
</div>
@endsection

@section('scripts')
<script src="{{ asset('theme/assets/plugin/nouislider/nouislider.min.js') }}"></script>
<script>
(function () {
    // Category checkbox auto-navigate.
    var shopBase = @json(route('shop'));
    function preserveParams(form) {
        var params = new URLSearchParams();
        var q = form.querySelector('[name="q"]');
        if (q && q.value) params.set('q', q.value);
        var pmin = form.querySelector('[name="price_min"]');
        if (pmin && parseInt(pmin.value, 10) > 0) params.set('price_min', pmin.value);
        var pmax = form.querySelector('[name="price_max"]');
        if (pmax && parseInt(pmax.value, 10) > 0) params.set('price_max', pmax.value);
        return params;
    }
    document.querySelectorAll('.shop-cat-checkbox').forEach(function (cb) {
        cb.addEventListener('change', function () {
            var form    = cb.closest('form');
            var checked = Array.from(form.querySelectorAll('.shop-cat-checkbox:checked'));
            var params  = preserveParams(form);
            var qs, url;
            if (checked.length === 0) {
                qs = params.toString();
                url = shopBase + (qs ? '?' + qs : '');
            } else if (checked.length === 1) {
                qs = params.toString();
                url = checked[0].dataset.url + (qs ? '?' + qs : '');
            } else {
                checked.forEach(function (c) { params.append('categories[]', c.value); });
                url = shopBase + '?' + params.toString();
            }
            window.location.href = url;
        });
    });

    // Shared price hidden inputs
    var priceMinInput = document.getElementById('shopPriceMin');
    var priceMaxInput = document.getElementById('shopPriceMax');

    // Initialize all price sliders (desktop + mobile), both update the same hidden inputs
    document.querySelectorAll('.shop-price-slider').forEach(function (slider) {
        var filterPrice = slider.closest('.filter-price');
        var minDisplay  = filterPrice.querySelector('.min-price-filter');
        var maxDisplay  = filterPrice.querySelector('.max-price-filter');

        var maxVal  = parseInt(slider.dataset.max, 10)     || 50000000;
        var initMin = parseInt(slider.dataset.initMin, 10) || 0;
        var initMax = parseInt(slider.dataset.initMax, 10) || maxVal;

        noUiSlider.create(slider, {
            start: [initMin, initMax],
            connect: true,
            range: { min: 0, max: maxVal },
            step: 100000,
            format: {
                to:   function (v) { return Math.round(v); },
                from: function (v) { return Number(v); }
            }
        });

        slider.noUiSlider.on('update', function (values, handle) {
            var val = values[handle];
            var formatted = new Intl.NumberFormat('fa-IR').format(val);
            if (handle === 0) {
                if (minDisplay) minDisplay.value = formatted;
                if (priceMinInput) priceMinInput.value = val;
            } else {
                if (maxDisplay) maxDisplay.value = formatted;
                if (priceMaxInput) priceMaxInput.value = val;
            }
        });
    });
})();
</script>
@endsection
