<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

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

/**
 * Read-only star display for a numeric rating (the display half of the Star
 * Rating edit control). Supports fractional values via a clipped overlay, an
 * optional numeric label, and theme tokens.
 */
class StarRatingView implements ViewPlugin
{
    use PluginSupport;

    // NOTE: class is StarRatingView (not StarRating) to avoid colliding with the
    // Edit/StarRating class in the shared PpPhp\Plugins namespace; the registry
    // resolves it via its declared class name. The control id stays "StarRating".
    public static function id(): string { return 'StarRating'; }
    public static function label(): string { return 'Star Rating'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'Displays a numeric rating as filled stars (supports fractions) with an optional value label.'; }

    public static function render(mixed $value, array $settings): string
    {
        if ($value === null || $value === '') return '';
        $max = (int) ($settings['max'] ?? 5);
        $max = max(1, min(10, $max));
        $val = (float) $value;
        if ($val < 0) $val = 0.0;
        if ($val > $max) $val = (float) $max;

        $pct = $max > 0 ? ($val / $max) * 100 : 0;
        $pct = round($pct, 2);
        $size = (string) ($settings['size'] ?? 'md');
        if (!in_array($size, ['sm', 'md', 'lg'], true)) $size = 'md';
        $stars = str_repeat("\u{2605}", $max);   // ★ × max

        $label = '';
        if (in_array(strtolower((string) ($settings['showValue'] ?? 'no')), ['1', 'yes', 'true', 'on'], true)) {
            $num = rtrim(rtrim(number_format($val, 1), '0'), '.');
            $label = '<span class="pp-starsv-num">' . self::e($num) . '/' . $max . '</span>';
        }

        return '<span class="pp-starsv is-' . $size . '" title="' . self::e(rtrim(rtrim(number_format($val, 1), '0'), '.') . ' / ' . $max) . '"'
            . ' role="img" aria-label="Rated ' . self::e((string) $val) . ' out of ' . $max . '">'
            . '<span class="pp-starsv-track">' . $stars . '</span>'
            . '<span class="pp-starsv-fill" style="width:' . $pct . '%">' . $stars . '</span>'
            . '</span>' . $label;
    }

    public static function settingsSchema(): array
    {
        return [
            ['key' => 'max',       'type' => 'number', 'label' => 'Number of stars', 'default' => 5, 'hint' => '1–10.'],
            ['key' => 'size',      'type' => 'select', 'label' => 'Size', 'options' => ['sm', 'md', 'lg'], 'default' => 'md'],
            ['key' => 'showValue', 'type' => 'bool',   'label' => 'Show value (e.g. 3.5/5)', 'default' => 'no'],
        ];
    }

    public static function assets(): array
    {
        return ['js' => [], 'css' => ['plugins/View/StarRating/star-rating-view.css']];
    }
}
