@php
    $t = $catalogTheme ?? [];
    $imtHeroConsoleDebug = (bool) config('product_catalog_themes.debug_log_listing_theme', false);
    $decorRaw = isset($t['decor_asset']) && is_string($t['decor_asset']) ? trim($t['decor_asset']) : '';
    $photoRaw = isset($t['hero_photo']) && is_string($t['hero_photo']) ? trim($t['hero_photo']) : '';
    // Absolute URL: use as-is. Relative: prefer preset PNG; if missing on disk use hero-photo-main.png; last resort asset() of preset.
    $decor = $decorRaw !== '' ? asset($decorRaw) : '';

    $heroPhotoSourceRel = null;
    if ($photoRaw !== '' && preg_match('#^https?://#i', $photoRaw)) {
        $heroPhoto = $photoRaw;
        $heroPhotoSourceRel = 'external_absolute';
    } elseif ($photoRaw !== '') {
        $localExtras = [];
        if (! preg_match('#^https?://#i', $photoRaw) && ! preg_match('#hero-photo-main\.png(\?.*)?$#', $photoRaw)) {
            $localExtras[] = 'assets/imt/catalog/heroes/photo/hero-photo-main.png';
        }
        $candidates = array_values(array_unique(array_merge([$photoRaw], $localExtras)));
        $heroPhoto = '';
        foreach ($candidates as $rel) {
            if ($rel !== '' && is_file(public_path($rel))) {
                $heroPhoto = asset($rel);
                $heroPhotoSourceRel = $rel;
                break;
            }
        }
        if ($heroPhoto === '') {
            $heroPhoto = asset($photoRaw);
            $heroPhotoSourceRel = 'asset_fallback_file_missing';
        }
    } else {
        $heroPhoto = '';
    }

    $__coverStyle = '';
    if (! empty($heroPhoto)) {
        $__coverStyle =
            sprintf(
                'background-image:url(%s);background-size:cover;background-position:center center;',
                json_encode($heroPhoto, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
            );
    }

    $title = $t['hero_title'] ?? '';
    $subtitle = $t['hero_subtitle'] ?? '';
    $isRtl = app()->getLocale() === 'ar';
    $counterPrefix = '+';

    $showCatalogHeroSearchBar = filter_var(($showCatalogHeroSearchBar ?? true), FILTER_VALIDATE_BOOLEAN);

    $imtHeroDiag = [
        'preset' => $t['base_preset_key'] ?? null,
        'route' => $imtHeroConsoleDebug ? request()->path() : null,
        'photo_config' => $photoRaw !== '' ? $photoRaw : null,
        'resolved_url' => $heroPhoto !== '' ? $heroPhoto : null,
        'resolved_from' => $heroPhotoSourceRel,
        'config_path_exists' => ($photoRaw !== '' && ! preg_match('#^https?://#i', $photoRaw)) ? is_file(public_path($photoRaw)) : null,
        'decor_config' => $decorRaw !== '' ? $decorRaw : null,
        'decor_url' => $decor !== '' ? $decor : null,
    ];
@endphp

<section class="imt-catalog-hero imt-catalog-hero--pastel {{ trim($t['hero_class'] ?? '') }} mx-auto mb-0"
         @if ($imtHeroConsoleDebug) data-imt-hero-debug="1" @endif>
    {{-- Background: full-cover image / fallback décor + readability scrim --}}
    <div class="imt-catalog-hero__media{{ ! empty($heroPhoto) ? ' imt-catalog-hero__media--has-photo' : '' }}"
         @if (! empty($heroPhoto)) style="{{ htmlspecialchars($__coverStyle, ENT_QUOTES, 'UTF-8') }}" @endif
         aria-hidden="true">
        @if(! empty($decor))
            <div class="imt-catalog-hero__bg-fallback imt-catalog-hero__bg-fallback--layer"
                 style="background-image:url('{{ $decor }}')"></div>
        @endif
        @if(! empty($heroPhoto))
            {{-- Matches background sizing; shows SVG layer behind if PNG is missing locally or fails to decode --}}
            {!! premium_picture_tag([
                'src' => $heroPhoto,
                'alt' => '',
                'class' => 'imt-catalog-hero__bg-img',
                'loading' => 'eager',
                'fetchpriority' => 'high',
                'responsive' => true,
                'sizes' => '100vw',
            ]) !!}
        @endif
        <div class="imt-catalog-hero__scrim"></div>
    </div>

    @if(!empty($t['stats']))
        <div class="container imt-catalog-hero__stats-under-media d-lg-none position-relative px-3">
            @include('web.default.products.includes.catalog_hero_stats_slot', [
                'statsRows' => $t['stats'],
                'counterPrefix' => $counterPrefix,
            ])
        </div>
    @endif

    <div class="container position-relative imt-catalog-hero__content">
        <div class="imt-catalog-hero__stack mx-auto">
            <div class="imt-catalog-hero__copy text-center w-100">
                <span class="imt-catalog-badge imt-catalog-badge--hero-kicker mx-auto">{{ $productsCount ?? 0 }} {{ trans('update.products') }}</span>

                @if(($title ?? '') !== '')
                    <h1 class="imt-catalog-h1 imt-catalog-h1--hero mx-auto">{{ $title }}</h1>
                @endif

                @if(($subtitle ?? '') !== '')
                    <p class="imt-catalog-sub imt-catalog-sub--hero mx-auto">{{ $subtitle }}</p>
                @endif
            </div>

            @if ($showCatalogHeroSearchBar)
            <div class="imt-catalog-hero__search-row w-100 d-flex justify-content-center">
                <div class="imt-catalog-hero__searchpill imt-catalog-hero__searchpill--compact {{ $isRtl ? 'imt-catalog-hero__searchpill--rtl' : '' }} align-items-center">
                    <button type="submit"
                            form="imt-catalog-filters-form"
                            class="btn imt-catalog-hero__searchbtn d-flex align-items-center justify-content-center flex-shrink-0"
                            aria-label="{{ trans('home.find') }}">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" aria-hidden="true">
                            <circle cx="11" cy="11" r="7"/>
                            <path d="m20 20-3.2-3.2"/>
                        </svg>
                    </button>
                    <input type="text"
                           name="q"
                           form="imt-catalog-filters-form"
                           value="{{ request()->get('q', request()->get('search')) }}"
                           class="form-control imt-catalog-hero__search-input border-0 bg-transparent shadow-none"
                           placeholder="{{ trans('catalog.hero_search_placeholder') }}"
                           @if($isRtl) dir="rtl"@endif/>
                </div>
            </div>
            @endif

            @include('web.default.products.includes.catalog_hero_stats_slot', [
                'statsRows' => $t['stats'] ?? [],
                'counterPrefix' => $counterPrefix,
                'slotExtraClass' => 'd-none d-lg-block',
            ])
        </div>
    </div>
</section>
@if ($imtHeroConsoleDebug)
    <script>
        (function () {
            var ctx = @json($imtHeroDiag);
            var group = '[IMT catalog hero]';
            console.groupCollapsed(group);
            console.info('Diagnostics (IMT_LOG_CATALOG_HERO)', ctx);
            console.info(group, 'Note: Edge "Tracking Prevention blocked access to storage" is usually fonts/analytics/third-party cookies — not your hero PNG unless <img src> is another domain.');
            if (!ctx.resolved_url) {
                console.warn('No hero image URL: empty hero_photo in theme or failed resolution.');
            } elseif (ctx.config_path_exists === false) {
                console.warn('hero_photo path from config is not a file on disk at public_path:', ctx.photo_config);
            }
            console.groupEnd();

            var section = document.querySelector('section.imt-catalog-hero[data-imt-hero-debug="1"]');
            if (!section) {
                return;
            }
            var img = section.querySelector('img.imt-catalog-hero__bg-img[data-imt-hero-img="1"]');
            var media = section.querySelector('.imt-catalog-hero__media');

            function logVisibleSize(el, label) {
                if (!el || !el.getBoundingClientRect) {
                    return;
                }
                var r = el.getBoundingClientRect();
                console.info(group, label + ' layout box (px)', Math.round(r.width) + '×' + Math.round(r.height));
            }

            if (!img) {
                if (ctx.resolved_url) {
                    console.warn(group, 'Expected <img> missing but resolved_url was set (markup mismatch?).');
                }
                return;
            }

            var src = img.currentSrc || img.src;
            console.info(group, '<img> src', src);
            try {
                var heroUrlObj = new URL(src, window.location.href);
                if (heroUrlObj.origin === window.location.origin) {
                    fetch(heroUrlObj.href, { method: 'HEAD', cache: 'no-store' }).then(function (res) {
                        var ct = res.headers.get('content-type') || '';
                        console.info(group, 'HEAD same-origin:', res.status, ct);
                        if (res.status === 404) {
                            console.error(group, 'File missing on server (404). Upload PNG to public/', ctx.photo_config || '');
                        } else if (res.ok && ct.indexOf('image/') !== 0 && ct.indexOf('application/octet-stream') !== 0) {
                            console.error(group, 'URL does not return an image MIME type — wrong path or rewritten to HTML?', ct);
                        }
                    }).catch(function (err) {
                        console.warn(group, 'HEAD request failed:', err.message);
                    });
                } else if (heroUrlObj.hostname.indexOf('google') !== -1 || heroUrlObj.hostname.indexOf('unsplash') !== -1) {
                    console.warn(group, 'Remote hero host — Tracking Prevention / hotlink rules can block embedding. Prefer files under', window.location.origin + '/assets/...');
                }
            } catch (e) {}

            img.addEventListener('load', function () {
                if (img.naturalWidth > 0) {
                    console.info(group, 'Image loaded OK', img.naturalWidth + '×' + img.naturalHeight);
                } else {
                    console.error(group, 'Image "loaded" but naturalWidth is 0 (broken or empty body / blocked decode).', src);
                }
                logVisibleSize(img, 'Hero <img>');
                logVisibleSize(media, 'Hero media');
            });

            img.addEventListener('error', function () {
                console.error(group, '<img> error — open Network tab, filter Img, inspect status. Same-origin PNG: usually 404 or wrong MIME. Third-party URLs: CSP or browser blocking.', src);
                logVisibleSize(img, 'Hero <img>');
                logVisibleSize(media, 'Hero media');
            });

            if (img.complete) {
                if (img.naturalWidth === 0) {
                    console.error(group, 'Image already complete but naturalWidth=0 (decode fail or bad URL).', src);
                } else {
                    console.info(group, 'Image from cache / already complete', img.naturalWidth + '×' + img.naturalHeight);
                }
            }
        })();
    </script>
@endif
