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

class I18nText extends BaseField {
    /**
     * Render multiple inputs (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'] ?? '';
        $hasError = !empty($errors);

        $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'] ?? '';

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

        $values = is_array($value) ? $value : [];
        $defaultId = function_exists('mh_cfg') ? (int)\mh_cfg('DEFAULT_LANGUAGE_ID', 1) : 1;

        $compactGenerated = !empty($opts['compact_generated_i18n']);
        if ($compactGenerated) {
            $toggleField = (string)($opts['compact_generated_i18n_toggle_field'] ?? 'is_template');
            $generatedValue = (string)($opts['compact_generated_i18n_generated_value'] ?? '0');
            $ctx = isset($opts['context']) && is_array($opts['context']) ? $opts['context'] : [];
            $currentMode = isset($ctx[$toggleField]) ? (string)$ctx[$toggleField] : '';
            $compactGenerated = ($currentMode === $generatedValue);
        }

        // Input-group classes (mirror Components\\Form\\Input)
        $groupClass = self::groupClass($hasError);
        $groupInputClass = 'block min-w-0 grow py-1.5 pr-3 pl-1 text-base text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-sm/6 dark:bg-transparent dark:text-white dark:placeholder:text-gray-500';

        $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;
            }
            $rowHtml = <<<HTML
<div class="{$groupClass}">
  <input name="{$nameEsc}[{$lidAttr}]" type="text" value="{$valEsc}" class="{$groupInputClass}" />
  <div class="shrink-0 text-base text-gray-500 select-none sm:text-sm dark:text-gray-400 opacity-70">{$suffix}</div>
</div>
HTML;
            $rows[] = [
                'id' => $lid,
                'is_default' => ($lid === $defaultId),
                'html' => $rowHtml,
            ];
        }


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

        $rowsHtml = '';
        if ($compactGenerated && !empty($rows)) {
            $defaultIndex = 0;
            foreach ($rows as $idx => $row) {
                if (!empty($row['is_default'])) {
                    $defaultIndex = (int)$idx;
                    break;
                }
            }

            $defaultRowHtml = (string)($rows[$defaultIndex]['html'] ?? '');
            $otherRowsHtml = '';
            $otherCount = 0;
            foreach ($rows as $idx => $row) {
                if ((int)$idx === $defaultIndex) {
                    continue;
                }
                $otherRowsHtml .= (string)($row['html'] ?? '');
                $otherCount++;
            }

            if ($otherRowsHtml === '') {
                $rowsHtml = $defaultRowHtml;
            } else {
                $rowsHtml = self::renderCompactI18nRows($defaultRowHtml, $otherRowsHtml, $otherCount);
            }
        } else {
            foreach ($rows as $row) {
                $rowsHtml .= (string)($row['html'] ?? '');
            }
        }

        $inputInner = <<<HTML
<div class="flex flex-col gap-2">
  {$rowsHtml}
</div>
HTML;
        return self::renderContainer($labelHtml, $inputInner, $helpHtml, $errorHtml, $clientErr, $opts);
    }
}
