<?php

declare(strict_types=1);

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\ContentType;
use App\Models\Tag;
use App\Services\ArtworkSearchService;
use App\Services\Maturity\ArtworkMaturityService;
use App\Services\Tags\TagDiscoveryService;
use App\Services\ThumbnailPresenter;
use Illuminate\Http\Request;
use Illuminate\View\View;

final class TagController extends Controller
{
    public function __construct(
        private readonly ArtworkSearchService $search,
        private readonly ArtworkMaturityService $maturity,
        private readonly TagDiscoveryService  $tagDiscovery,
    ) {}

    public function index(Request $request): View
    {
        $query = trim((string) $request->query('q', ''));
        $featuredTags = $this->tagDiscovery->featuredTags();
        $risingTags = $this->tagDiscovery->risingTags($featuredTags);
        $tags = $this->tagDiscovery->paginatedTags($query);
        $tagStats = $this->tagDiscovery->stats($tags->total());

        return view('web.tags.index', [
            'tags'                  => $tags,
            'query'                 => $query,
            'featuredTags'          => $featuredTags,
            'risingTags'            => $risingTags,
            'tagStats'              => $tagStats,
            'page_title'            => 'Browse Tags — Skinbase',
            'page_meta_description' => 'Explore the most-used artwork tags on Skinbase and jump straight into the styles, themes, and aesthetics you want to browse.',
            'page_canonical'        => route('tags.index'),
            'page_robots'           => 'index,follow',
        ]);
    }

    public function show(Tag $tag, Request $request): View
    {
        $sort    = $request->query('sort', 'popular'); // popular | likes | latest | downloads
        $perPage = min((int) $request->query('per_page', 24), 100);

        $artworks = $this->search->byTag($tag->slug, $perPage, $sort);

        // Eager-load relations used by the gallery presenter and thumbnails.
        $artworks->getCollection()->each(fn($m) => $m->loadMissing(['user.profile', 'categories']));

        // Sidebar: main content type links (same as browse gallery)
        $mainCategories = ContentType::ordered()->get(['name', 'slug'])
            ->map(fn ($type) => (object) [
                'id'   => $type->id,
                'name' => $type->name,
                'slug' => $type->slug,
                'url'  => '/' . strtolower($type->slug),
            ]);

        // Map artworks into the lightweight shape expected by the gallery React component.
        $galleryCollection = collect($this->maturity->filterPayloadItems($artworks->getCollection()->map(function ($a) use ($request): array {
            $primaryCategory = $a->categories->sortBy('sort_order')->first();
            $present = ThumbnailPresenter::present($a, 'md');
            $avatarUrl = \App\Support\AvatarUrl::forUser((int) ($a->user_id ?? 0), $a->user?->profile?->avatar_hash ?? null, 64);

            return $this->maturity->decoratePayload([
                'id'            => $a->id,
                'name'          => $a->title ?? ($a->name ?? null),
                'content_type_name' => $primaryCategory?->contentType?->name ?? '',
                'content_type_slug' => $primaryCategory?->contentType?->slug ?? '',
                'category_name' => $primaryCategory->name ?? '',
                'category_slug' => $primaryCategory->slug ?? '',
                'thumb_url'     => $present['url'] ?? ($a->thumbUrl('md') ?? null),
                'thumb_srcset'  => $present['srcset'] ?? null,
                'uname'         => $a->user?->name ?? '',
                'username'      => $a->user?->username ?? '',
                'avatar_url'    => $avatarUrl,
                'published_at'  => $a->published_at ?? null,
                'width'         => $a->width  ?? null,
                'height'        => $a->height ?? null,
                'slug'          => $a->slug ?? null,
            ], $a, $request->user());
        })->values()->all(), $request->user()))
            ->map(static fn (array $item): object => (object) $item)
            ->values();

        // Replace paginator collection with the gallery-shaped collection so
        // the gallery.index blade will generate the expected JSON payload.
        if (method_exists($artworks, 'setCollection')) {
            $artworks->setCollection($galleryCollection);
        }

        // Determine gallery sort mapping so the gallery UI highlights the right tab.
        $sortMapToGallery = [
            'popular'   => 'trending',
            'latest'    => 'latest',
            'likes'     => 'top-rated',
            'downloads' => 'downloaded',
        ];
        $gallerySort = $sortMapToGallery[$sort] ?? 'trending';

        $sortLabels = [
            'popular' => 'Most viewed',
            'likes' => 'Most liked',
            'latest' => 'Latest uploads',
            'downloads' => 'Most downloaded',
        ];

        $relatedTags = $this->tagDiscovery->relatedTags($tag);

        // Build simple pagination SEO links
        $prev = method_exists($artworks, 'previousPageUrl') ? $artworks->previousPageUrl() : null;
        $next = method_exists($artworks, 'nextPageUrl') ? $artworks->nextPageUrl() : null;

        return view('gallery.index', [
            'gallery_type'    => 'tag',
            'mainCategories'  => $mainCategories,
            'subcategories'   => collect(),
            'contentType'     => null,
            'category'        => null,
            'artworks'        => $artworks,
            'gallery_nav_section' => 'tags',
            'current_sort'    => $gallerySort,
            'sort_options'    => [
                ['value' => 'trending', 'label' => '🔥 Trending'],
                ['value' => 'fresh', 'label' => '🆕 New & Hot'],
                ['value' => 'top-rated', 'label' => '⭐ Top Rated'],
                ['value' => 'latest', 'label' => '🕐 Latest'],
            ],
            'hero_title'      => '#' . $tag->name,
            'hero_description' => 'Browse artworks tagged "' . $tag->name . '" and jump between the strongest matching uploads on Skinbase.',
            'tag_context'     => [
                'name' => $tag->name,
                'slug' => $tag->slug,
                'artworks_total' => $artworks->total(),
                'usage_count' => (int) $tag->usage_count,
                'current_sort_label' => $sortLabels[$sort] ?? 'Most viewed',
                'rss_url' => route('rss.tag', ['slug' => $tag->slug]),
                'related_tags' => $relatedTags,
            ],
            'breadcrumbs'     => collect([
                (object) ['name' => 'Home', 'url' => '/'],
                (object) ['name' => 'Tags', 'url' => route('tags.index')],
                (object) ['name' => $tag->name, 'url' => route('tags.show', $tag->slug)],
            ]),
            'page_title'      => 'Artworks tagged "' . $tag->name . '" — Skinbase',
            'page_meta_description' => 'Browse all Skinbase artworks tagged "' . $tag->name . '".',
            'page_meta_keywords'    => $tag->slug . ', skinbase, artworks, tag',
            'page_canonical'  => route('tags.show', $tag->slug),
            'page_rel_prev'   => $prev,
            'page_rel_next'   => $next,
            'page_robots'     => 'index,follow',
        ]);
    }
}

