<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Inertia\Middleware;

final class HandleInertiaRequests extends Middleware
{
    protected $rootView = 'upload';

    /**
     * Select the root Blade view based on route prefix.
     */
    public function rootView(Request $request): string
    {
        if ($request->path() === 'leaderboard') {
            return 'leaderboard';
        }

        if (str_starts_with($request->path(), 'studio')) {
            return 'studio';
        }

        // Profile pages: /@{username}
        if (str_starts_with($request->path(), '@')) {
            return 'profile.show';
        }

        // Feed pages — ordered most-specific first
        if ($request->path() === 'feed/trending') {
            return 'feed.trending';
        }

        if ($request->path() === 'feed/saved') {
            return 'feed.saved';
        }

        if (str_starts_with($request->path(), 'feed')) {
            return 'feed.following';
        }

        // Hashtag pages: /tags/{tag}
        if (str_starts_with($request->path(), 'tags/')) {
            return 'feed.hashtag';
        }

        return $this->rootView;
    }

    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    public function share(Request $request): array
    {
        return array_merge(parent::share($request), [
            'auth' => [
                'user' => $request->user() ? [
                    'id' => $request->user()->id,
                    'name' => $request->user()->name,
                ] : null,
            ],
            'cdn' => [
                'files_url' => config('cdn.files_url'),
            ],
        ]);
    }
}
