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

class I18nTextarea extends BaseField {
    /**
     * Render multiple textareas (one per language) using mh_get_language_list()).
     * $value is expected to be an array keyed by language_id -> string value.
     */
    public static function render(string $name, string $label, $value = [], array $opts = []): string {
        $errors = $opts['errors'] ?? [];
        $help = $opts['help'] ?? '';

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

        $langs = [];
        if (function_exists('mh_get_language_list')) {
            try { $langs = (array) \mh_get_language_list(); } catch (\Throwable $e) { $langs = []; }
        }
        if (empty($langs)) {
            $defaultId = function_exists('mh_cfg') ? (int)\mh_cfg('DEFAULT_LANGUAGE_ID', 1) : 1;
            $defaultCode = function_exists('mh_cfg') ? (string)\mh_cfg('DEFAULT_LANGUAGE_CODE', 'en') : 'en';
            $langs = [ [ 'id' => $defaultId, 'text' => 'Default', 'code' => $defaultCode ] ];
        }

        $values = is_array($value) ? $value : [];

        $taClass = self::inputClass() . ' px-3';

        $rows = '';
        foreach ($langs as $lang) {
            if (!is_array($lang)) continue;
            $lid = (int)($lang['id'] ?? 0);
            if ($lid <= 0) continue;
            $lname = (string)($lang['text'] ?? ($lang['code'] ?? ''));
            $lcode = (string)($lang['code'] ?? '');
            $val = (string)($values[$lid] ?? '');
            $valEsc = self::h($val);
            $lidAttr = self::h((string)$lid);
            $lnameEsc = self::h($lname);
            $lnameEsc = '';

            $flag = self::flagIconHtml($lcode);
            $suffix = $lnameEsc;
            if ($flag !== '') {
                $suffix = <<<HTML
<span class="inline-flex items-center gap-1">{$flag}</span>
HTML;
            }
            // Add right padding so text doesn't overlap with the language label
            $rows .= <<<HTML
<div class="relative">
  <textarea name="{$nameEsc}[{$lidAttr}]" rows="2" class="{$taClass} pr-8">{$valEsc}</textarea>
  <div class="pointer-events-none absolute right-3 top-2 inline-flex items-center gap-1 text-base text-gray-500 select-none sm:text-sm/6 dark:text-gray-400 bg-white/90 dark:bg-white/10 py-0.5 rounded-md opacity-70">{$suffix}</div>
</div>
HTML;
        }

        $labelCls = self::labelClass();
        $containerClass = (string)($opts['container_class'] ?? '');

        return <<<HTML
<div class="{$containerClass}">
  <label class="{$labelCls}">{$labelEsc}{$badge}</label>
  <div class="mt-2 space-y-2">
    {$rows}
  </div>
  {$helpHtml}
  {$errorHtml}
  {$clientErr}
</div>
HTML;
    }
}
