@extends('layouts.nova')

@php
    use App\Banner;
    $useUnifiedSeo = true;
@endphp

@php
    $seoPage = max(1, (int) request()->query('page', 1));
    $seoBase = url()->current();
    $seoQ    = request()->query(); unset($seoQ['page']);
    $seoUrl  = fn(int $p) => $seoBase . ($p > 1
        ? '?' . http_build_query(array_merge($seoQ, ['page' => $p]))
        : (count($seoQ) ? '?' . http_build_query($seoQ) : ''));
    $seoPrev = $seoPage > 1 ? $seoUrl($seoPage - 1) : null;
    $seoNext = (isset($artworks) && method_exists($artworks, 'nextPageUrl'))
                 ? $artworks->nextPageUrl() : null;
@endphp

@php
    $page_canonical = $page_canonical ?? $seoUrl($seoPage);
    $page_rel_prev = $page_rel_prev ?? $seoPrev;
    $page_rel_next = $page_rel_next ?? $seoNext;
    $page_robots = $page_robots ?? 'index,follow';
@endphp

@php
    // ── Rank API endpoint ────────────────────────────────────────────────────
    // Map the active sort alias to the ranking API ?type= parameter.
    // Only trending / fresh / top-rated have pre-computed ranking lists.
    $rankTypeMap = [
        'trending'  => 'trending',
        'fresh'     => 'new_hot',
        'top-rated' => 'best',
    ];
    $rankApiType     = $rankTypeMap[$current_sort ?? 'trending'] ?? null;
    $rankApiEndpoint = null;
    if ($rankApiType) {
        if (isset($category) && $category && $category->id ?? null) {
            $rankApiEndpoint = '/api/rank/category/' . $category->id;
        } elseif (isset($contentType) && $contentType && $contentType->slug ?? null) {
            $rankApiEndpoint = '/api/rank/type/' . $contentType->slug;
        } else {
            $rankApiEndpoint = '/api/rank/global';
        }
    }

    $tagContext = ($gallery_type ?? null) === 'tag' ? ($tag_context ?? null) : null;
@endphp

@section('content')
<div class="container-fluid legacy-page">
    @php Banner::ShowResponsiveAd(); @endphp

    @php
        $browseSection = $gallery_nav_section
            ?? (isset($contentType) && $contentType ? strtolower((string) $contentType->slug) : (($gallery_type ?? null) === 'tag' ? 'tags' : 'artworks'));
        $browseIconMap = [
            'artworks' => 'fa-border-all',
            'photography' => 'fa-camera',
            'wallpapers' => 'fa-desktop',
            'skins' => 'fa-layer-group',
            'digital-art' => 'fa-palette',
            'other' => 'fa-folder-open',
            'tags' => 'fa-tags',
        ];
        $browseIcon = $browseIconMap[$browseSection] ?? 'fa-border-all';
    @endphp

    <div class="pt-0">
        <div class="mx-auto w-full">
            <div class="relative min-h-[calc(120vh-64px)] md:min-h-[calc(100vh-64px)]">

                <main class="w-full">

                    {{-- ── Hero header (discover-style) ── --}}
                    @php
                        $headerBreadcrumbs = collect();

                        if (($gallery_type ?? null) === 'browse') {
                            $headerBreadcrumbs = $breadcrumbs ?? collect();
                        } elseif (isset($breadcrumbs) && $breadcrumbs->isNotEmpty()) {
                            $headerBreadcrumbs = $breadcrumbs;
                        } elseif (isset($contentType) && $contentType) {
                            $headerBreadcrumbs = collect([
                                (object) ['name' => 'Explore', 'url' => '/browse'],
                                (object) ['name' => $contentType->name, 'url' => '/' . strtolower($contentType->slug)],
                            ]);
                        }
                    @endphp

                    <x-nova-page-header
                        section="{{ ($gallery_type ?? null) === 'tag' ? 'Tags' : 'Browse' }}"
                        :title="$hero_title ?? 'Browse Artworks'"
                        :icon="$browseIcon"
                        :breadcrumbs="$headerBreadcrumbs"
                        :description="$hero_description ?? null"
                        actionsClass="lg:pt-8"
                    >
                        <x-slot name="actions">
                            @include('gallery._browse_nav', ['section' => $browseSection, 'includeTags' => ($gallery_type ?? null) === 'tag'])
                        </x-slot>
                    </x-nova-page-header>

                    @if($tagContext)
                    <section class="px-6 pt-8 md:px-10">
                        @php
                            $topCompanionTag = collect($tagContext['related_tags'] ?? [])->first();
                        @endphp
                        <div class="overflow-hidden rounded-[1.75rem] border border-white/[0.08] bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_34%),linear-gradient(135deg,rgba(11,17,27,0.96),rgba(10,16,24,0.88))] shadow-[0_20px_70px_rgba(3,7,18,0.24)]">
                            <div class="grid gap-6 p-6 md:p-7 xl:grid-cols-[minmax(0,1.35fr)_minmax(300px,0.85fr)] xl:items-start">
                                <div class="space-y-6">
                                    <div class="flex flex-wrap items-center gap-3 text-sm text-white/56">
                                        <span class="inline-flex items-center gap-2 rounded-full border border-sky-400/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200">
                                            <span class="h-2 w-2 rounded-full bg-sky-300"></span>
                                            Tag feed
                                        </span>
                                        <span class="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-xs font-medium text-white/60">
                                            Sorted by {{ $tagContext['current_sort_label'] ?? 'Most viewed' }}
                                        </span>
                                    </div>

                                    <div class="space-y-3">
                                        <h2 class="text-2xl font-semibold tracking-tight text-white md:text-3xl">
                                            #{{ $tagContext['slug'] ?? $tagContext['name'] }}
                                        </h2>
                                        <p class="max-w-3xl text-sm leading-6 text-white/62 md:text-base">
                                            A focused feed for artwork tied to this theme. Use the ranking tabs to switch between momentum, recency, and quality without leaving the tag context.
                                        </p>
                                        @if($topCompanionTag && isset($topCompanionTag->shared_artworks_count))
                                            <a href="{{ route('tags.show', $topCompanionTag->slug) }}" data-tag-analytics-link data-tag-analytics-surface="top_companion" data-tag-analytics-tag="{{ $topCompanionTag->slug }}" data-tag-analytics-source-tag="{{ $tagContext['slug'] ?? '' }}" data-tag-analytics-position="1" class="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-3.5 py-2 text-sm text-white/68 transition hover:border-sky-400/28 hover:bg-sky-400/[0.08] hover:text-white">
                                                <span class="text-sky-200">Top companion</span>
                                                <span class="font-medium text-white">#{{ $topCompanionTag->name }}</span>
                                                <span class="text-white/34">{{ number_format($topCompanionTag->shared_artworks_count) }} shared artworks</span>
                                                @if(isset($topCompanionTag->transition_clicks) && (int) $topCompanionTag->transition_clicks > 0)
                                                    <span class="text-emerald-200">{{ number_format((int) $topCompanionTag->transition_clicks) }} recent clicks</span>
                                                @endif
                                            </a>
                                        @endif
                                    </div>

                                    @if(collect($tagContext['related_tags'] ?? [])->isNotEmpty())
                                        <div>
                                            <p class="text-xs font-semibold uppercase tracking-[0.24em] text-white/38">Related tags</p>
                                            <div class="mt-3 flex flex-wrap gap-2.5">
                                                @foreach($tagContext['related_tags'] as $relatedIndex => $relatedTag)
                                                    <a href="{{ route('tags.show', $relatedTag->slug) }}" data-tag-analytics-link data-tag-analytics-surface="related_chip" data-tag-analytics-tag="{{ $relatedTag->slug }}" data-tag-analytics-source-tag="{{ $tagContext['slug'] ?? '' }}" data-tag-analytics-position="{{ $relatedIndex + 1 }}" class="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.06] px-3.5 py-2 text-sm text-white/72 transition hover:border-sky-400/28 hover:bg-sky-400/[0.08] hover:text-white">
                                                        <span>#{{ $relatedTag->name }}</span>
                                                        <span class="text-xs text-white/36">
                                                            {{ number_format($relatedTag->shared_artworks_count ?? $relatedTag->usage_count) }}
                                                            {{ isset($relatedTag->shared_artworks_count) ? 'shared' : 'uses' }}
                                                        </span>
                                                        @if(isset($relatedTag->transition_clicks) && (int) $relatedTag->transition_clicks > 0)
                                                            <span class="text-xs text-emerald-200">{{ number_format((int) $relatedTag->transition_clicks) }} recent</span>
                                                        @endif
                                                    </a>
                                                @endforeach
                                            </div>

                                            <div class="mt-4 grid gap-3 md:grid-cols-3">
                                                @foreach(collect($tagContext['related_tags'])->take(3)->values() as $clusterIndex => $clusterTag)
                                                    <a href="{{ route('tags.show', $clusterTag->slug) }}" data-tag-analytics-link data-tag-analytics-surface="related_cluster" data-tag-analytics-tag="{{ $clusterTag->slug }}" data-tag-analytics-source-tag="{{ $tagContext['slug'] ?? '' }}" data-tag-analytics-position="{{ $clusterIndex + 1 }}" class="rounded-2xl border border-white/10 bg-white/[0.04] p-4 transition hover:border-sky-400/28 hover:bg-sky-400/[0.08]">
                                                        <p class="text-[11px] font-semibold uppercase tracking-[0.2em] text-white/34">Related cluster</p>
                                                        <h3 class="mt-2 text-base font-semibold text-white">#{{ $clusterTag->name }}</h3>
                                                        <p class="mt-2 text-sm text-white/52">
                                                            {{ number_format($clusterTag->shared_artworks_count ?? 0) }} shared artworks with this tag feed.
                                                        </p>
                                                        @if(isset($clusterTag->transition_clicks) && (int) $clusterTag->transition_clicks > 0)
                                                            <p class="mt-2 text-xs font-medium uppercase tracking-[0.18em] text-emerald-200">{{ number_format((int) $clusterTag->transition_clicks) }} recent clicks</p>
                                                        @endif
                                                    </a>
                                                @endforeach
                                            </div>
                                        </div>
                                    @endif
                                </div>

                                <aside class="grid gap-3 sm:grid-cols-3 xl:grid-cols-1">
                                    <div class="rounded-2xl border border-white/10 bg-white/[0.05] p-4 backdrop-blur-sm">
                                        <p class="text-[11px] font-semibold uppercase tracking-[0.22em] text-white/40">Artworks</p>
                                        <p class="mt-3 text-3xl font-semibold text-white">{{ number_format((int) ($tagContext['artworks_total'] ?? 0)) }}</p>
                                        <p class="mt-2 text-sm text-white/45">Public approved artworks currently in this feed.</p>
                                    </div>
                                    <div class="rounded-2xl border border-white/10 bg-white/[0.05] p-4 backdrop-blur-sm">
                                        <p class="text-[11px] font-semibold uppercase tracking-[0.22em] text-white/40">Total uses</p>
                                        <p class="mt-3 text-3xl font-semibold text-white">{{ number_format((int) ($tagContext['usage_count'] ?? 0)) }}</p>
                                        <p class="mt-2 text-sm text-white/45">How often this tag is attached across the catalog.</p>
                                    </div>
                                    <div class="rounded-2xl border border-white/10 bg-white/[0.05] p-4 backdrop-blur-sm">
                                        <p class="text-[11px] font-semibold uppercase tracking-[0.22em] text-white/40">Feed tools</p>
                                        <div class="mt-3 flex flex-wrap gap-2">
                                            <a href="{{ route('tags.index') }}" class="inline-flex items-center gap-2 rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-sm font-medium text-white/72 transition hover:bg-white/[0.08] hover:text-white">
                                                All tags
                                            </a>
                                            <a href="{{ $tagContext['rss_url'] ?? '#' }}" class="inline-flex items-center gap-2 rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-sm font-medium text-white/72 transition hover:bg-white/[0.08] hover:text-white">
                                                RSS
                                            </a>
                                        </div>
                                        <p class="mt-3 text-sm text-white/45">Jump back to discovery or subscribe to this tag feed.</p>
                                    </div>
                                </aside>
                            </div>
                        </div>
                    </section>
                    @endif

                    {{-- ═══════════════════════════════════════════════════════════════ --}}
                    {{-- RANKING TABS                                                   --}}
                    {{-- ═══════════════════════════════════════════════════════════════ --}}
                    @php
                        $rankingTabs = [
                            ['value' => 'trending',  'label' => 'Trending',  'icon' => '🔥'],
                            ['value' => 'fresh',     'label' => 'New & Hot', 'icon' => '🚀'],
                            ['value' => 'top-rated', 'label' => 'Best',      'icon' => '⭐'],
                            ['value' => 'latest',    'label' => 'Latest',    'icon' => '🕐'],
                        ];
                        $activeTab = $current_sort ?? 'trending';
                    @endphp

                    <div class="sticky top-0 z-30 border-b border-white/10 bg-nova-900/90 backdrop-blur-md" id="gallery-ranking-tabs">
                        <div class="px-6 md:px-10">
                            <div class="flex items-center justify-between gap-4">

                                {{-- Tab list --}}
                                <nav class="flex items-center gap-0 -mb-px nb-scrollbar-none overflow-x-auto" role="tablist" aria-label="Gallery ranking">
                                    @foreach($rankingTabs as $tab)
                                        @php $isActive = $activeTab === $tab['value']; @endphp
                                        <button
                                            role="tab"
                                            aria-selected="{{ $isActive ? 'true' : 'false' }}"
                                            data-rank-tab="{{ $tab['value'] }}"
                                            class="gallery-rank-tab relative flex items-center gap-1.5 whitespace-nowrap px-5 py-4 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60 {{ $isActive ? 'text-white' : 'text-neutral-400 hover:text-white' }}"
                                        >
                                            <span aria-hidden="true">{{ $tab['icon'] }}</span>
                                            {{ $tab['label'] }}
                                            {{-- Active underline indicator --}}
                                            <span class="nb-tab-indicator absolute bottom-0 left-0 right-0 h-0.5 {{ $isActive ? 'bg-accent scale-x-100' : 'bg-transparent scale-x-0' }} transition-transform duration-300 origin-left rounded-full"></span>
                                        </button>
                                    @endforeach
                                </nav>

                                {{-- Filters button — wired to slide-over panel (Phase 3) --}}
                                <button
                                    id="gallery-filter-panel-toggle"
                                    type="button"
                                    class="hidden md:flex items-center gap-2 shrink-0 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-white/80 hover:bg-white/10 hover:text-white transition-colors"
                                    aria-haspopup="dialog"
                                    aria-expanded="false"
                                    aria-controls="gallery-filter-panel"
                                >
                                    <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2a1 1 0 01-.293.707L13 13.414V19a1 1 0 01-.553.894l-4 2A1 1 0 017 21v-7.586L3.293 6.707A1 1 0 013 6V4z" />
                                    </svg>
                                    Filters
                                </button>

                            </div>
                        </div>
                    </div>

                    {{-- ═══════════════════════════════════════════════════════════════ --}}
                    {{-- HORIZONTAL CATEGORY FILTER ROW                                --}}
                    {{-- ═══════════════════════════════════════════════════════════════ --}}
                    @php
                        $filterItems    = $subcategories ?? collect();
                        $activeFilterId = isset($category) ? ($category->id ?? null) : null;
                        $categoryAllHref = isset($subcategory_parent) && $subcategory_parent && ($subcategory_parent->url ?? null)
                            ? url($subcategory_parent->url)
                            : (isset($contentType) && $contentType
                                ? url('/' . $contentType->slug)
                                : url('/browse'));
                        $activeSortSlug = $activeTab !== 'trending' ? $activeTab : null;
                    @endphp

                    @if($filterItems->isNotEmpty())
                    <div class="sticky top-[57px] z-20 bg-nova-900/80 backdrop-blur-md border-b border-white/[0.06]">
                        @php
                            $allHref = $categoryAllHref . ($activeSortSlug ? '?sort=' . $activeSortSlug : '');
                            $carouselItems = [[
                                'label' => 'All',
                                'href' => $allHref,
                                'active' => !$activeFilterId,
                            ]];

                            foreach ($filterItems as $sub) {
                                $subName = $sub->name ?? $sub->category_name ?? null;
                                $subUrl  = $sub->url ?? null;

                                if (! $subUrl && isset($sub->slug) && isset($contentType) && $contentType) {
                                    $subUrl = url('/' . $contentType->slug . '/' . $sub->slug);
                                }

                                if (! $subName || ! $subUrl) {
                                    continue;
                                }

                                $sep = str_contains($subUrl, '?') ? '&' : '?';
                                $subLinkHref = $activeSortSlug ? ($subUrl . $sep . 'sort=' . $activeSortSlug) : $subUrl;
                                $isActiveSub = $activeFilterId && isset($sub->id) && (int) $sub->id === (int) $activeFilterId;

                                $carouselItems[] = [
                                    'label' => $subName,
                                    'href' => $subLinkHref,
                                    'active' => $isActiveSub,
                                ];
                            }
                        @endphp

                        <div
                            data-react-pill-carousel
                            data-aria-label="Filter by category"
                            data-items='@json($carouselItems)'
                        ></div>
                    </div>
                    @endif

                    @php
                        $galleryItems = (is_object($artworks) && method_exists($artworks, 'getCollection'))
                            ? $artworks->getCollection()
                            : collect($artworks);

                        $galleryArtworks = $galleryItems->map(fn ($art) => [
                            'id'            => $art->id            ?? null,
                            'name'          => $art->name          ?? null,
                            'thumb'         => $art->thumb_url     ?? $art->thumb ?? null,
                            'thumb_srcset'  => $art->thumb_srcset  ?? null,
                            'uname'         => $art->uname         ?? '',
                            'username'      => $art->username      ?? '',
                            'avatar_url'    => $art->avatar_url    ?? null,
                            'profile_url'   => $art->profile_url   ?? null,
                            'published_as_type' => $art->published_as_type ?? null,
                            'publisher'     => $art->publisher     ?? null,
                            'category_name' => $art->category_name ?? '',
                            'category_slug' => $art->category_slug ?? '',
                            'slug'          => $art->slug          ?? '',
                            'width'         => $art->width         ?? null,
                            'height'        => $art->height        ?? null,
                        ])->values();

                        $galleryNextPageUrl = (is_object($artworks) && method_exists($artworks, 'nextPageUrl'))
                            ? $artworks->nextPageUrl()
                            : null;
                    @endphp

                    <section class="px-6 pb-10 pt-8 md:px-10">
                        @if($galleryItems->isEmpty())
                            <div class="rounded-xl border border-white/10 bg-white/5 p-8 text-center text-white/60">
                                No artworks found yet. Check back soon.
                            </div>
                        @else
                            <div
                                data-react-masonry-gallery
                                data-artworks="{{ json_encode($galleryArtworks) }}"
                                data-gallery-type="{{ $gallery_type ?? 'browse' }}"
                                @if($galleryNextPageUrl) data-next-page-url="{{ $galleryNextPageUrl }}" @endif
                                @if($rankApiEndpoint) data-rank-api-endpoint="{{ $rankApiEndpoint }}" @endif
                                @if($rankApiType) data-rank-type="{{ $rankApiType }}" @endif
                                data-limit="24"
                                class="min-h-32"
                            ></div>
                        @endif
                    </section>

                    {{-- ─── Filter Slide-over Panel ──────────────────────────────────── --}}
                    @include('gallery._filter_panel')

                </main>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
@vite('resources/js/entry-masonry-gallery.jsx')
@vite('resources/js/entry-pill-carousel.jsx')
<script>
(function () {
    'use strict';

    // ── Filter Slide-over Panel ──────────────────────────────────────────
    function initGalleryFilterPanel() {
        var panel      = document.getElementById('gallery-filter-panel');
        var backdrop   = document.getElementById('gallery-filter-backdrop');
        var drawer     = document.getElementById('gallery-filter-drawer');
        var toggleBtn  = document.getElementById('gallery-filter-panel-toggle');
        var closeBtn   = document.getElementById('gallery-filter-panel-close');
        var applyBtn   = document.getElementById('gallery-filter-apply');
        var resetBtn   = document.getElementById('gallery-filter-reset');
        if (!panel || !drawer || !backdrop) return;

        var isOpen = false;

        function openPanel() {
            isOpen = true;
            panel.setAttribute('aria-hidden', 'false');
            panel.classList.remove('pointer-events-none');
            panel.classList.add('pointer-events-auto');
            backdrop.classList.remove('opacity-0');
            backdrop.classList.add('opacity-100');
            drawer.classList.remove('translate-x-full');
            drawer.classList.add('translate-x-0');
            if (toggleBtn) toggleBtn.setAttribute('aria-expanded', 'true');
            // Focus first interactive element in drawer
            var first = drawer.querySelector('button, input, select, a[href]');
            if (first) { setTimeout(function () { if (first) first.focus(); }, 320); }
        }

        function closePanel() {
            isOpen = false;
            panel.setAttribute('aria-hidden', 'true');
            panel.classList.add('pointer-events-none');
            panel.classList.remove('pointer-events-auto');
            backdrop.classList.add('opacity-0');
            backdrop.classList.remove('opacity-100');
            drawer.classList.add('translate-x-full');
            drawer.classList.remove('translate-x-0');
            if (toggleBtn) toggleBtn.setAttribute('aria-expanded', 'false');
        }

        if (toggleBtn) toggleBtn.addEventListener('click', function () { isOpen ? closePanel() : openPanel(); });
        if (closeBtn)  closeBtn.addEventListener('click', closePanel);
        backdrop.addEventListener('click', closePanel);

        // Close on ESC
        document.addEventListener('keydown', function (e) {
            if (isOpen && (e.key === 'Escape' || e.key === 'Esc')) { closePanel(); }
        });

        // Apply: collect all named inputs and navigate with updated params
        if (applyBtn) {
            applyBtn.addEventListener('click', function () {
                var url = new URL(window.location.href);
                url.searchParams.delete('page');

                // Radio groups: orientation, resolution, sort
                drawer.querySelectorAll('input[type="radio"]:checked').forEach(function (input) {
                    if ((input.name === 'orientation' || input.name === 'resolution') && input.value !== 'any') {
                        url.searchParams.set(input.name, input.value);
                    } else if (input.name === 'orientation' || input.name === 'resolution') {
                        url.searchParams.delete(input.name);
                    } else {
                        url.searchParams.set(input.name, input.value);
                    }
                });

                // Text inputs: author
                ['date_from', 'date_to', 'author'].forEach(function (name) {
                    var el = drawer.querySelector('[name="' + name + '"]');
                    if (el && el.value) {
                        url.searchParams.set(name, el.value);
                    } else {
                        url.searchParams.delete(name);
                    }
                });

                window.location.href = url.toString();
            });
        }

        // Reset: strip all filter params, keep only current path
        if (resetBtn) {
            resetBtn.addEventListener('click', function () {
                var url = new URL(window.location.href);
                ['orientation', 'resolution', 'author', 'date_from', 'date_to', 'sort', 'page'].forEach(function (p) {
                    url.searchParams.delete(p);
                });
                window.location.href = url.toString();
            });
        }
    }

    // ── Ranking Tab navigation ───────────────────────────────────────────
    // Clicking a tab updates ?sort= in the URL and navigates.
    // Active underline animation plays before navigation for visual feedback.
    function initRankingTabs() {
        var tabBar = document.getElementById('gallery-ranking-tabs');
        if (!tabBar) return;

        tabBar.addEventListener('click', function (e) {
            var btn = e.target.closest('[data-rank-tab]');
            if (!btn) return;

            var sortValue = btn.dataset.rankTab;
            if (!sortValue) return;

            // Optimistic visual feedback — light up the clicked tab
            tabBar.querySelectorAll('[data-rank-tab]').forEach(function (t) {
                var ind = t.querySelector('.nb-tab-indicator');
                if (t === btn) {
                    t.classList.add('text-white');
                    t.classList.remove('text-neutral-400');
                    if (ind) { ind.classList.add('bg-accent', 'scale-x-100'); ind.classList.remove('bg-transparent', 'scale-x-0'); }
                } else {
                    t.classList.remove('text-white');
                    t.classList.add('text-neutral-400');
                    if (ind) { ind.classList.remove('bg-accent', 'scale-x-100'); ind.classList.add('bg-transparent', 'scale-x-0'); }
                }
            });

            // Navigate to the new URL
            var url = new URL(window.location.href);
            url.searchParams.set('sort', sortValue);
            url.searchParams.delete('page');
            window.location.href = url.toString();
        });
    }

    function init() {
        initGalleryFilterPanel();
        initRankingTabs();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
}());
</script>
@endpush
