<?php
// components/Assistant/Question.php
namespace Components\Assistant;

use Components\Base;

class Question
{
    /**
     * Render a single_choice question as inline chips of radio buttons.
     */
    public static function renderSingleChoice(array $current, string $id, string $value, array $errs = []): string
    {
        $hasErr = !empty($errs[$id]);
        $errMsg = $hasErr ? (string)$errs[$id] : '';
        $required = !empty($current['required']);
        $options = (array)($current['options'] ?? []);
        ob_start();
        ?>
<div class="mt-2 flex flex-wrap gap-2" data-group="radio" <?php if ($required): ?>data-required="1"<?php endif; ?>>
  <?php foreach ($options as $opt): $oid = $opt['id']; $sel = $value === (string)$oid; ?>
    <label class="cursor-pointer inline-flex">
      <input type="radio" class="peer sr-only" form="assistant-form" name="<?= Base::h($id) ?>" value="<?= Base::h($oid) ?>" <?= $sel ? 'checked' : '' ?> onchange="document.getElementById('assistant-form').requestSubmit()" />
      <span class="inline-flex items-center rounded-full border px-3 py-1 text-sm border-gray-200 dark:border-white/10 bg-white dark:bg-white/5 text-gray-700 dark:text-gray-200
            peer-checked:bg-brand peer-checked:text-white peer-checked:border-brand-600 hover:border-brand-400">
        <?= Base::h($opt['label']) ?>
      </span>
    </label>
  <?php endforeach; ?>
</div>
<?php $hasErr = !empty($errs[$id]); $errMsg = $hasErr ? (string)$errs[$id] : ''; ?>
<p id="err-<?= Base::h($id) ?>" data-error-for="<?= Base::h($id) ?>" role="alert" class="text-sm mt-1 text-red-600 <?= $hasErr ? '' : 'invisible' ?>" style="min-height: 1.25rem;"><?= Base::h($errMsg) ?></p>
<?php if (!$required): ?>
<div class="mt-2">


  <button type="button" class="shrink-0 size-10 flex justify-center items-center rounded-full bg-brand text-sm font-medium text-white hover:bg-brand-700" onclick="try{document.getElementById('assistant-form').requestSubmit();}catch(e){}">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-5">
          <path fill-rule="evenodd" d="M11.47 2.47a.75.75 0 0 1 1.06 0l7.5 7.5a.75.75 0 1 1-1.06 1.06l-6.22-6.22V21a.75.75 0 0 1-1.5 0V4.81l-6.22 6.22a.75.75 0 1 1-1.06-1.06l7.5-7.5Z" clip-rule="evenodd" />
      </svg>


  </button>
</div>
<?php endif; ?>
<?php
        return ob_get_clean();
    }

    /**
     * Render a single_choice_rich question using Tailwind Plus Elements <el-select>.
     */
    public static function renderSingleChoiceRich(array $current, string $id, string $value, array $errs = []): string
    {
        $required = !empty($current['required']);
        $selectedLabel = '';
        foreach (($current['options'] ?? []) as $opt) {
            if ((string)($opt['id'] ?? '') === $value) { $selectedLabel = (string)($opt['label'] ?? $value); break; }
        }
        if ($selectedLabel === '') { $selectedLabel = (string)($current['placeholder'] ?? 'Select an option'); }
        $hasErr = !empty($errs[$id]);
        $errMsg = $hasErr ? (string)$errs[$id] : '';
        ob_start();
        ?>
<div class="mt-2" <?php if ($required): ?>data-required="1"<?php endif; ?>>
  <el-select name="<?= Base::h($id) ?>" value="<?= Base::h($value) ?>" form="assistant-form" onchange="document.getElementById('assistant-form').requestSubmit()">
    <div class="inline-flex divide-x divide-brand-700 rounded-md outline-hidden dark:divide-brand-600">
      <div class="inline-flex items-center gap-x-1.5 rounded-l-md bg-brand px-3 py-2 text-white dark:bg-brand-500">
        <svg viewBox="0 0 20 20" fill="currentColor" data-slot="icon" aria-hidden="true" class="-ml-0.5 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>
        <el-selectedcontent class="text-sm font-semibold"><?= Base::h($selectedLabel) ?></el-selectedcontent>
      </div>
      <button type="button" aria-label="Change selection" class="inline-flex items-center rounded-l-none rounded-r-md bg-brand p-2 hover:bg-brand-700 focus-visible:outline-2 focus-visible:outline-brand-400 dark:bg-brand-500 dark:hover:bg-brand-400 dark:focus-visible:outline-brand-400">
        <svg viewBox="0 0 20 20" fill="currentColor" data-slot="icon" aria-hidden="true" class="size-5 text-white forced-colors:text-[Highlight]">
          <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" popover class="w-72 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">
      <?php foreach ($current['options'] as $opt): $oid = (string)$opt['id']; $olabel = (string)($opt['label'] ?? $oid); ?>
        <el-option value="<?= Base::h($oid) ?>" class="group/option block cursor-default p-4 text-sm text-gray-900 select-none focus:bg-brand focus:text-white focus:outline-hidden dark:text-white dark:focus:bg-brand-500">
          <div class="flex flex-col">
            <div class="flex justify-between">
              <p class="font-normal group-aria-selected/option:font-semibold in-[el-selectedcontent]:font-semibold"><?= Base::h($olabel) ?></p>
              <span class="text-brand-600 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" data-slot="icon" 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>
          </div>
        </el-option>
      <?php endforeach; ?>
    </el-options>
  </el-select>
</div>
<?php $hasErr = !empty($errs[$id]); $errMsg = $hasErr ? (string)$errs[$id] : ''; ?>
<p id="err-<?= Base::h($id) ?>" data-error-for="<?= Base::h($id) ?>" role="alert" class="text-sm mt-1 text-red-600 <?= $hasErr ? '' : 'invisible' ?>" style="min-height: 1.25rem;"><?= Base::h($errMsg) ?></p>
<?php if (!$required): ?>
<div class="mt-2">


  <button type="button" class="shrink-0 size-10 flex justify-center items-center rounded-full bg-brand text-sm font-medium text-white hover:bg-brand-700" onclick="try{document.getElementById('assistant-form').requestSubmit();}catch(e){}">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-5">
          <path fill-rule="evenodd" d="M11.47 2.47a.75.75 0 0 1 1.06 0l7.5 7.5a.75.75 0 1 1-1.06 1.06l-6.22-6.22V21a.75.75 0 0 1-1.5 0V4.81l-6.22 6.22a.75.75 0 1 1-1.06-1.06l7.5-7.5Z" clip-rule="evenodd" />
      </svg>

  </button>
</div>
<?php endif; ?>
<?php
        return ob_get_clean();
    }

    /**
     * Render a multi_choice question as inline chips of checkboxes.
     */
    public static function renderMultiChoice(array $current, string $id, array $values, array $errs = []): string
    {
        $required = !empty($current['required']);
        $options = (array)($current['options'] ?? []);
        $hasErr = !empty($errs[$id]);
        $errMsg = $hasErr ? (string)$errs[$id] : '';
        ob_start();
        ?>
<div class="mt-2 flex flex-wrap gap-2" data-group="checkbox" <?php if ($required): ?>data-required="1"<?php endif; ?>>
  <?php foreach ($options as $opt): $oid = $opt['id']; $sel = in_array($oid, $values, true); ?>
    <label class="cursor-pointer inline-flex">
      <input type="checkbox" class="peer sr-only" form="assistant-form" name="<?= Base::h($id) ?>[]" value="<?= Base::h($oid) ?>" <?= $sel ? 'checked' : '' ?> />
      <span class="inline-flex items-center rounded-full border px-3 py-1 text-sm border-gray-200 dark:border-white/10 bg-white dark:bg-white/5 text-gray-700 dark:text-gray-200
            peer-checked:bg-brand peer-checked:text-white peer-checked:border-brand-600 hover:border-brand-400">
        <?= Base::h($opt['label']) ?>
      </span>
    </label>
  <?php endforeach; ?>
</div>
<div class="mt-2 flex items-end justify-end">

  <button type="button" class="shrink-0 size-10 flex justify-center items-center rounded-full bg-brand text-sm font-medium text-white hover:bg-brand-700" onclick="try{document.getElementById('assistant-form').requestSubmit();}catch(e){}">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-5">
          <path fill-rule="evenodd" d="M11.47 2.47a.75.75 0 0 1 1.06 0l7.5 7.5a.75.75 0 1 1-1.06 1.06l-6.22-6.22V21a.75.75 0 0 1-1.5 0V4.81l-6.22 6.22a.75.75 0 1 1-1.06-1.06l7.5-7.5Z" clip-rule="evenodd" />
      </svg>
  </button>
</div>
<?php $hasErr = !empty($errs[$id]); $errMsg = $hasErr ? (string)$errs[$id] : ''; ?>
<p id="err-<?= Base::h($id) ?>" data-error-for="<?= Base::h($id) ?>" role="alert" class="text-sm mt-1 text-red-600 <?= $hasErr ? '' : 'invisible' ?>" style="min-height: 1.25rem;"><?= Base::h($errMsg) ?></p>
<?php
        return ob_get_clean();
    }

    /**
     * Render a text question as an inline form inside the chat area.
     */
    public static function renderText(array $current, string $id, string $value, array $errs, array $step, string $flowId = ''): string
    {
        $type = (string)($current['type'] ?? 'text');
        $clientMetaInline = [
            'id' => (string)$id,
            'type' => (string)$type,
            'required' => !empty($current['required']),
            'validate' => $current['validate'] ?? null,
        ];
        $hasErr = !empty($errs[$id]);
        $errMsg = $hasErr ? (string)$errs[$id] : '';
        // Optional UI addons (prefix/suffix labels) e.g., for delay_days
        $ui = is_array($current['ui'] ?? null) ? $current['ui'] : [];
        $addonPrefix = (string)($ui['addon_prefix'] ?? ($current['addon_prefix'] ?? ''));
        $addonSuffix = (string)($ui['addon_suffix'] ?? ($current['addon_suffix'] ?? ''));
        $hasAddon = ($addonPrefix !== '' || $addonSuffix !== '');
        ob_start();
        ?>
<form id="assistant-form"
      data-no-local-loader="true"
      data-no-global-loader="true"
      hx-post="<?= \Components\Router::url('assistant_answer', ['partial' => 1, 'flow' => isset($flowId)?$flowId:'' , 'module' => \Components\Assistant\FlowUtils::req('module')]); ?>"
      hx-target="#assistant-step"
      hx-swap="innerHTML"
      class="mt-2 flex gap-2"
      data-assistant-form="1"
      data-item-meta='<?= Base::h(json_encode($clientMetaInline)) ?>'>
  <?= MH_POST_TOKEN ?>
  <input type="hidden" name="step_id" value="<?= Base::h($step['id']) ?>" />
  <input type="hidden" name="flow" value="<?= Base::h(isset($flowId)?$flowId:'') ?>" />
  <input type="hidden" name="module" value="<?= Base::h(\Components\Assistant\FlowUtils::req('module')) ?>" />

  <?php if ($hasAddon): ?>
    <div class="flex min-w-0 flex-1 items-center rounded-md bg-white px-3 outline outline-1 -outline-offset-1 outline-gray-300 focus-within:outline-2 focus-within:-outline-offset-2 focus-within:outline-brand dark:bg-white/5 dark:outline-white/10 dark:focus-within:outline-brand">
      <?php if ($addonPrefix !== ''): ?>
        <div class="shrink-0 text-base text-gray-500 select-none sm:text-sm/6 dark:text-gray-400"><?= Base::h($addonPrefix) ?></div>
      <?php endif; ?>
      <input id="f-<?= Base::h($id) ?>" name="<?= Base::h($id) ?>" type="text"
             value="<?= Base::h((string)$value) ?>"
             placeholder="<?= Base::h($current['placeholder'] ?? 'Message the assistant…') ?>"
             <?php if (!empty($current['required'])): ?>required aria-required="true"<?php endif; ?>
             <?php if (!empty($current['validate']['min_length'])): ?> data-min-length="<?= (int)$current['validate']['min_length'] ?>"<?php endif; ?>
             <?php if (!empty($current['validate']['max_length'])): ?> data-max-length="<?= (int)$current['validate']['max_length'] ?>"<?php endif; ?>
             class="block min-w-0 grow bg-white 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" />
      <?php if ($addonSuffix !== ''): ?>
        <div class="shrink-0 text-base text-gray-500 select-none sm:text-sm/6 dark:text-gray-400"><?= Base::h($addonSuffix) ?></div>
      <?php endif; ?>
    </div>
  <?php else: ?>
    <input id="f-<?= Base::h($id) ?>" name="<?= Base::h($id) ?>" type="text"
           value="<?= Base::h((string)$value) ?>"
           placeholder="<?= Base::h($current['placeholder'] ?? 'Message the assistant…') ?>"
           <?php if (!empty($current['required'])): ?>required aria-required="true"<?php endif; ?>
           <?php if (!empty($current['validate']['min_length'])): ?> data-min-length="<?= (int)$current['validate']['min_length'] ?>"<?php endif; ?>
           <?php if (!empty($current['validate']['max_length'])): ?> data-max-length="<?= (int)$current['validate']['max_length'] ?>"<?php endif; ?>
           class="flex-1 rounded-xl border border-gray-200 bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-brand dark:border-white/10 dark:bg-white/5 dark:text-white" />
  <?php endif; ?>

    <button type="submit" class="shrink-0 size-10 flex justify-center items-center rounded-full bg-brand text-sm font-medium text-white hover:bg-brand-700">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-5">
            <path fill-rule="evenodd" d="M11.47 2.47a.75.75 0 0 1 1.06 0l7.5 7.5a.75.75 0 1 1-1.06 1.06l-6.22-6.22V21a.75.75 0 0 1-1.5 0V4.81l-6.22 6.22a.75.75 0 1 1-1.06-1.06l7.5-7.5Z" clip-rule="evenodd" />
        </svg>
    </button>
</form>
<?php $hasErr = !empty($errs[$id]); $errMsg = $hasErr ? (string)$errs[$id] : ''; ?>
<p id="err-<?= Base::h($id) ?>" data-error-for="<?= Base::h($id) ?>" role="alert" class="text-sm mt-1 text-red-600 <?= $hasErr ? '' : 'invisible' ?>" style="min-height: 1.25rem;"><?= Base::h($errMsg) ?></p>
<?php
        return ob_get_clean();
    }
}
