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

class Select extends BaseField {
    /**
     * @param array $options key=>label pairs
     */
    public static function render(string $name, string $label, array $options = [], $value = '', array $opts = []): string {
        $errors = $opts['errors'] ?? [];
        $help = $opts['help'] ?? '';
        $extra = $opts['input_attrs'] ?? '';
        $hasError = !empty($errors);

        $nameEsc = self::h($name);
        $labelEsc = self::h($label);

        // Build id for label association
        $id = (string)($opts['id'] ?? '');
        if ($id === '') {
            $idBase = preg_replace('/[^a-zA-Z0-9_-]+/', '-', $name);
            $idBase = trim($idBase ?? '', '-');
            if ($idBase === '') {
                $idBase = 'select';
            }
            $id = self::h($idBase);
        } else {
            $id = self::h($id);
        }

        $includeEmpty = $opts['include_empty'] ?? true;
        $emptyLabel = $opts['empty_label'] ?? '-- Select --';
        $emptyValue = array_key_exists('empty_value', $opts) ? (string)$opts['empty_value'] : '';

        $optionsHtml = '';
        if ($includeEmpty) {
            $sel = ((string)$emptyValue === (string)$value) ? ' selected' : '';
            $emptyValEsc = self::h((string)$emptyValue);
            $emptyLabelEsc = self::h((string)$emptyLabel);
            $optionsHtml .= <<<HTML
<option value="{$emptyValEsc}"{$sel}>{$emptyLabelEsc}</option>
HTML;
        }
        foreach ($options as $val => $text) {
            $sel = ((string)$val === (string)$value) ? ' selected' : '';
            $valEsc = self::h((string)$val);
            $textEsc = self::h((string)$text);
            $optionsHtml .= <<<HTML
<option value="{$valEsc}"{$sel}>{$textEsc}</option>
HTML;
        }

        $helpHtml = self::helpHtml($help);
        $errorHtml = self::errorsHtml($errors);
        $clientErr = self::clientErrorHtml($name);
        $badge = $opts['label_badge_html'] ?? '';
        $size = $opts['size'] ?? 'md';

        $sizeClasses = [
            'xs' => 'py-0.5 pl-2',
            'sm' => 'py-1 pl-2.5',
            'md' => 'py-1.5 pl-3',
            'lg' => 'py-2 pl-3.5',
        ];
        $sizeClass = $sizeClasses[$size] ?? $sizeClasses['md'];

        $labelHtml = '';
        if (!($opts['no_label'] ?? false)) {
            $labelHtml = self::renderLabel($id, $label, $badge, $opts);
        }

        $inputWrapperClass = $opts['no_label'] ?? false ? '' : 'mt-2';

        // Select base class; note appearance-none and extra right padding for chevron
        if (($opts['variant'] ?? '') === 'ghost') {
            $selectClass = 'col-start-1 row-start-1 appearance-none bg-transparent border-none rounded-md ' . $sizeClass . ' pr-8 text-base sm:text-sm/6 focus:ring-0 cursor-pointer hover:bg-gray-100 dark:text-white dark:hover:bg-white/10';
        } else {
            $selectClass = self::inputClass($hasError, !empty($opts['is_readonly']));
            $selectClass = str_replace('block', 'col-start-1 row-start-1 appearance-none', $selectClass);

            // Adjust padding if not md (since inputClass defaults to py-1.5)
            if ($size === 'xs') {
                $selectClass = str_replace('py-1.5', 'py-0.5', $selectClass);
            } elseif ($size === 'sm') {
                $selectClass = str_replace('py-1.5', 'py-1', $selectClass);
            } elseif ($size === 'lg') {
                $selectClass = str_replace('py-1.5', 'py-2', $selectClass);
            }

            $selectClass .= ' pr-8 pl-3 dark:*:bg-gray-800';
        }

        $inputInner = <<<HTML
<div class="grid grid-cols-1">
  <select id="{$id}" name="{$nameEsc}" class="{$selectClass}" {$extra}>
    {$optionsHtml}
  </select>
  <svg viewBox="0 0 16 16" fill="currentColor" data-slot="icon" aria-hidden="true" class="pointer-events-none col-start-1 row-start-1 mr-2 size-5 self-center justify-self-end text-gray-500 sm:size-4 dark:text-gray-400">
    <path d="M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z" clip-rule="evenodd" fill-rule="evenodd" />
  </svg>
</div>
HTML;
        return self::renderContainer($labelHtml, $inputInner, $helpHtml, $errorHtml, $clientErr, $opts);
    }
}
