<?php
// components/Button.php
namespace Components;

class Button extends Base {
    public static function render(string $label, array $opts = []): string {
        $variant = $opts['variant'] ?? 'primary';
        $size    = $opts['size'] ?? 'sm';
        $as      = $opts['as'] ?? 'button'; // 'button'|'a'
        $href    = $opts['href'] ?? '#';
        $extra   = $opts['attrs'] ?? [];
        $extraClass = trim($opts['class'] ?? '');
        $type    = strtolower((string)($opts['type'] ?? 'button')); // for <button> only: 'button'|'submit'|'reset'
        $iconOpt = $opts['icon'] ?? null; // default: no icon

        $base = 'inline-flex items-center font-medium text-center rounded-lg focus:ring-4';
        $sizeClass = [
            'sm' => 'text-sm px-3 py-2',
            'md' => 'text-sm px-4 py-2.5',
            'lg' => 'text-base px-5 py-3',
        ][$size] ?? 'text-sm px-3 py-2';

        switch ($variant) {
            case 'secondary': $variantClass = 'text-gray-900 bg-gray-100 hover:bg-gray-200 focus:ring-gray-300'; break;
            case 'danger':    $variantClass = 'text-white bg-red-600 hover:bg-red-700 focus:ring-red-300'; break;
            case 'ghost':     $variantClass = 'text-gray-700 bg-transparent hover:bg-gray-100 focus:ring-transparent'; break;
            case 'primary':
            default:          $variantClass = 'text-white bg-brand hover:bg-brand-800 focus:ring-brand-300';
        }

        // Determine icon HTML (default: none). If true or 'arrow' -> default arrow svg; if string -> enforce size-5.
        $iconHtml = '';
        if (is_string($iconOpt) && $iconOpt !== '') {
            $iconHtml = $iconOpt; // assume safe/intentional HTML
            // Try to enforce size-5 on common icon elements
            if (stripos($iconHtml, '<svg') !== false) {
                if (preg_match('/<svg[^>]*\\bclass\\s*=\\s*([\"\'])(.*?)\\1/i', $iconHtml, $m)) {
                    if (strpos($m[2], 'size-5') === false) {
                        $iconHtml = preg_replace('/(<svg[^>]*\\bclass\\s*=\\s*)([\"\'])(.*?)(\\2)/i', '$1$2$3 size-5! $4', $iconHtml, 1);
                    }
                } else {
                    $iconHtml = preg_replace('/<svg\\b/i', '<svg class="size-5"', $iconHtml, 1);
                }
            } elseif (stripos($iconHtml, '<img') !== false) {
                if (preg_match('/<img[^>]*\\bclass\\s*=\\s*([\"\'])(.*?)\\1/i', $iconHtml, $m)) {
                    if (strpos($m[2], 'size-5') === false) {
                        $iconHtml = preg_replace('/(<img[^>]*\\bclass\\s*=\\s*)([\"\'])(.*?)(\\2)/i', '$1$2$3 size-5! $4', $iconHtml, 1);
                    }
                } else {
                    $iconHtml = preg_replace('/<img\\b/i', '<img class="size-5"', $iconHtml, 1);
                }
            } else {
                // Fallback: wrap in a span with enforced size
                $iconHtml = '<span class="size-5!">' . $iconHtml . '</span>';
            }
        }

        $labelEsc = self::h($label);
        // Build classes (add horizontal space if icon present)
        $classes = trim("$base $sizeClass $variantClass" . (($iconHtml !== '' && $labelEsc !== '') ? ' gap-2' : '') . " $extraClass");
        $attributes = array_merge(['class' => $classes], $extra);
        $attrStr = self::attrs($attributes);

        $content = $iconHtml !== '' ? "<span>$labelEsc</span>" . $iconHtml : $labelEsc;

        if ($as === 'a') {
            $hrefEsc = self::h($href);
            $html = <<<HTML
<a href=\"$hrefEsc\" $attrStr>$content</a>
HTML;
            return $html;
        }

        // Sanitize button type
        if (!in_array($type, ['button', 'submit', 'reset'], true)) {
            $type = 'button';
        }

        $html = <<<HTML
<button type="$type" $attrStr>$content</button>
HTML;
        return $html;
    }
}
