<?php

use Botble\Shortcode\Compilers\Shortcode as ShortcodeCompiler;
use Botble\Shortcode\Facades\Shortcode;
use Botble\Theme\Facades\Theme;

app()->booted(function () {
    if (! is_plugin_active('blog')) {
        return;
    }

    Shortcode::register('news', __('News'), __('News'), function (ShortcodeCompiler $shortcode): string|null {
        $limit = (int) $shortcode->limit ?: 4;

        $posts = match ($shortcode->type) {
            'popular' => get_popular_posts($limit),
            'featured' => get_featured_posts($limit),
            'recent' => get_recent_posts($limit),
            default => get_latest_posts($limit),
        };

        if ($posts->isEmpty()) {
            return null;
        }

        return Theme::partial('shortcodes.news.index', compact('shortcode', 'posts'));
    });

    Shortcode::setAdminConfig('news', function (array $attributes): string|null {
        $types = [
            'latest' => __('Latest'),
            'popular' => __('Popular'),
            'featured' => __('Featured'),
            'recent' => __('Recent'),
        ];

        return Theme::partial('shortcodes.news.admin', compact('attributes', 'types'));
    });
});
