<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\ArtworkService;
use App\Services\CategoryDirectoryService;
use App\Models\Category;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class CategoryController extends Controller
{
    protected ArtworkService $artworkService;
    protected CategoryDirectoryService $categoryDirectory;

    public function __construct(ArtworkService $artworkService, CategoryDirectoryService $categoryDirectory)
    {
        $this->artworkService = $artworkService;
        $this->categoryDirectory = $categoryDirectory;
    }

    public function index(Request $request)
    {
        return $this->browseCategories($request);
    }

    public function show(Request $request, $id, $slug = null, $group = null)
    {
        $path = trim($request->path(), '/');
        $segments = array_values(array_filter(explode('/', $path)));

        if (count($segments) < 2 || strtolower($segments[0]) !== 'category') {
            return view('shared.placeholder');
        }

        $parts = array_slice($segments, 1);

        $first = $parts[0] ?? null;
        if ($first !== null && ctype_digit((string) $first)) {
            try {
                $category = Category::findOrFail((int) $first);
                $contentTypeSlug = $category->contentType->slug ?? null;
                $canonical = '/' . strtolower($contentTypeSlug) . '/' . $category->full_slug_path;
                return redirect($canonical, 301);
            } catch (ModelNotFoundException $e) {
                abort(404);
            }
        }

        $contentTypeSlug = array_shift($parts);
        $slugs = array_merge([$contentTypeSlug], $parts);

        $perPage = (int) $request->get('per_page', 40);
        $sort = (string) $request->get('sort', 'latest');

        try {
            $artworks = $this->artworkService->getArtworksByCategoryPath($slugs, $perPage, $sort);
        } catch (ModelNotFoundException $e) {
            abort(404);
        }

        try {
            $category = $this->artworkService->resolveCategoryByPath($slugs);
        } catch (\Throwable $e) {
            $category = null;
        }

        if (! $category) {
            abort(404);
        }

        $subcategories = $category->children()->orderBy('sort_order')->orderBy('name')->get();

        $breadcrumbs = collect(array_merge([
            (object) ['name' => 'Home', 'url' => '/'],
            (object) ['name' => 'Explore', 'url' => '/browse'],
            (object) ['name' => $category->contentType->name, 'url' => '/' . strtolower((string) $category->contentType->slug)],
        ], collect($category->breadcrumbs)->map(fn ($crumb) => (object) [
            'name' => $crumb->name,
            'url' => $crumb->url,
        ])->all()));

        $page_title = sprintf('%s — %s — Skinbase', $category->name, $category->contentType->name);
        $page_meta_description = $category->description ?? ($category->contentType->name . ' artworks on Skinbase');
        $page_meta_keywords = strtolower($category->contentType->slug) . ', skinbase, artworks, wallpapers, skins, photography';
        $page_canonical = url()->current();

        return view('web.category', compact(
            'page_title',
            'page_meta_description',
            'page_meta_keywords',
            'page_canonical',
            'breadcrumbs',
            'group',
            'category',
            'subcategories',
            'artworks'
        ));
    }

    public function browseCategories(Request $request)
    {
        $pageTitle = 'All Categories – Wallpapers, Skins & Digital Art | Skinbase';
        $pageDescription = 'Browse all categories on Skinbase including wallpapers, skins, themes, and digital art collections.';
        $payload = $this->categoryDirectory->getDirectoryPayload(
            (string) $request->query('q', ''),
            (string) $request->query('sort', 'popular'),
            (int) $request->query('page', 1),
            (int) $request->query('per_page', 24),
        );

        return view('web.categories', [
            'initialPayload' => $payload,
            'page_title' => $pageTitle,
            'page_meta_description' => $pageDescription,
            'page_canonical' => url('/categories'),
            'structured_data' => [
                '@context' => 'https://schema.org',
                '@type' => 'CollectionPage',
                'name' => 'Categories',
                'description' => $pageDescription,
                'url' => url('/categories'),
                'isPartOf' => [
                    '@type' => 'WebSite',
                    'name' => 'Skinbase',
                    'url' => url('/'),
                ],
            ],
        ]);
    }
}
