<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

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

class Hyperlink implements ViewPlugin
{
    use PluginSupport;

    public static function id(): string { return 'Hyperlink'; }
    public static function label(): string { return 'Hyperlink'; }
    public static function version(): string { return '1.1.0'; }
    public static function description(): string { return 'Renders a field value as a clickable link, with scheme validation (blocks javascript:/data:) and safe rel/target.'; }

    public static function render(mixed $value, array $settings): string
    {
        $raw = trim((string) ($value ?? ''));
        if ($raw === '') return '';

        $label = (string) ($settings['text'] ?? '');
        $text  = self::e($label !== '' ? $label : $raw);

        // Reject javascript:/data:/vbscript: and obfuscated schemes. An unsafe URL
        // degrades to plain text instead of a live (XSS-capable) link.
        $href = self::safeUrl($raw);
        if ($href === '') return $text;

        $target = (string) ($settings['target'] ?? '_blank');
        if (!in_array($target, ['_blank', '_self'], true)) $target = '_blank';
        // rel=noopener noreferrer closes the reverse-tabnabbing hole on _blank.
        $rel = $target === '_blank' ? ' rel="noopener noreferrer"' : '';

        return '<a href="' . $href . '" target="' . $target . '"' . $rel . '>' . $text . '</a>';
    }

    public static function settingsSchema(): array
    {
        return [
            ['key' => 'target', 'type' => 'select', 'label' => 'Open in', 'options' => ['_blank', '_self'], 'default' => '_blank', 'hint' => '_blank opens a new tab.'],
            ['key' => 'text',   'type' => 'text',   'label' => 'Link text', 'default' => '', 'hint' => 'Optional fixed label; defaults to the URL.'],
        ];
    }

    public static function assets(): array { return ['js' => [], 'css' => []]; }
}
