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

use Components\Support\Palette;

class ColorSelect extends BaseField
{
    /**
     * Render a color selector using the shared Palette tokens.
     * - Shows a colored dot for each option and in the selected header.
     * - Posts the selected token value (e.g., "blue", "indigo", ...).
     *
     * Options (in $opts):
     * - help: string help text
     * - errors: array of error strings
     * - input_attrs: string raw attributes added to <el-select>
     * - 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'] ?? '';

        // Build normalized options: [ [value, label, dotClass], ... ]
        $options = [];
        if ($includeEmpty) {
            $options[] = ['value' => (string)$emptyValue, 'label' => (string)$emptyLabel, 'dot' => ''];
        }
        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,
            ];
        }

        // Determine selected option for header
        $selected = null;
        foreach ($options as $opt) {
            if ((string)$opt['value'] === (string)$value) { $selected = $opt; break; }
        }
        if ($selected === null) {
            // Skip the empty option for header "default" selection when value is empty and include_empty is false
            $fallbackToken = (string)($tokens[0] ?? 'gray');
            $selected = [
                'value' => (string)$value,
                'label' => $value !== '' ? ucfirst((string)$value) : ucfirst($fallbackToken),
                'dot' => $value !== '' ? Palette::dotBg((string)$value, 'gray') : Palette::dotBg($fallbackToken, 'gray'),
            ];
        }

        $helpHtml = self::helpHtml($help);
        $errorHtml = self::errorsHtml($errors);
        $clientErr = self::clientErrorHtml($name);

        // Build options HTML
        $optsHtml = '';
        foreach ($options as $opt) {
            $v = self::h((string)$opt['value']);
            $t = self::h((string)$opt['label']);
            $dotCls = trim('inline-block size-2.5 rounded-full ring-1 ring-black/5 ' . (string)$opt['dot']);
            $optsHtml .= <<<HTML
    <el-option value="{$v}"
     class="group/option block cursor-default p-2.5 text-sm text-gray-900 select-none focus:bg-gray-100 focus:text-white focus:outline-hidden dark:text-white dark:focus:bg-brand-600">
      <div class="flex items-center gap-2">
        <span class="{$dotCls}"></span>
        <span class="font-normal group-aria-selected/option:font-semibold">{$t}</span>
        <span class="ml-auto text-brand-700 group-not-aria-selected/option:hidden group-focus/option:text-white in-[el-selectedcontent]:hidden dark:text-brand-400">
          <svg viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" class="size-5">
            <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>
        </span>
      </div>
    </el-option>
HTML;
        }

        $valueEsc = self::h((string)$value);
        $selectedLabelEsc = self::h((string)$selected['label']);
        $selectedDotCls = self::h('inline-block size-2.5 rounded-full ring-1 ring-black/5 ' . (string)$selected['dot']);


        // Render
        return <<<HTML
<div>
<label class="block">
  <span class="text-sm text-gray-700">{$labelEsc}{$badge}</span>
  <el-select name="{$nameEsc}" value="{$valueEsc}" {$extra}>
    <div class="inline-flex items-center gap-x-2 rounded-md bg-brand-700 px-3 py-2 text-white dark:bg-brand-600">
     
      <el-selectedcontent class="text-sm font-semibold"> <span class="{$selectedDotCls}"></span> {$selectedLabelEsc}</el-selectedcontent>
      <button type="button"
              aria-label="Toggle system mode"
              class="inline-flex items-center rounded-l-none rounded-r-md p-2 "
     >
        <svg viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" class="size-5 text-white">
          <path d="M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z" clip-rule="evenodd" fill-rule="evenodd" />
        </svg>
      </button>
    </div>
    <el-options 
    anchor="bottom end"  class="w-64 origin-top-right divide-y divide-gray-200 overflow-hidden rounded-md bg-white shadow-lg outline-1 outline-black/5 [--anchor-gap:--spacing(2)] data-leave:transition data-leave:transition-discrete data-leave:duration-100 data-leave:ease-in data-closed:data-leave:opacity-0 dark:divide-white/10 dark:bg-gray-800 dark:shadow-none dark:-outline-offset-1 dark:outline-white/10">
{$optsHtml}
    </el-options>
  </el-select>
  {$helpHtml}
  {$errorHtml}
  {$clientErr}
</label>
</div>
HTML;
    }
}
