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

use Components\Support\Palette;

class ColorChoice extends BaseField
{
    /**
     * Render a flex grid of color badges using Palette tokens.
     * Highlights the currently selected color. Posts the palette token value.
     *
     * Options (in $opts):
     * - help: string help text
     * - errors: array of error strings
     * - include_empty: bool add an empty option (default false)
     * - empty_label: string label for the empty option (default "Default")
     * - empty_value: string value for the empty option (default "")
     * - tokens: array of token strings to restrict the palette (default: all tokens from Palette::map)
     * - label_badge_html: string extra html to display next to label
     */
    public static function render(string $name, string $label, $value = '', array $opts = []): string
    {
        $errors = $opts['errors'] ?? [];
        $help = $opts['help'] ?? '';
        $extra = $opts['input_attrs'] ?? '';
        $includeEmpty = (bool)($opts['include_empty'] ?? false);
        $emptyLabel = (string)($opts['empty_label'] ?? 'Default');
        $emptyValue = array_key_exists('empty_value', $opts) ? (string)$opts['empty_value'] : '';
        $tokens = is_array($opts['tokens'] ?? null) ? $opts['tokens'] : array_keys(Palette::map());

        $nameEsc = self::h($name);
        $labelEsc = self::h($label);
        $badge = $opts['label_badge_html'] ?? '';
        $helpHtml = self::helpHtml($help);
        $errorHtml = self::errorsHtml($errors);
        $hasError = !empty($errors);
        $groupErrorClass = $hasError ? ' ring-1 ring-red-500/50 rounded-md p-1' : '';
        $validate = $opts['validate'] ?? [];
        $requiredAttr = (!empty($validate['required'])) ? ' required' : '';

        // Build normalized options list
        $options = [];
        if ($includeEmpty) {
            $options[] = ['value' => (string)$emptyValue, 'label' => (string)$emptyLabel, 'dot' => 'bg-gray-300'];
        }
        foreach ($tokens as $tok) {
            $tok = trim((string)$tok);
            if ($tok === '') { continue; }
            $dot = Palette::dotBg($tok, 'gray');
            $labelText = ucfirst($tok);
            $options[] = [
                'value' => $tok,
                'label' => $labelText,
                'dot' => $dot,
            ];
        }

        $current = (string)$value;
        $itemsHtml = '';
        foreach ($options as $opt) {
            $v = self::h((string)$opt['value']);
            $t = self::h((string)$opt['label']);
            $checked = ($current !== '' && (string)$opt['value'] === $current) || ($current === '' && (string)$opt['value'] === $emptyValue);
            $checkedAttr = $checked ? ' checked' : '';
            // Badge visuals: circular color swatch with highlight when selected
            $dotCls = (string)$opt['dot'];
            $itemsHtml .= <<<HTML
<label class="group relative flex cursor-pointer items-center gap-1 rounded-md border border-transparent px-2 py-2 has-checked:outline-2 has-checked:-outline-offset-2 has-checked:outline-brand focus-within:ring-2 focus-within:ring-brand">
  <input type="radio" name="{$nameEsc}" value="{$v}" class="absolute inset-0 appearance-none focus:outline-none"{$checkedAttr}{$requiredAttr} {$extra} />
  <div class="inline-block size-5  rounded-full ring-1 ring-black/5  {$dotCls}"></div>
  <span class="text-xs text-secondary ">{$t}</span>
<!--  <svg viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" class="invisible ml-auto size-5 text-brand group-has-checked:visible">-->
<!--    <path d="M16.704 4.153a.75.75 0 0 1 .143 1.052l-8 10.5a.75.75 0 0 1-1.127.075l-4.5-4.5a.75.75 0 0 1 1.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 0 1 1.05-.143Z" clip-rule="evenodd" fill-rule="evenodd" />-->
<!--  </svg>-->
</label>
HTML;
        }

        // Wrap in fieldset with legend and flex 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-2 gap-2 sm:grid-cols-5 md:grid-cols-5">
    {$itemsHtml}
  </div>
  {$helpHtml}
  {$errorHtml}
</fieldset>
HTML;
    }
}
