<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

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

/**
 * Displays a colour value as a swatch + hex label. Only strict hex colours are
 * put into inline CSS (preventing style injection); anything else shows as text.
 */
class Color implements ViewPlugin
{
    use PluginSupport;

    public static function id(): string { return 'Color'; }
    public static function label(): string { return 'Colour Swatch'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'Shows a hex colour as a swatch with its value.'; }

    public static function render(mixed $value, array $settings): string
    {
        $hex = trim((string) ($value ?? ''));
        if ($hex === '') return '';
        // Only a strict hex may reach the inline style attribute.
        if (!preg_match('/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/', $hex)) {
            return self::e($hex);
        }
        $showHex = !in_array(strtolower((string) ($settings['showHex'] ?? 'yes')), ['0', 'no', 'false', 'off'], true);
        return '<span class="pp-colorv">'
            . '<span class="pp-colorv-sw" style="background:' . $hex . '"></span>'
            . ($showHex ? '<code>' . self::e($hex) . '</code>' : '')
            . '</span>';
    }

    public static function settingsSchema(): array
    {
        return [['key' => 'showHex', 'type' => 'bool', 'label' => 'Show hex value', 'default' => 'yes']];
    }

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