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

/**
 * ButtonGroup
 * Renders a segmented button group based on the provided Tailwind snippet.
 *
 * Usage:
 * echo \Components\ButtonGroup::render([
 *   [
 *     'label' => 'Years',
 *     'active' => false,
 *     'as' => 'button', // 'button' | 'a'
 *     'href' => null,    // for 'a'
 *     'type' => 'button',// for 'button'
 *     'attrs' => [ 'hx-get' => '/path', 'hx-target' => '#id' ],
 *   ],
 *   ...
 * ], [
 *   'size' => 'sm', // sm|md|lg
 *   'class' => '',  // extra classes for wrapper
 *   'activeClass' => 'bg-gray-100 text-gray-900',
 *   'ariaLabel' => null, // optional aria-label for the group
 * ]);
 */
class ButtonGroup extends Base
{
    public static function render(array $items, array $opts = []): string
    {
        if (empty($items)) {
            return '';
        }

        $size = $opts['size'] ?? 'sm';
        $wrapperExtra = trim((string)($opts['class'] ?? ''));
        $activeClass = trim((string)($opts['activeClass'] ?? 'bg-gray-100 text-gray-900'));
        $ariaLabel = isset($opts['ariaLabel']) ? (string)$opts['ariaLabel'] : null;

        $wrapperBase = 'isolate inline-flex rounded-md shadow-xs dark:shadow-none';
        $wrapperClass = trim($wrapperBase . ($wrapperExtra ? (' ' . $wrapperExtra) : ''));

        // Size mapping similar to snippet (defaults to text-sm px-3 py-2)
        $sizeMap = [
            'sm' => 'px-3 py-2 text-sm',
            'md' => 'px-3.5 py-2.5 text-sm',
            'lg' => 'px-4 py-2.5 text-base',
        ];
        $sizeClass = $sizeMap[$size] ?? $sizeMap['sm'];

        $buttonBase = 'relative inline-flex items-center bg-white font-semibold text-gray-900 '
                    . $sizeClass
                    . ' inset-ring-1 inset-ring-gray-300 hover:bg-gray-50 focus:z-10 '
                    . 'dark:bg-white/10 dark:text-white dark:inset-ring-gray-700 dark:hover:bg-white/20';

        $htmlButtons = [];
        $count = count($items);
        foreach ($items as $idx => $item) {
            $label = $item['label'] ?? '';
            $as    = $item['as'] ?? 'button';
            $href  = $item['href'] ?? '#';
            $type  = strtolower((string)($item['type'] ?? 'button'));
            $attrs = $item['attrs'] ?? [];
            $extraClass = trim((string)($item['class'] ?? ''));
            $active = (bool)($item['active'] ?? false);
            $html  = $item['html'] ?? null;

            // Position-specific classes
            $posClass = '';
            if ($idx === 0) {
                $posClass = 'rounded-l-md';
            } elseif ($idx === $count - 1) {
                $posClass = 'rounded-r-md -ml-px';
            } else {
                $posClass = '-ml-px';
            }

            $classes = trim($buttonBase . ' ' . $posClass . ($extraClass ? (' ' . $extraClass) : '') . ($active ? (' ' . $activeClass) : ''));

            // Accessibility
            $attrs['aria-pressed'] = $active ? 'true' : 'false';

            // Merge class in attributes after computing
            $attrs = array_merge(['class' => $classes], $attrs);

            $content = ($html !== null) ? (string)$html : self::h($label);
            if ($as === 'a') {
                $hrefEsc = self::h($href);
                $attrStr = self::attrs($attrs);
                $htmlButtons[] = <<<HTML
<a href="{$hrefEsc}" {$attrStr}>{$content}</a>
HTML;
            } else {
                if (!in_array($type, ['button', 'submit', 'reset'], true)) { $type = 'button'; }
                $attrs['type'] = $type;
                $attrStr = self::attrs($attrs);
                $htmlButtons[] = <<<HTML
<button {$attrStr}>{$content}</button>
HTML;
            }
        }

        $roleAttrs = ['class' => $wrapperClass, 'role' => 'group'];
        if ($ariaLabel !== null && $ariaLabel !== '') {
            $roleAttrs['aria-label'] = $ariaLabel;
        }

        $buttonsHtml = implode("\n", $htmlButtons);
        $spanAttrs = self::attrs($roleAttrs);
        return <<<HTML
<span {$spanAttrs}>
{$buttonsHtml}
</span>
HTML;
    }
}
