<?php
// components/Form/TabsGroup.php
namespace Components\Form;

use Components\Ui\TabsGroup as UiTabsGroup;

/**
 * TabsGroup
 * Renders a segmented control (tabs) as a form field.
 * Integrates with Alpine.js form state.
 */
class TabsGroup extends RadioBase
{
    /**
     * Render the component as a form field.
     *
     * @param string $name
     * @param string $label
     * @param array $options
     * @param mixed $value
     * @param array $opts
     * @return string
     */
    public static function render(string $name, string $label, array $options, $value = '', array $opts = []): string
    {
        $ctx = self::buildRadioFieldContext($name, $label, $opts);

        $nameEsc = $ctx['name_esc'];
        $labelEsc = $ctx['label_esc'];
        $helpHtml = $ctx['help_html'];
        $errorHtml = $ctx['error_html'];
        $clientErr = $ctx['client_err_html'];
        $badge = $ctx['badge_html'];
        
        // input_attrs contains Alpine.js bindings: x-model="form['name']" etc.
        $inputAttrs = $opts['input_attrs'] ?? '';

        $items = self::normalizeOptions($options, $value);
        $tabItems = [];
        
        // Use the same Alpine.js variable as defined in Engine.php renderField
        $xModelVar = "form['" . addslashes($name) . "']";

        foreach ($items as $item) {
            $val = $item['value'];
            $valJs = json_encode((string)$val, JSON_UNESCAPED_UNICODE);
            
            $tabItems[] = [
                'label' => $item['label'],
                'click' => "{$xModelVar} = {$valJs}; validateField('" . addslashes($name) . "')",
                'active' => "{$xModelVar} === {$valJs}",
                'attrs' => [
                    'disabled' => $item['disabled'] ? 'disabled' : null,
                ]
            ];
        }

        $fullWidth = $opts['fullWidth'] ?? true;
        $tabsHtml = UiTabsGroup::render($tabItems, [
            'fullWidth' => $fullWidth,
            'model' => $xModelVar
        ]);
        
        $layout = (string)($opts['layout'] ?? 'stacked');
        $isHorizontal = self::isHorizontalLayout($layout);

        $explainerHtml = '';
        foreach ($items as $item) {
            if ($item['description'] !== '') {
                $valJs = json_encode((string)$item['value'], JSON_UNESCAPED_UNICODE);
                $descEsc = self::h($item['description']);
                $showExpr = htmlspecialchars("{$xModelVar} === {$valJs}", ENT_QUOTES);
                $explainerHtml .= <<<HTML
<div x-show="{$showExpr}" class="mt-2 text-sm text-gray-500 dark:text-gray-400">
    {$descEsc}
</div>
HTML;
            }
        }

        $innerHtml = <<<HTML
<input type="hidden" name="{$nameEsc}" {$inputAttrs} />
{$tabsHtml}
{$explainerHtml}
HTML;

        if (!$isHorizontal) {
            $containerClass = $ctx['container_class'];
            if ($layout === 'short') {
                $containerClass .= ' w-full md:w-1/2';
            }
            return <<<HTML
<fieldset class="{$containerClass} form-field {$ctx['group_error_class']}">
  <legend class="mb-1 block text-sm font-medium text-primary">{$labelEsc} {$badge}</legend>
  {$helpHtml}
  <div class="mt-2">
    {$innerHtml}
  </div>
  {$errorHtml}
  {$clientErr}
</fieldset>
HTML;
        }

        $labelHtml = self::renderLabel('', $label, $badge, $opts);
        return self::renderContainer($labelHtml, $innerHtml, $helpHtml, $errorHtml, $clientErr, $opts);
    }
}
