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

class Textarea extends BaseField {
    public static function render(string $name, string $label, $value = '', array $opts = []): string {
        $errors = $opts['errors'] ?? [];
        $help = $opts['help'] ?? '';
        $extra = $opts['input_attrs'] ?? '';
        $hasError = !empty($errors);
        $collapsible = $opts['collapsible'] ?? false;

        $nameEsc = self::h($name);
        $labelEsc = self::h($label);
        $valueEsc = self::h((string)$value);
        $helpHtml = self::helpHtml($help);
        $errorHtml = self::errorsHtml($errors);
        $clientErr = self::clientErrorHtml($name);
        $badge = $opts['label_badge_html'] ?? '';

        $idBase = preg_replace('/[^a-zA-Z0-9_-]+/', '-', $name);
        $idBase = trim($idBase ?? '', '-');
        if ($idBase === '') { $idBase = 'textarea'; }
        $id = self::h($idBase);

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

        $inputWrapperClass = $opts['no_label'] ?? false ? '' : 'mt-2';
        $containerClass = (string)($opts['container_class'] ?? '');

        $textareaClass = self::inputClass($hasError, !empty($opts['is_readonly'])) . ' px-3';

        if ($collapsible) {
            $addNoteLabel = self::lng('MAILBEEZ_NEWSLETTER_ADD_NOTE', '+ Add Note');
            $xModelName = addslashes($name);

            $btnHtml = \Components\Button::render($addNoteLabel, [
                'variant' => 'ghost',
                'size' => 'sm',
                'icon' => self::SVG_ADD,
                'iconPosition' => 'front',
                'class' => 'text-brand hover:text-brand-800',
                'attrs' => [
                    '@click' => 'expanded = true',
                ],
            ]);

            return <<<HTML
<div class="{$containerClass}" x-data="{ expanded: (form['{$xModelName}'] && form['{$xModelName}'].length > 0) }">
  <div x-show="!expanded" x-cloak class="{$inputWrapperClass} flex justify-end -mt-4!">
    {$btnHtml}
  </div>
  <div x-show="expanded" x-collapse.duration.300ms x-cloak>
    {$labelHtml}
    <div class="{$inputWrapperClass}">
      <textarea id="{$id}" name="{$nameEsc}" rows="3" class="{$textareaClass}" {$extra}>{$valueEsc}</textarea>
    </div>
    {$helpHtml}
    {$errorHtml}
    {$clientErr}
  </div>
</div>
HTML;
        }

        $inputInner = <<<HTML
<textarea id="{$id}" name="{$nameEsc}" rows="3" class="{$textareaClass}" {$extra}>{$valueEsc}</textarea>
HTML;
        return self::renderContainer($labelHtml, $inputInner, $helpHtml, $errorHtml, $clientErr, $opts);
    }
}
