{{-- Products section component
     Usage: @include('florial::sections.products', ['sectionKey' => 'homepage_products_1'])
--}}
@php
    $ts = themeService()->boot();
    $section = $ts->section($sectionKey ?? '');
    if (!$section) return;

    $settings = $ts->settings($sectionKey);
    $sectionTitle = $ts->trans($sectionKey, 'section_title');
    $sectionSubtitle = $ts->trans($sectionKey, 'section_subtitle');

    $source = $settings['source'] ?? 'latest';
    $categoryId = $settings['category_id'] ?? null;
    $itemsCount = $settings['items_count'] ?? 6;
    $columns = $settings['columns'] ?? 6;

    // Fetch products based on source (including subcategories)
    $productsQuery = \ViartasShop\Products\Models\Accounting\Product::where('is_visible', true);

    switch ($source) {
        case 'category':
            if ($categoryId) {
                $categoryIds = \ViartasShop\ProductCategories\Models\Accounting\ProductCategory::find($categoryId)
                    ?->descendantsAndSelf()
                    ->pluck('id')
                    ->toArray() ?? [$categoryId];
                $productsQuery->whereIn('product_category_id', $categoryIds);
            }
            break;
        case 'featured':
            $productsQuery->orderByDesc('updated_at');
            break;
        case 'bestselling':
            $productsQuery->orderByDesc('updated_at');
            break;
        case 'latest':
        default:
            $productsQuery->orderByDesc('created_at');
            break;
    }

    $products = $productsQuery->with(['category', 'variants.attributeValues.attr', 'media'])->limit($itemsCount)->get();

    // Batch: variantų SKU likučiai
    $allVariantSkus = $products->flatMap(fn($p) => $p->variants->pluck('sku'))->filter()->unique()->toArray();
    $inStockSkus = $allVariantSkus
        ? \ViartasShop\Warehouses\Models\WarehouseStock::whereIn('sku', $allVariantSkus)
            ->where('quantity', '>', 0)
            ->pluck('sku')
            ->toArray()
        : [];

    // Batch: prekių be variantų likučiai (per product_id)
    $noVariantProductIds = $products->filter(fn($p) => $p->variants->isEmpty())->pluck('id')->toArray();
    $inStockProductIds = $noVariantProductIds
        ? \ViartasShop\Warehouses\Models\WarehouseStock::whereIn('product_id', $noVariantProductIds)
            ->where('quantity', '>', 0)
            ->pluck('product_id')
            ->toArray()
        : [];

    $colClass = match($columns) {
        3 => 'col-xxl-4 col-xl-4 col-lg-4 col-md-4 col-6',
        4 => 'col-xxl-3 col-xl-3 col-lg-4 col-md-4 col-6',
        default => 'col-xxl-2 col-xl-3 col-lg-4 col-md-4 col-6',
    };
@endphp

@if($products->isNotEmpty())
    <div class="row g-sm-4 g-3 mt-2 mb-4 product-list-section">
        @foreach($products as $product)
            <div class="{{ $colClass }}">
                <div class="product-box-3 h-100 wow fadeInUp">
                    <div class="product-header">
                        <div class="product-image">
                            <a href="{{ $product->getRoute() ?? '#' }}">
                                @if($product->mainImageUrl('card-3x4'))
                                    <img src="{{ $product->mainImageUrl('card-3x4') }}"
                                         class="img-fluid blur-up lazyload" alt="{{ $product->title }}">
                                @else
                                    <img src="{{ theme()->publicPath('images/placeholder.png') }}"
                                         class="img-fluid blur-up lazyload" alt="{{ $product->title }}">
                                @endif
                            </a>
                        </div>
                    </div>

                    <div class="product-footer">
                        <div class="product-detail">
                            @if($product->category)
                                <span class="span-name">{{ $product->category->title }}</span>
                            @endif
                            <a href="{{ $product->getRoute() ?? '#' }}">
                                <h5 class="name">{{ $product->title }}</h5>
                            </a>

                            @if($product->variants->isNotEmpty())
                                @php
                                    $lengthAttribute = $product->variants->first()
                                        ?->attributeValues?->first()?->attr;
                                @endphp
                                @if($lengthAttribute)
                                    <div class="stem-sizes-label mt-3">
                                        <i class="fa-solid fa-ruler-vertical me-1"></i>
                                        {{ $lengthAttribute->getLocalizedTitle() ?? '' }}
                                    </div>
                                @endif
                                <div class="stem-grid mt-2">
                                    @foreach($product->variants as $variant)
                                        @php $inStock = in_array($variant->sku, $inStockSkus); @endphp
                                        @if(!$inStock) @continue @endif
                                        <div class="stem-option"
                                             onclick="selectStem(this)"
                                             data-price="{{ $variant->price->formatAsPrice() }}">
                                            <div class="stem-option__height">{{ $variant->name }}</div>
                                            <div class="stem-option__price">{{ $variant->price->formatAsPrice() }}</div>
                                        </div>
                                    @endforeach
                                </div>
                            @else
                                @php $productInStock = in_array($product->id, $inStockProductIds); @endphp
                                <h5 class="price mt-3">
                                    <span class="theme-color">{{ $product->price->formatAsPrice() }}</span>
                                </h5>
                                @unless($productInStock)
                                    <span class="text-danger small">{{ __('globals.out_stock') }}</span>
                                @endunless
                            @endif

                            <div class="add-to-cart-box mt-3">
                                <button class="btn btn-add-cart addcart-button">
                                    <i class="fa-solid fa-basket-shopping"></i>
                                    {{ __('globals.add_to_cart') }}
                                </button>
                            </div>

                            <div class="stem-note text-center mt-2">
                                {{ __('globals.stem_note') }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        @endforeach
    </div>
@endif
