<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

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

/**
 * Displays a numeric value as a horizontal progress bar (value / max), with an
 * optional label and threshold colouring.
 */
class ProgressBar implements ViewPlugin
{
    use PluginSupport;

    public static function id(): string { return 'ProgressBar'; }
    public static function label(): string { return 'Progress Bar'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'Shows a number as a progress bar with an optional percentage label and threshold colours.'; }

    public static function render(mixed $value, array $settings): string
    {
        if ($value === null || $value === '') return '';
        $max = (float) ($settings['max'] ?? 100);
        if ($max <= 0) $max = 100;
        $val = (float) $value;
        if ($val < 0) $val = 0.0;
        $pct = min(100.0, ($val / $max) * 100);
        $pctR = round($pct);

        // Threshold colour: <34 danger, <67 warning, else success (opt-in).
        $color = 'var(--pp-accent, #4f46e5)';
        if (in_array(strtolower((string) ($settings['thresholds'] ?? 'no')), ['1', 'yes', 'true', 'on'], true)) {
            $color = $pct < 34 ? 'var(--pp-danger, #dc2626)' : ($pct < 67 ? 'var(--pp-warning, #f59e0b)' : 'var(--pp-success, #16a34a)');
        }

        $label = '';
        if (!in_array(strtolower((string) ($settings['showLabel'] ?? 'yes')), ['0', 'no', 'false', 'off'], true)) {
            $label = '<span class="pp-progress-num">' . $pctR . '%</span>';
        }

        return '<span class="pp-progress-wrap" title="' . $pctR . '%">'
            . '<span class="pp-progress" role="progressbar" aria-valuenow="' . $pctR . '" aria-valuemin="0" aria-valuemax="100">'
            . '<span class="pp-progress-fill" style="width:' . round($pct, 1) . '%;background:' . $color . '"></span>'
            . '</span>' . $label . '</span>';
    }

    public static function settingsSchema(): array
    {
        return [
            ['key' => 'max',        'type' => 'number', 'label' => 'Max value (= 100%)', 'default' => 100],
            ['key' => 'showLabel',  'type' => 'bool',   'label' => 'Show % label', 'default' => 'yes'],
            ['key' => 'thresholds', 'type' => 'bool',   'label' => 'Colour by level', 'default' => 'no', 'hint' => 'Red < 34% · amber < 67% · green above.'],
        ];
    }

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