<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

use PpPhp\Core\PluginSupport;
use PpPhp\Core\ViewPlugin;

/**
 * Pretty-prints a JSON value in a scrollable code block. Invalid JSON is shown
 * as escaped plain text.
 */
class Json implements ViewPlugin
{
    use PluginSupport;

    public static function id(): string { return 'Json'; }
    public static function label(): string { return 'JSON'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'Shows a JSON value pretty-printed in a code block (invalid JSON shown as text).'; }

    public static function render(mixed $value, array $settings): string
    {
        $raw = (string) ($value ?? '');
        if (trim($raw) === '') return '';

        $decoded = json_decode($raw, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return '<code class="pp-json is-invalid">' . self::e($raw) . '</code>';
        }
        $pretty = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        if ($pretty === false) return '<code class="pp-json is-invalid">' . self::e($raw) . '</code>';

        $rows = max(2, (int) ($settings['maxRows'] ?? 12));
        $style = ' style="max-height:' . ($rows * 1.35) . 'rem"';
        return '<pre class="pp-json"' . $style . '>' . self::e($pretty) . '</pre>';
    }

    public static function settingsSchema(): array
    {
        return [
            ['key' => 'maxRows', 'type' => 'number', 'label' => 'Max visible rows', 'default' => 12, 'hint' => 'Taller content scrolls.'],
        ];
    }

    public static function assets(): array
    {
        return ['js' => [], 'css' => ['plugins/View/Json/json.css']];
    }
}
