<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

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

/**
 * Displays a separator-joined value (from the Tags edit control, or any delimited
 * column) as read-only pills. Pair with "Tags / Multi-select".
 */
class Tags implements ViewPlugin
{
    use PluginSupport;

    public static function id(): string { return 'Tags'; }
    public static function label(): string { return 'Tags'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'Displays delimited values as read-only pills.'; }

    public static function render(mixed $value, array $settings): string
    {
        $raw = (string) ($value ?? '');
        if (trim($raw) === '') return '';
        $sep = (string) ($settings['separator'] ?? ',');
        $sep = $sep === '' ? ',' : substr($sep, 0, 1);

        $tags = array_values(array_filter(array_map('trim', explode($sep, $raw)), fn ($t) => $t !== ''));
        if ($tags === []) return '';

        $max = (int) ($settings['max'] ?? 0);
        $extra = 0;
        if ($max > 0 && count($tags) > $max) { $extra = count($tags) - $max; $tags = array_slice($tags, 0, $max); }

        $out = '<span class="pp-tagv-wrap">';
        foreach ($tags as $t) $out .= '<span class="pp-tagv">' . self::e($t) . '</span>';
        if ($extra > 0) $out .= '<span class="pp-tagv pp-tagv-more">+' . $extra . '</span>';
        return $out . '</span>';
    }

    public static function settingsSchema(): array
    {
        return [
            ['key' => 'separator', 'type' => 'text',   'label' => 'Separator', 'default' => ',', 'hint' => 'Character the stored values are joined by.'],
            ['key' => 'max',       'type' => 'number', 'label' => 'Max pills shown', 'default' => 0, 'hint' => '0 = show all; extra collapse into a +N pill.'],
        ];
    }

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