<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Artwork;
use App\Services\CommunityActivityService;
use App\Services\ArtworkSearchService;
use App\Services\ArtworkService;
use App\Services\EarlyGrowth\AdaptiveTimeWindow;
use App\Services\EarlyGrowth\GridFiller;
use App\Services\Maturity\ArtworkMaturityService;
use App\Services\Recommendations\RecommendationFeedResolver;
use App\Services\UserSuggestionService;
use App\Services\ThumbnailPresenter;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * DiscoverController
 *
 * Powers the /discover/* discovery pages:
 *   - /discover/trending       → most viewed in last 7 days
 *   - /discover/fresh          → latest uploads  (replaces /uploads/latest)
 *   - /discover/top-rated      → highest favourite count
 *   - /discover/most-downloaded → most downloaded all-time
 *   - /discover/on-this-day    → published on this calendar day in previous years
 *   - /discover/for-you        → personalised feed (auth required)
 */
final class DiscoverController extends Controller
{
    public function __construct(
        private readonly ArtworkService        $artworkService,
        private readonly ArtworkSearchService  $searchService,
        private readonly AdaptiveTimeWindow    $timeWindow,
        private readonly RecommendationFeedResolver $feedResolver,
        private readonly GridFiller            $gridFiller,
        private readonly CommunityActivityService $communityActivity,
        private readonly UserSuggestionService $userSuggestions,
        private readonly ArtworkMaturityService $maturity,
    ) {}

    // ─── /discover/trending ──────────────────────────────────────────────────

    public function trending(Request $request)
    {
        $perPage = 24;
        $windowDays = $this->timeWindow->getTrendingWindowDays(30);

        try {
            $results = $this->searchService->discoverTrending($perPage);
        } catch (\Throwable) {
            $results = $this->fallbackTrendingFromDatabase($perPage, $windowDays);
        }

        if ($this->paginatorIsEmpty($results)) {
            $results = $this->fallbackTrendingFromDatabase($perPage, $windowDays);
        }

        $this->hydrateDiscoverSearchResults($results);

        return view('web.discover.index', [
            'artworks'    => $results,
            'page_title'  => 'Trending Artworks',
            'page_canonical' => $this->canonicalRoute('discover.trending'),
            'section'     => 'trending',
            'description' => 'The most-viewed artworks on Skinbase over the past 7 days.',
            'icon'        => 'fa-fire',
        ]);
    }

    // ─── /discover/rising ────────────────────────────────────────────────────

    public function rising(Request $request)
    {
        $perPage = 24;
        $windowDays = $this->timeWindow->getTrendingWindowDays(30);

        try {
            $results = $this->searchService->discoverRising($perPage);
        } catch (\Throwable) {
            $results = $this->fallbackRisingFromDatabase($perPage, $windowDays);
        }

        if ($this->paginatorIsEmpty($results)) {
            $results = $this->fallbackRisingFromDatabase($perPage, $windowDays);
        }

        if ($this->paginatorHasNoRisingMomentum($results)) {
            $results = $this->fallbackRisingLowSignalFromDatabase($perPage, $windowDays);
        }

        $this->hydrateDiscoverSearchResults($results);

        return view('web.discover.index', [
            'artworks'    => $results,
            'page_title'  => 'Rising Now',
            'page_canonical' => $this->canonicalRoute('discover.rising'),
            'section'     => 'rising',
            'description' => 'Fastest growing artworks right now.',
            'icon'        => 'fa-rocket',
        ]);
    }

    // ─── /discover/fresh ─────────────────────────────────────────────────────

    public function fresh(Request $request)
    {
        $perPage = 24;
        $results = $this->searchService->discoverFresh($perPage);

        if ($this->paginatorIsEmpty($results)) {
            $results = $this->fallbackFreshFromDatabase($perPage);
        }

        $this->hydrateDiscoverSearchResults($results);

        return view('web.discover.index', [
            'artworks'    => $results,
            'page_title'  => 'Fresh Uploads',
            'page_canonical' => $this->canonicalRoute('discover.fresh'),
            'section'     => 'fresh',
            'description' => 'The latest artworks just uploaded to Skinbase.',
            'icon'        => 'fa-bolt',
        ]);
    }

    // ─── /discover/top-rated ─────────────────────────────────────────────────

    public function topRated(Request $request)
    {
        $perPage = 24;
        $page    = max(1, (int) $request->query('page', 1));
        $results = $this->searchService->discoverTopRated($perPage);
        $results = $this->gridFiller->fill($results, 0, $page);
        $this->hydrateDiscoverSearchResults($results);

        return view('web.discover.index', [
            'artworks'    => $results,
            'page_title'  => 'Top Rated Artworks',
            'page_canonical' => $this->canonicalRoute('discover.top-rated'),
            'section'     => 'top-rated',
            'description' => 'The most-loved artworks on Skinbase, ranked by community favourites.',
            'icon'        => 'fa-medal',
        ]);
    }

    // ─── /discover/most-downloaded ───────────────────────────────────────────

    public function mostDownloaded(Request $request)
    {
        $perPage = 24;
        $page    = max(1, (int) $request->query('page', 1));
        $results = $this->searchService->discoverMostDownloaded($perPage);
        $results = $this->gridFiller->fill($results, 0, $page);
        $this->hydrateDiscoverSearchResults($results);

        return view('web.discover.index', [
            'artworks'    => $results,
            'page_title'  => 'Most Downloaded',
            'page_canonical' => $this->canonicalRoute('discover.most-downloaded'),
            'section'     => 'most-downloaded',
            'description' => 'All-time most downloaded artworks on Skinbase.',
            'icon'        => 'fa-download',
        ]);
    }

    // ─── /discover/on-this-day ───────────────────────────────────────────────

    public function onThisDay(Request $request)
    {
        $perPage = 24;
        $today   = now();

        $artworks = Artwork::query()
            ->catalogVisible()
            ->with([
                'user:id,name',
                'user.profile:user_id,avatar_hash',
                'categories:id,name,slug,content_type_id,parent_id,sort_order',
                'categories.contentType:id,slug,name',
            ])
            ->whereMonth('published_at', $today->month)
            ->whereDay('published_at', $today->day)
            ->whereYear('published_at', '<', $today->year)
            ->orderMissingThumbnailsLast()
            ->orderByDesc('published_at')
            ->paginate($perPage)
            ->withQueryString();

        $artworks->getCollection()->transform(fn ($a) => $this->presentArtwork($a));

        return view('web.discover.index', [
            'artworks'    => $artworks,
            'page_title'  => 'On This Day',
            'page_canonical' => $this->canonicalRoute('discover.on-this-day'),
            'section'     => 'on-this-day',
            'description' => 'Artworks published on ' . $today->format('F j') . ' in previous years.',
            'icon'        => 'fa-calendar-day',
        ]);
    }

    // ─── /creators/rising ────────────────────────────────────────────────────

    public function risingCreators(Request $request)
    {
        $perPage = 20;

        // Creators with artworks published in the last 90 days, ordered by total recent views.
        $hasStats = false;
        try { $hasStats = Schema::hasTable('artwork_stats'); } catch (\Throwable) {}

        if ($hasStats) {
            $sub = Artwork::query()
                ->catalogVisible()
                ->join('artwork_stats', 'artwork_stats.artwork_id', '=', 'artworks.id')
                ->where('artworks.published_at', '>=', now()->subDays(90))
                ->selectRaw('artworks.user_id, SUM(artwork_stats.views) as recent_views, MAX(artworks.published_at) as latest_published')
                ->groupBy('artworks.user_id');
        } else {
            $sub = Artwork::query()
                ->catalogVisible()
                ->where('published_at', '>=', now()->subDays(90))
                ->selectRaw('user_id, COUNT(*) as recent_views, MAX(published_at) as latest_published')
                ->groupBy('user_id');
        }

        $creators = DB::table(DB::raw('(' . $sub->toSql() . ') as t'))
            ->mergeBindings($sub->getQuery())
            ->join('users as u', 'u.id', '=', 't.user_id')
            ->leftJoin('user_profiles as up', 'up.user_id', '=', 't.user_id')
            ->select('u.id as user_id', 'u.name as uname', 'u.username', 't.recent_views', 't.latest_published', 'up.avatar_hash')
            ->orderByDesc('t.recent_views')
            ->orderByDesc('t.latest_published')
            ->paginate($perPage)
            ->withQueryString();

        $creators->getCollection()->transform(function ($row) {
            return (object) [
                'user_id'     => $row->user_id,
                'uname'       => $row->uname,
                'username'    => $row->username,
                'total'       => (int) $row->recent_views,
                'metric'      => 'views',
                'avatar_hash' => $row->avatar_hash ?? null,
            ];
        });

        return view('web.creators.rising', [
            'creators'   => $creators,
            'page_title' => 'Rising Creators — Skinbase',
            'page_canonical' => $this->canonicalRoute('creators.rising'),
        ]);
    }

    // ─── /discover/for-you ───────────────────────────────────────────────────

    /**
     * Personalised "For You" feed page.
     *
     * Uses the newer personalized feed service so the web surface stays aligned
     * with the API recommendation stack and discovery-event training loop.
     */
    public function forYou(Request $request)
    {
        $user    = $request->user();
        $limit   = max(1, min(50, (int) $request->query('limit', 40)));
        $cursor  = $request->query('cursor') ?: null;

        $feedResult = $this->feedResolver->getFeed(
            userId: (int) $user->id,
            limit: $limit,
            cursor: is_string($cursor) ? $cursor : null,
            algoVersion: $request->filled('algo_version') ? (string) $request->query('algo_version') : null,
        );

        $artworks = collect($feedResult['data'] ?? [])->map(
            fn (array $item) => $this->presentRecommendedArtwork($item)
        );
        $artworks = $this->reorderDiscoverItemsByThumbnailHealth($artworks)->values();

        $meta       = $feedResult['meta'] ?? [];
        $nextCursor = $meta['next_cursor'] ?? null;

        if ($request->ajax()) {
            return response()->json([
                'artworks' => $artworks->map(fn (object $artwork) => (array) $artwork)->all(),
                'next_cursor' => $nextCursor,
                'has_more' => ! empty($nextCursor),
                'meta' => $meta,
            ]);
        }

        return view('web.discover.for-you', [
            'artworks'    => $artworks,
            'page_title'  => 'For You',
            'section'     => 'for-you',
            'description' => 'Artworks picked for you based on your taste.',
            'icon'        => 'fa-wand-magic-sparkles',
            'next_cursor' => $nextCursor,
            'feed_meta' => $meta,
            'cache_status' => $meta['cache_status'] ?? null,
        ]);
    }

    // ─── /discover/following ─────────────────────────────────────────────────

    public function following(Request $request)
    {
        $user    = $request->user();
        $perPage = 24;

        // Subquery: IDs of users this viewer follows
        $followingIds = DB::table('user_followers')
            ->where('follower_id', $user->id)
            ->pluck('user_id');

        if ($followingIds->isEmpty()) {
            // Trending fallback: show popular artworks so the page isn't blank
            try {
                $fallbackResults = $this->searchService->discoverTrending(12);
                $fallbackArtworks = $fallbackResults->getCollection()
                    ->transform(fn ($a) => $this->presentArtwork($a));
            } catch (\Throwable) {
                $fallbackArtworks = collect();
            }

            // Suggested creators: most-followed users the viewer doesn't follow yet
            $suggestedCreators = $this->userSuggestions->suggestFor($user, 6);

            return view('web.discover.index', [
                'artworks'           => collect(),
                'page_title'         => 'Following Feed',
                'page_canonical'     => $this->canonicalRoute('discover.following'),
                'section'            => 'following',
                'description'        => 'Follow some creators to see their work here.',
                'icon'               => 'fa-user-group',
                'empty'              => true,
                'fallback_trending'  => $fallbackArtworks,
                'fallback_creators'  => $suggestedCreators,
                'following_activity' => [],
                'network_trending'   => [],
                'suggested_users'    => $suggestedCreators,
            ]);
        }

        $page    = (int) request()->get('page', 1);
        $cacheKey = "discover.following.{$user->id}.p{$page}";

        $artworks = Cache::remember($cacheKey, 60, function () use ($user, $followingIds, $perPage): \Illuminate\Pagination\LengthAwarePaginator {
            return Artwork::query()
                ->catalogVisible()
                ->with(['user:id,name,username', 'categories:id,name,slug,content_type_id,parent_id,sort_order'])
                ->whereIn('user_id', $followingIds)
                ->orderMissingThumbnailsLast()
                ->orderByDesc('published_at')
                ->paginate($perPage)
                ->withQueryString();
        });

        $artworks->getCollection()->transform(fn ($a) => $this->presentArtwork($a));

        $networkActivity = $this->communityActivity->getFeed(
            viewer: $user,
            filter: 'following',
            page: 1,
            perPage: 8,
            actorUserId: null,
        );

        return view('web.discover.index', [
            'artworks'    => $artworks,
            'page_title'  => 'Following Feed',
            'page_canonical' => $this->canonicalRoute('discover.following'),
            'section'     => 'following',
            'description' => 'The latest artworks from creators you follow.',
            'icon'        => 'fa-user-group',
            'following_activity' => $networkActivity['data'] ?? [],
            'network_trending' => $this->buildNetworkTrendingArtworks($followingIds->all(), 8),
            'suggested_users' => $this->userSuggestions->suggestFor($user, 6),
        ]);
    }

    // ─── Helpers ─────────────────────────────────────────────────────────────

    private function paginatorIsEmpty($paginator): bool
    {
        if (! is_object($paginator) || ! method_exists($paginator, 'getCollection')) {
            return true;
        }

        $items = $paginator->getCollection();

        return ! $items || $items->isEmpty();
    }

    private function canonicalRoute(string $routeName): string
    {
        return route($routeName);
    }

    private function paginatorHasNoRisingMomentum($paginator): bool
    {
        if (! is_object($paginator) || ! method_exists($paginator, 'getCollection')) {
            return true;
        }

        $items = $paginator->getCollection();

        if (! $items || $items->isEmpty()) {
            return true;
        }

        return $items->every(function ($item): bool {
            $heat = (float) ($item->heat_score ?? $item->stats?->heat_score ?? 0);
            $velocity = (float) ($item->engagement_velocity ?? $item->stats?->engagement_velocity ?? 0);

            return $heat <= 0.0 && $velocity <= 0.0;
        });
    }

    private function fallbackFreshFromDatabase(int $perPage)
    {
        return Artwork::query()
            ->catalogVisible()
            ->with([
                'user:id,name,username',
                'user.profile:user_id,avatar_hash',
                'categories:id,name,slug,content_type_id,parent_id,sort_order',
                'categories.contentType:id,slug,name',
            ])
            ->orderMissingThumbnailsLast()
            ->orderByDesc('published_at')
            ->orderByDesc('id')
            ->paginate($perPage)
            ->withQueryString();
    }

    private function fallbackTrendingFromDatabase(int $perPage, int $windowDays)
    {
        $cutoff = now()->subDays($windowDays)->startOfDay();

        return Artwork::query()
            ->catalogVisible()
            ->with([
                'user:id,name,username',
                'user.profile:user_id,avatar_hash',
                'categories:id,name,slug,content_type_id,parent_id,sort_order',
                'categories.contentType:id,slug,name',
            ])
            ->leftJoin('artwork_stats as discover_stats', 'discover_stats.artwork_id', '=', 'artworks.id')
            ->select('artworks.*')
            ->where('artworks.published_at', '>=', $cutoff)
            ->orderMissingThumbnailsLast()
            ->orderByDesc('discover_stats.ranking_score')
            ->orderByDesc('discover_stats.engagement_velocity')
            ->orderByDesc('discover_stats.views')
            ->orderByDesc('artworks.published_at')
            ->orderByDesc('artworks.id')
            ->paginate($perPage)
            ->withQueryString();
    }

    private function fallbackRisingFromDatabase(int $perPage, int $windowDays)
    {
        $cutoff = now()->subDays($windowDays)->startOfDay();

        return Artwork::query()
            ->catalogVisible()
            ->with([
                'user:id,name,username',
                'user.profile:user_id,avatar_hash',
                'categories:id,name,slug,content_type_id,parent_id,sort_order',
                'categories.contentType:id,slug,name',
            ])
            ->leftJoin('artwork_stats as discover_stats', 'discover_stats.artwork_id', '=', 'artworks.id')
            ->select('artworks.*')
            ->selectRaw('COALESCE(discover_stats.heat_score, 0) as heat_score')
            ->selectRaw('COALESCE(discover_stats.engagement_velocity, 0) as engagement_velocity')
            ->where('artworks.published_at', '>=', $cutoff)
            ->orderMissingThumbnailsLast()
            ->orderByDesc('discover_stats.heat_score')
            ->orderByDesc('discover_stats.engagement_velocity')
            ->orderByDesc('artworks.published_at')
            ->orderByDesc('artworks.id')
            ->paginate($perPage)
            ->withQueryString();
    }

    private function fallbackRisingLowSignalFromDatabase(int $perPage, int $windowDays)
    {
        $cutoff = now()->subDays($windowDays)->startOfDay();
        $recentActivity = $this->risingRecentActivitySubquery();

        return Artwork::query()
            ->catalogVisible()
            ->with([
                'user:id,name,username',
                'user.profile:user_id,avatar_hash',
                'categories:id,name,slug,content_type_id,parent_id,sort_order',
                'categories.contentType:id,slug,name',
            ])
            ->leftJoin('artwork_stats as discover_stats', 'discover_stats.artwork_id', '=', 'artworks.id')
            ->leftJoinSub($recentActivity, 'recent_rising_activity', function ($join): void {
                $join->on('recent_rising_activity.artwork_id', '=', 'artworks.id');
            })
            ->select('artworks.*')
            ->selectRaw('COALESCE(discover_stats.heat_score, 0) as heat_score')
            ->selectRaw('COALESCE(discover_stats.engagement_velocity, 0) as engagement_velocity')
            ->selectRaw('COALESCE(recent_rising_activity.recent_signal_24h, 0) as recent_signal_24h')
            ->where('artworks.published_at', '>=', $cutoff)
            ->orderMissingThumbnailsLast()
            ->orderByDesc('recent_signal_24h')
            ->orderByDesc('artworks.published_at')
            ->orderByDesc('artworks.id')
            ->paginate($perPage)
            ->withQueryString();
    }

    private function risingRecentActivitySubquery()
    {
        $since = now()->startOfHour()->subHours(24);

        return DB::table('artwork_metric_snapshots_hourly as rising_snapshots')
            ->selectRaw('rising_snapshots.artwork_id')
            ->selectRaw('(
                COALESCE(MAX(rising_snapshots.views_count) - MIN(rising_snapshots.views_count), 0)
                + (COALESCE(MAX(rising_snapshots.downloads_count) - MIN(rising_snapshots.downloads_count), 0) * 3)
                + (COALESCE(MAX(rising_snapshots.favourites_count) - MIN(rising_snapshots.favourites_count), 0) * 4)
                + (COALESCE(MAX(rising_snapshots.comments_count) - MIN(rising_snapshots.comments_count), 0) * 5)
                + (COALESCE(MAX(rising_snapshots.shares_count) - MIN(rising_snapshots.shares_count), 0) * 6)
            ) as recent_signal_24h')
            ->where('rising_snapshots.bucket_hour', '>=', $since)
            ->groupBy('rising_snapshots.artwork_id');
    }

    private function hydrateDiscoverSearchResults($paginator): void
    {
        if (!is_object($paginator) || !method_exists($paginator, 'getCollection') || !method_exists($paginator, 'setCollection')) {
            return;
        }

        $items = $paginator->getCollection();
        if (!$items || $items->isEmpty()) {
            return;
        }

        $ids = $items
            ->pluck('id')
            ->filter(fn ($id) => is_numeric($id) && (int) $id > 0)
            ->map(fn ($id) => (int) $id)
            ->values();

        if ($ids->isEmpty()) {
            return;
        }

        $byId = Artwork::query()
            ->catalogVisible()
            ->whereIn('id', $ids)
            ->with([
                'user:id,name,username',
                'user.profile:user_id,avatar_hash',
                'group:id,name,slug,avatar_path',
                'categories:id,name,slug,content_type_id,parent_id,sort_order',
                'categories.contentType:id,slug,name',
            ])
            ->get()
            ->keyBy('id');

        $paginator->setCollection(
            $items->map(function ($item) use ($byId) {
                $id = (int) ($item->id ?? 0);
                $full = $id > 0 ? $byId->get($id) : null;

                if ($full instanceof Artwork) {
                    return $this->presentArtwork($full);
                }

                if ($id > 0) {
                    return null;
                }

                return (object) [
                    'id'            => $item->id ?? 0,
                    'name'          => $item->title ?? $item->name ?? 'Untitled',
                    'category_name' => $item->category_name ?? $item->category ?? '',
                    'category_slug' => $item->category_slug ?? '',
                    'thumb_url'     => $item->thumbnail_url ?? $item->thumb_url ?? $item->thumb ?? null,
                    'thumb_srcset'  => $item->thumb_srcset ?? null,
                    'uname'         => $item->author_name ?? $item->author ?? $item->uname ?? 'Skinbase',
                    'username'      => (($item->published_as_type ?? null) === 'group') ? '' : ($item->username ?? ''),
                    'avatar_url'    => \App\Support\AvatarUrl::forUser((int) ($item->user_id ?? $item->author_id ?? 0), null, 64),
                    'profile_url'   => $item->profile_url ?? null,
                    'published_as_type' => $item->published_as_type ?? null,
                    'publisher'     => $item->publisher ?? null,
                    'published_at'  => $item->published_at ?? null,
                    'width'         => isset($item->width)  && $item->width  ? (int) $item->width  : null,
                    'height'        => isset($item->height) && $item->height ? (int) $item->height : null,
                ];
            })->filter()->values()
        );
    }

    private function presentArtwork(Artwork $artwork): object
    {
        $primaryCategory = $artwork->categories->sortBy('sort_order')->first();
        $present         = ThumbnailPresenter::present($artwork, 'md');
        $group           = $artwork->group;
        $isGroupPublisher = $group !== null;
        $avatarUrl       = $isGroupPublisher
            ? $group->avatarUrl()
            : \App\Support\AvatarUrl::forUser(
                (int) ($artwork->user_id ?? 0),
                $artwork->user?->profile?->avatar_hash ?? null,
                64
            );
        $displayName     = $isGroupPublisher ? ($group->name ?? 'Skinbase') : ($artwork->user?->name ?? 'Skinbase');
        $username        = $isGroupPublisher ? '' : ($artwork->user?->username ?? '');
        $profileUrl      = $isGroupPublisher ? $group->publicUrl() : ($username !== '' ? '/@' . $username : null);

        return (object) $this->maturity->decoratePayload([
            'id'            => $artwork->id,
            'name'          => $artwork->title,
            'content_type_name' => $primaryCategory?->contentType?->name ?? '',
            'content_type_slug' => $primaryCategory?->contentType?->slug ?? '',
            'category_name' => $primaryCategory->name ?? '',
            'category_slug' => $primaryCategory->slug ?? '',
            'gid_num'       => $primaryCategory ? ((int) $primaryCategory->id % 5) * 5 : 0,
            'thumb_url'     => $present['url'],
            'thumb_srcset'  => $present['srcset'] ?? $present['url'],
            'uname'         => $displayName,
            'username'      => $username,
            'avatar_url'    => $avatarUrl,
            'profile_url'   => $profileUrl,
            'published_as_type' => $isGroupPublisher ? 'group' : 'user',
            'publisher'     => [
                'type' => $isGroupPublisher ? 'group' : 'user',
                'name' => $displayName,
                'username' => $username,
                'avatar_url' => $avatarUrl,
                'profile_url' => $profileUrl,
            ],
            'published_at'  => $artwork->published_at,
            'width'         => $artwork->width  ?? null,
            'height'        => $artwork->height ?? null,
        ], $artwork, request()->user());
    }

    /**
     * @param array<string, mixed> $item
     */
    private function presentRecommendedArtwork(array $item): object
    {
        $width = isset($item['width']) && (int) $item['width'] > 0 ? (int) $item['width'] : null;
        $height = isset($item['height']) && (int) $item['height'] > 0 ? (int) $item['height'] : null;

        return (object) [
            'id' => (int) ($item['id'] ?? 0),
            'name' => (string) ($item['title'] ?? 'Untitled'),
            'thumb_url' => $item['thumbnail_url'] ?? null,
            'thumb_srcset' => $item['thumbnail_srcset'] ?? null,
            'uname' => (string) ($item['author'] ?? 'Artist'),
            'username' => (string) ($item['username'] ?? ''),
            'avatar_url' => $item['avatar_url'] ?? null,
            'published_at' => $item['published_at'] ?? null,
            'slug' => (string) ($item['slug'] ?? ''),
            'url' => $item['url'] ?? null,
            'width' => $width,
            'height' => $height,
            'content_type_name' => (string) ($item['content_type_name'] ?? ''),
            'content_type_slug' => (string) ($item['content_type_slug'] ?? ''),
            'category_name' => (string) ($item['category_name'] ?? ''),
            'category_slug' => (string) ($item['category_slug'] ?? ''),
            'primary_tag' => $item['primary_tag'] ?? null,
            'tags' => is_array($item['tags'] ?? null) ? $item['tags'] : [],
            'recommendation_source' => (string) ($item['source'] ?? 'mixed'),
            'recommendation_reason' => (string) ($item['reason'] ?? 'Picked for you'),
            'recommendation_score' => isset($item['score']) ? round((float) $item['score'], 4) : null,
            'recommendation_algo_version' => (string) ($item['algo_version'] ?? ''),
            'hide_artwork_endpoint' => route('api.discovery.feedback.hide-artwork'),
            'dislike_tag_endpoint' => route('api.discovery.feedback.dislike-tag'),
        ];
    }

    private function buildNetworkTrendingArtworks(array $followingIds, int $limit = 8): array
    {
        if ($followingIds === []) {
            return [];
        }

        return Artwork::query()
            ->catalogVisible()
            ->with(['user:id,name,username', 'user.profile:user_id,avatar_hash', 'stats:artwork_id,views,favorites,comments_count,heat_score'])
            ->whereIn('user_id', $followingIds)
            ->where('published_at', '>=', now()->subDays(30))
            ->leftJoin('artwork_stats as ast', 'ast.artwork_id', '=', 'artworks.id')
            ->orderMissingThumbnailsLast()
            ->orderByDesc(DB::raw('COALESCE(ast.heat_score, 0)'))
            ->orderByDesc(DB::raw('COALESCE(ast.favorites, 0)'))
            ->orderByDesc('artworks.published_at')
            ->limit(max(1, $limit))
            ->select('artworks.*')
            ->get()
            ->map(fn (Artwork $artwork) => [
                'id' => (int) $artwork->id,
                'title' => (string) $artwork->title,
                'url' => route('art.show', ['id' => (int) $artwork->id, 'slug' => $artwork->slug]),
                'thumb_url' => $artwork->thumb_url,
                'published_at' => $artwork->published_at?->diffForHumans(),
                'author' => [
                    'username' => $artwork->user?->username,
                    'name' => $artwork->user?->name,
                    'avatar_url' => $artwork->user?->profile?->avatar_url,
                    'profile_url' => $artwork->user?->username ? '/@' . strtolower((string) $artwork->user->username) : null,
                ],
                'stats' => [
                    'favorites' => (int) ($artwork->stats?->favorites ?? 0),
                    'views' => (int) ($artwork->stats?->views ?? 0),
                    'comments' => (int) ($artwork->stats?->comments_count ?? 0),
                ],
            ])
            ->values()
            ->all();
    }

    /**
     * @param Collection<int, object> $items
     * @return Collection<int, object>
     */
    private function reorderDiscoverItemsByThumbnailHealth(Collection $items): Collection
    {
        if ($items->isEmpty()) {
            return $items;
        }

        $ids = $items
            ->pluck('id')
            ->filter(fn ($id) => is_numeric($id) && (int) $id > 0)
            ->map(fn ($id) => (int) $id)
            ->values();

        if ($ids->isEmpty()) {
            return $items;
        }

        $missingIds = Artwork::query()
            ->whereIn('id', $ids)
            ->where('has_missing_thumbnails', true)
            ->pluck('id')
            ->map(fn ($id) => (int) $id)
            ->flip();

        if ($missingIds->isEmpty()) {
            return $items;
        }

        $healthy = $items->reject(fn ($item) => $missingIds->has((int) ($item->id ?? 0)));

        return $healthy
            ->concat($items->filter(fn ($item) => $missingIds->has((int) ($item->id ?? 0))))
            ->values();
    }
}
