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

class Button extends Base {
    public static function render($label, array $opts = []): string {
        if (is_array($label)) {
            $opts = $label;
            $label = $opts['label'] ?? '';
        }
        $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
        $iconPosition = $opts['iconPosition'] ?? 'back'; // 'front'|'back'
        $fullWidth = $opts['fullWidth'] ?? false;
        $rounded = $opts['rounded'] ?? 'md';

        if (isset($opts['modal_close'])) {
            $extra['data-modal-close'] = ($opts['modal_close'] === true) ? 'true' : (string)$opts['modal_close'];
        }

        // Determine icon and label HTML early to adjust layout
        $iconHtml = (is_string($iconOpt) && $iconOpt !== '') ? $iconOpt : '';
        $labelEsc = self::h($label);
        $isIconOnly = ($labelEsc === '' && $iconHtml !== '');

        $roundedClass = $rounded === 'full' ? 'rounded-full' : 'rounded-' . $rounded;
        $base = "inline-flex items-center font-semibold text-center $roundedClass focus:ring-4";
        if ($fullWidth) {
            $base .= ' w-full justify-center';
        }

        if ($isIconOnly) {
            $sizeClass = [
                'xs' => 'p-1',
                'sm' => 'p-1.5',
                'md' => 'p-2',
                'lg' => 'p-2.5',
            ][$size] ?? 'p-2';
        } else {
            $sizeClass = [
                'xs' => 'text-xs px-2 py-1',
                'sm' => 'text-sm px-2 py-1.5',
                'md' => 'text-sm px-3 py-2',
                'lg' => 'text-sm px-3.5 py-2.5',
            ][$size] ?? 'text-sm px-3 py-2';
        }

        $iconSizeClass = [
            'xs' => '[&_svg]:size-3! [&>img]:size-3! [&_svg]:stroke-1.5!',
            'sm' => '[&_svg]:size-4! [&>img]:size-4! [&_svg]:stroke-1.5!',
            'md' => '[&_svg]:size-5! [&>img]:size-5!',
            'lg' => '[&_svg]:size-5! [&>img]:size-5!',
        ][$size] ?? '[&_svg]:size-5! [&>img]:size-5!';

        $gapClass = [
            'xs' => 'gap-x-1',
            'sm' => 'gap-x-1.5',
            'md' => 'gap-x-1.5',
            'lg' => 'gap-x-2',
        ][$size] ?? 'gap-x-1.5';

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

        $iconParentClasses = [];
        if ($iconHtml !== '') {
            $iconParentClasses[] = "$iconSizeClass [&_svg]:shrink-0 [&>img]:shrink-0";
            if ($labelEsc !== '') {
                $iconParentClasses[] = $gapClass;
                $iconFrontOffsetClass = [
                    'xs' => '[&_svg]:-ml-0.5 [&>img]:-ml-0.5',
                    'sm' => '[&_svg]:-ml-0.5 [&>img]:-ml-0.5',
                    'md' => '[&_svg]:-ml-1 [&>img]:-ml-1',
                    'lg' => '[&_svg]:-ml-1 [&>img]:-ml-1',
                ][$size] ?? '[&_svg]:-ml-0.5 [&>img]:-ml-0.5';

                $iconBackOffsetClass = [
                    'xs' => '[&_svg]:-mr-0.5 [&>img]:-mr-0.5',
                    'sm' => '[&_svg]:-mr-0.5 [&>img]:-mr-0.5',
                    'md' => '[&_svg]:-mr-1 [&>img]:-mr-1',
                    'lg' => '[&_svg]:-mr-1 [&>img]:-mr-1',
                ][$size] ?? '[&_svg]:-mr-0.5 [&>img]:-mr-0.5';

                if ($iconPosition === 'front') {
                    $iconParentClasses[] = $iconFrontOffsetClass;
                } else {
                    $iconParentClasses[] = $iconBackOffsetClass;
                }
            }
        }
        $iconClassStr = implode(' ', $iconParentClasses);

        // Build final classes
        $classes = trim("$base $sizeClass $variantClass $iconClassStr $extraClass");
        $attributes = array_merge(['class' => $classes], $extra);
        $attrStr = self::attrs($attributes);

        if ($iconHtml !== '') {
            $labelHtml = $labelEsc !== '' ? "<span>{$labelEsc}</span>" : '';
            $content = ($iconPosition === 'front') ? ($iconHtml . $labelHtml) : ($labelHtml . $iconHtml);
        } else {
            $content = $labelEsc;
        }

        if ($as === 'a') {
            $hrefEsc = self::h($href, false);
            $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;
    }
}
