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

class RadioCards extends BaseField {
    /**
     * Render a radio-card group similar to Tailwind UI example
     * $options: array where key is value and item is:
     *   - string label
     *   - or array{label: string, description?: string, meta?: string, aria_label?: string, aria_description?: string}
     */
    public static function render(string $name, string $label, array $options, $value = '', array $opts = []): string {
        $validate = $opts['validate'] ?? [];
        $errors = $opts['errors'] ?? [];
        $help = $opts['help'] ?? '';
        $extra = $opts['input_attrs'] ?? '';
        $badge = $opts['label_badge_html'] ?? '';

        $hasError = !empty($errors);
        $nameEsc = self::h($name);
        $labelEsc = self::h($label);
        $helpHtml = self::helpHtml($help);
        $errorHtml = self::errorsHtml($errors);
        $clientErr = <<<HTML
<p class="mt-1 text-sm text-red-600" x-show="clientErrors && clientErrors['{$nameEsc}'] && clientErrors['{$nameEsc}'].length" x-text="(clientErrors && clientErrors['{$nameEsc}'] && clientErrors['{$nameEsc}'].length) ? clientErrors['{$nameEsc}'][0] : ''"></p>
HTML;

        $requiredAttr = !empty($validate['required']) ? ' required' : '';
        $groupErrorClass = $hasError ? ' ring-1 ring-red-500/50 rounded-md p-1' : '';

        // Build cards
        $cards = '';
        $current = (string)$value;
        foreach ($options as $val => $opt) {
            $valStr = (string)$val;
            $isArray = is_array($opt);
            $optLabel = $isArray ? (string)($opt['label'] ?? $valStr) : (string)$opt;
            $optDesc = $isArray ? (string)($opt['description'] ?? '') : '';
            $optMeta = $isArray ? (string)($opt['meta'] ?? '') : '';
            $ariaLabel = $isArray ? (string)($opt['aria_label'] ?? $optLabel) : $optLabel;
            $ariaDesc = $isArray ? (string)($opt['aria_description'] ?? $optDesc) : $optDesc;

            // If options are provided as a simple list like ['all','shop']
            // the array keys will be 0,1,... by default. In that case we want
            // the radio value to be the option string itself (e.g. 'all')
            // instead of the numeric key. Only apply this when the option is
            // a scalar string and the key is a numeric index.
            if (!$isArray && (is_int($val) || (is_string($val) && ctype_digit($val)))) {
                $valStr = (string)$optLabel;
            }

            $checked = $current !== '' && (string)$current === $valStr;

            $valEsc = self::h($valStr);
            $optLabelEsc = self::h($optLabel);
            $optDescEsc = self::h($optDesc);
            $optMetaEsc = self::h($optMeta);
            $ariaLabelEsc = self::h($ariaLabel);
            $ariaDescEsc = self::h($ariaDesc);
            $checkedAttr = $checked ? ' checked' : '';

            // Each card is a label containing the input and the content
            $cards .= <<<HTML
<label aria-label="{$ariaLabelEsc}" aria-description="{$ariaDescEsc}" class="group relative flex rounded-lg border border-gray-300 bg-white has-checked:bg-brand/5 p-4 has-checked:outline-2 has-checked:-outline-offset-2 has-checked:outline-brand has-focus-visible:outline-3 has-focus-visible:-outline-offset-1 has-disabled:border-gray-400 has-disabled:bg-gray-200 has-disabled:opacity-25 dark:border-white/10 dark:bg-gray-800/50 dark:has-checked:bg-brand/10 dark:has-checked:outline-brand dark:has-disabled:border-white/10 dark:has-disabled:bg-gray-800">
  <input type="radio" name="{$nameEsc}" value="{$valEsc}" class="absolute inset-0 appearance-none focus:outline-none"{$checkedAttr}{$requiredAttr} {$extra} />
  <div class="flex-1">
    <span class="block text-sm font-medium text-gray-900 dark:text-white">{$optLabelEsc}</span>
    <!-- description -->
    <span class="mt-1 block text-sm text-gray-500 dark:text-gray-400">{$optDescEsc}</span>
    <!-- meta (optional) -->
    <span class="mt-6 block text-sm font-medium text-gray-900 dark:text-white">{$optMetaEsc}</span>
  </div>
  <svg viewBox="0 0 20 20" fill="currentColor" data-slot="icon" aria-hidden="true" class="invisible size-5 text-brand group-has-checked:visible dark:text-brand">
    <path d="M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm3.857-9.809a.75.75 0 0 0-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 1 0-1.06 1.061l2.5 2.5a.75.75 0 0 0 1.137-.089l4-5.5Z" clip-rule="evenodd" fill-rule="evenodd" />
  </svg>
</label>
HTML;
        }

        // Wrap in fieldset with legend and grid
        return <<<HTML
<fieldset class="{$groupErrorClass}">
  <legend class="text-sm/6 font-semibold text-gray-900 dark:text-white">{$labelEsc}{$badge}</legend>
  <div class="mt-2 grid grid-cols-1 gap-y-3 sm:grid-cols-3 sm:gap-x-4">
    {$cards}
  </div>
  {$helpHtml}
  {$errorHtml}
  {$clientErr}
</fieldset>
HTML;
    }
}
