<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

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

/**
 * Displays a boolean value as an icon (✓/✗), Yes/No text, or a coloured badge.
 * Truthy = 1, true, "yes", "true", "on", "y" (case-insensitive); everything else
 * is false. A null/empty value can optionally show as a neutral dash.
 */
class Boolean implements ViewPlugin
{
    use PluginSupport;

    public static function id(): string { return 'Boolean'; }
    public static function label(): string { return 'Yes / No'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'Shows a boolean as a check/cross icon, Yes/No text, or a coloured badge.'; }

    public static function render(mixed $value, array $settings): string
    {
        $blank = $value === null || $value === '';
        if ($blank && !in_array(strtolower((string) ($settings['blankAsFalse'] ?? 'no')), ['1', 'yes', 'true', 'on'], true)) {
            return '<span class="pp-bool is-blank" title="Not set">&mdash;</span>';
        }
        $true = in_array(strtolower(trim((string) ($value ?? ''))), ['1', 'true', 'yes', 'on', 'y'], true);

        $style = (string) ($settings['style'] ?? 'icon');
        if (!in_array($style, ['icon', 'text', 'badge'], true)) $style = 'icon';
        $tLabel = self::e(($settings['trueLabel'] ?? '') !== '' ? $settings['trueLabel'] : 'Yes');
        $fLabel = self::e(($settings['falseLabel'] ?? '') !== '' ? $settings['falseLabel'] : 'No');
        $cls = $true ? 'is-true' : 'is-false';

        if ($style === 'icon') {
            $glyph = $true ? '&#10003;' : '&#10007;';   // ✓ / ✗
            $lbl = $true ? $tLabel : $fLabel;
            return '<span class="pp-bool ' . $cls . '" role="img" aria-label="' . $lbl . '">' . $glyph . '</span>';
        }
        if ($style === 'badge') {
            return '<span class="pp-bool-badge ' . $cls . '">' . ($true ? $tLabel : $fLabel) . '</span>';
        }
        return '<span class="pp-bool ' . $cls . '">' . ($true ? $tLabel : $fLabel) . '</span>';
    }

    public static function settingsSchema(): array
    {
        return [
            ['key' => 'style',        'type' => 'select', 'label' => 'Display as', 'options' => ['icon', 'text', 'badge'], 'default' => 'icon'],
            ['key' => 'trueLabel',    'type' => 'text',   'label' => 'True label', 'default' => 'Yes'],
            ['key' => 'falseLabel',   'type' => 'text',   'label' => 'False label', 'default' => 'No'],
            ['key' => 'blankAsFalse', 'type' => 'bool',   'label' => 'Treat empty as false', 'default' => 'no', 'hint' => 'Off shows a dash for unset values.'],
        ];
    }

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