<?php

declare(strict_types=1);

class FrontTagController
{
    public static function routes(): void
    {
        Router::get('/tags', [self::class, 'index']);
        Router::get('/tag/{slug}', [self::class, 'show']);
    }

    public static function index(): void
    {
        $videoType = Video::activeType();
        $groupedTags = LocalizedTags::dedupeGroups(Tag::allGroupedByLetter($videoType));
        $totalTags = Tag::count('', $videoType);

        $prefix = ltrim(Router::langPrefix() . Router::typePrefix(), '/');
        $canonicalPath = $prefix !== '' ? $prefix . '/tags' : 'tags';
        $canonicalUrl = SEO::canonical($canonicalPath);
        $alternates = self::buildListAlternates('tags');
        Router::setAlternates($alternates);

        ThemeRenderer::render('tags', [
            'pageTitle'   => SEO::title(__('page_title_tags')),
            'metaDescription' => __('page_title_tags'),
            'canonicalUrl' => $canonicalUrl,
            'alternates' => $alternates,
            'groupedTags' => $groupedTags,
            'totalTags'   => $totalTags,
        ]);
    }

    public static function show(): void
    {
        $tag = Tag::findBySlug(Router::param('slug'));
        if (!$tag) { http_response_code(404); ThemeRenderer::render('404'); return; }
        Router::enforceCanonicalType($tag['video_type'], 'tag', $tag['slug']);
        Router::enforceCanonicalSlug('tag', $tag['slug']);

        $sort = $_GET['sort'] ?? HookSystem::applyFilter('front.default_sort', Setting::get('default_sort', 'newest'), 'tag');
        $perPage = (int) Setting::get('videos_per_page', 24);
        $filters = ['tag_id' => $tag['id'], 'status' => 'published', 'sort' => $sort];
        $total = Video::count($filters);
        $pagination = Pagination::fromRequest($total, $perPage);

        $prefix = ltrim(Router::langPrefix() . Router::typePrefix(), '/');
        $canonicalPath = $prefix !== '' ? $prefix . '/tag/' . $tag['slug'] : 'tag/' . $tag['slug'];
        $canonicalUrl = SEO::canonical($canonicalPath);
        $alternates = self::buildAlternates((int) $tag['id']);
        Router::setAlternates($alternates);

         
        $siteUrl = SEO::siteUrl();
        $tagListPath = $prefix !== '' ? $prefix . '/tags' : 'tags';
        $breadcrumbJsonLd = SEO::breadcrumbJsonLd([
            ['name' => Setting::get('site_name', 'TubePress'), 'url' => $siteUrl . '/'],
            ['name' => __('page_title_tags'), 'url' => $siteUrl . '/' . $tagListPath],
            ['name' => $tag['name'], 'url' => html_entity_decode($canonicalUrl)],
        ]);

        ThemeRenderer::render('tag', [
            'pageTitle' => SEO::title($tag['name']),
            'metaDescription' => $tag['name'],
            'canonicalUrl' => $canonicalUrl,
            'alternates' => $alternates,
            'ogTags' => [
                'og:title' => $tag['name'],
                'og:description' => $tag['name'],
                'og:url' => $canonicalUrl,
            ],
            'twitterCard' => [
                'twitter:title' => $tag['name'],
                'twitter:description' => $tag['name'],
            ],
            'jsonLd' => $breadcrumbJsonLd,
            'tag' => $tag,
            'videos' => Video::all($filters, $perPage, $pagination->offset),
            'pagination' => $pagination,
            'sort' => $sort,
        ]);
    }

    private static function buildAlternates(int $tagId): array
    {
        $base = Database::fetchOne('SELECT slug, video_type FROM tags WHERE id = ?', [$tagId]);
        if (!$base) return [];

        $siteUrl = SEO::siteUrl();
        $defaultLang = Translator::getDefaultCode();
        $typePrefix = Router::typePrefixFor($base['video_type']);
        $translations = Tag::translations($tagId);
        $alternates = [];

        $alternates[$defaultLang] = $siteUrl . $typePrefix . '/tag/' . $base['slug'];
        foreach (Translator::available() as $lang) {
            if ($lang['code'] === $defaultLang) continue;
            $slug = $translations[$lang['code']]['slug'] ?? $base['slug'];
            $alternates[$lang['code']] = $siteUrl . '/' . $lang['code'] . $typePrefix . '/tag/' . $slug;
        }
        $alternates['x-default'] = $alternates[$defaultLang];
        return $alternates;
    }

    private static function buildListAlternates(string $route): array
    {
        $siteUrl = SEO::siteUrl();
        $defaultLang = Translator::getDefaultCode();
        $typePrefix = Router::typePrefix();
        $alternates = [];

        $alternates[$defaultLang] = $siteUrl . $typePrefix . '/' . $route;
        foreach (Translator::available() as $lang) {
            if ($lang['code'] === $defaultLang) continue;
            $alternates[$lang['code']] = $siteUrl . '/' . $lang['code'] . $typePrefix . '/' . $route;
        }
        $alternates['x-default'] = $alternates[$defaultLang];
        return $alternates;
    }
}
