<?php
// components/Onboarding/views/step_view.php
// Vars: $step, $answers, optional $errs, $old, $itemIndex
sleep(1);
$answers = $answers ?? [];
$errs = $errs ?? [];
$old = $old ?? [];
$items = isset($items) ? $items : ($step['items'] ?? []);
$idx = isset($itemIndex) ? (int)$itemIndex : 0;
$idx = max(0, min($idx, max(0, count($items) - 1)));

$vals = function ($id, $fallback = null) use ($answers, $old) {
    return $old[$id] ?? $answers[$id] ?? $fallback;
};

// Helper to resolve option labels for answers
$answerText = function (array $it, $val): string {
    $type = $it['type'] ?? 'text';
    $required = !empty($it['required']);

    if ($type === 'text') {
        return is_scalar($val) ? (string)$val : '';
    }

    if ($type === 'single_choice' || $type === 'single_choice_rich') {
        // No selection made
        if ($val === null || $val === '') {
            return $required ? '' : '(none)';
        }
        foreach (($it['options'] ?? []) as $opt) {
            if (($opt['id'] ?? null) == $val) {
                return (string)($opt['label'] ?? $val);
            }
        }
        return is_scalar($val) ? (string)$val : ($required ? '' : '(none)');
    }

    if ($type === 'multi_choice') {
        $vals = is_array($val) ? $val : (($val === null || $val === '') ? [] : [$val]);
        // Normalize and filter out empty values
        $norm = [];
        foreach ($vals as $v) {
            if ($v === null || $v === '') continue;
            $norm[] = $v;
        }
        if (count($norm) === 0) {
            return $required ? '' : '(none)';
        }
        $labels = [];
        foreach ($norm as $v) {
            $found = null;
            foreach (($it['options'] ?? []) as $opt) {
                if (($opt['id'] ?? null) == $v) {
                    $found = (string)($opt['label'] ?? $v);
                    break;
                }
            }
            $labels[] = $found ?? (string)$v;
        }
        $txt = implode(', ', array_filter($labels, fn($s) => $s !== ''));
        if ($txt === '') return $required ? '' : '(none)';
        return $txt;
    }

    // Fallback for other types
    $s = is_scalar($val) ? (string)$val : '';
    return $s === '' && !$required ? '(none)' : $s;
};

// Helper to resolve the bot question from language constant based on CONFIG_KEY + '_QUESTION'.
// Fallback to current label/id but with marker '[MISSING QUESTION]'.
$qText = function (array $it): string {
    $id = (string)($it['id'] ?? '');
    $label = (string)($it['label'] ?? $id);
    if ($id === '') return $label . ' [MISSING QUESTION]';
    $cfgKey = strtoupper($id);
    $fallback = $label . ' [MISSING QUESTION]';
    return (string)\mh_lng($cfgKey . '_QUESTION', $fallback);
};

// Localized group title & intro based on blueprint group key or fallback to module+group
$__moduleKey = strtoupper((string)\Components\Assistant\FlowUtils::req('module'));
$__groupIdKey = strtoupper((string)($step['group'] ?? ''));
$__groupBaseKey = '';
if (!empty($step['group_key'])) {
    $__groupBaseKey = strtoupper((string)$step['group_key']);
} elseif ($__moduleKey !== '' && $__groupIdKey !== '') {
    $__groupBaseKey = $__moduleKey . '_GROUP_' . $__groupIdKey;
}
$__titleKey = $__groupBaseKey !== '' ? ($__groupBaseKey . '_TITLE') : '';
$__explKey  = $__groupBaseKey !== '' ? ($__groupBaseKey . '_EXPLAINER') : '';
$__headerTitle = $__titleKey !== '' ? (string)\mh_lng($__titleKey, ($step['title'] ?? 'Step')) : ($step['title'] ?? 'Step');
$__groupExplainer = $__explKey !== '' ? (string)\mh_lng($__explKey, '') : '';
$__headerOut = (($step['type'] ?? '') === 'review') ? ($step['title'] ?? 'Step') : $__headerTitle;
?>
<div id="assistant-chat-root" x-data="chatStep" x-init="init()" class="space-y-4">
    <div id="assistant-header-title" hx-swap-oob="true"><?= \Components\Base::h($__headerOut) ?></div>
    <script>try{ window.__assistantAnswers = Object.assign({}, window.__assistantAnswers || {}, <?= json_encode($answers, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>); }catch(e){}</script>

    <?php if (($step['type'] ?? '') === 'review') {
        include BEEZUI_ROOT . '/components/Assistant/views/review_view.php';
        return;
    }
    ?>

    <?php if (!empty($items)): ?>
        <?php if ($idx === 0 && $__groupExplainer !== ''): ?>
            <?= \Components\Assistant\ChatBubble::renderBot($__groupExplainer, ['class' => 'opacity-0 translate-y-2 transition ease-out duration-300', 'data-reveal' => '', 'data-explainer' => '', 'reveal' => true]) ?>
        <?php endif; ?>
        <div class="space-y-4">
            <?php if (!empty($historyItems)): ?>
                <?php $hCount = is_array($historyItems) ? count($historyItems) : 0;
                $hPos = 0;
                foreach ($historyItems as $hist): $hid = $hist['id'];
                    $isLast = ($hPos === $hCount - 1); ?>
                    <!-- Bot question bubble (history) -->
                    <?= \Components\Assistant\ChatBubble::renderBot((string)$qText($hist)) ?>
                    <!-- User answer bubble (history) -->
                    <?php $av = $answers[$hid] ?? null;
                    echo \Components\Assistant\ChatBubble::renderUser((string)$answerText($hist, $av)); ?>
                    <?php $hPos++; endforeach; ?>
            <?php endif; ?>

            <?php if (empty($historyItems)): ?>
                <?php for ($i = 0; $i < $idx; $i++): $it = $items[$i];
                    $id = $it['id']; ?>
                    <!-- Bot question bubble -->
                    <?= \Components\Assistant\ChatBubble::renderBot((string)$qText($it)) ?>
                    <!-- User answer bubble -->
                    <?php $av = $answers[$id] ?? null;
                    echo \Components\Assistant\ChatBubble::renderUser((string)$answerText($it, $av)); ?>
                <?php endfor; ?>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <?php $current = $items[$idx] ?? null; ?>
    <div id="assistant-meta" data-step-id="<?= \Components\Base::h($step['id'] ?? '') ?>" data-item-index="<?= $idx ?>"
         data-item-id="<?= $current ? \Components\Base::h($current['id']) : '' ?>" class="hidden"></div>
    <?php if ($current): $id = $current['id'];
          $type = $current['type']; $hasExplainer = ($idx === 0 && $__groupExplainer !== ''); ?>
        <!-- Current question -->
        <?php if ($hasExplainer): ?>
            <div data-current-question x-data="{}" x-init="$el.style.display='none'; var __shown=false; var __show=function(){ if(!__shown){$el.style.display=''; __shown=true; try{var tgt=$el.querySelector('[data-reveal-root]'); if(tgt){ tgt.dispatchEvent(new CustomEvent('assistant:reveal', { bubbles: true })); }}catch(_e){} } }; var __h=function(ev){try{var t=ev&&(ev.target||ev.srcElement); if(t&&t.closest&&t.closest('[data-explainer]')){ __show(); document.removeEventListener('wordreveal:done', __h, false);} }catch(e){ __show(); document.removeEventListener('wordreveal:done', __h, false);} }; document.addEventListener('wordreveal:done', __h, false); setTimeout(function(){ __show(); document.removeEventListener('wordreveal:done', __h, false); }, 3500);">
                <?= \Components\Assistant\ChatBubble::renderBot((string)$qText($current), ['class' => 'opacity-0 translate-y-2 transition ease-out duration-300', 'data-reveal' => '', 'reveal' => true, 'defer_reveal' => true]) ?>
            </div>
        <?php else: ?>
            <?= \Components\Assistant\ChatBubble::renderBot((string)$qText($current), ['class' => 'opacity-0 translate-y-2 transition ease-out duration-300', 'data-reveal' => '', 'reveal' => true]) ?>
        <?php endif; ?>

        <!-- Reply options shown in chat area -->
        <?php if ($hasExplainer): ?>
        <div class="pl-1" data-reveal x-data="{}" x-init="$el.style.display='none'; var __shown=false; var __h=function(ev){ try{ var t=ev&&(ev.target||ev.srcElement); if(t){ var qwrap=document.querySelector('[data-current-question]'); if(qwrap && (t===qwrap.querySelector('[data-reveal-root]') || (t.closest && t.closest('[data-current-question]')))){ if(!__shown){$el.style.display=''; __shown=true;} document.removeEventListener('wordreveal:done', __h, false); } } }catch(e){ if(!__shown){$el.style.display=''; __shown=true;} document.removeEventListener('wordreveal:done', __h, false);} }; document.addEventListener('wordreveal:done', __h, false); setTimeout(function(){ if(!__shown){$el.style.display=''; __shown=true; document.removeEventListener('wordreveal:done', __h, false);} }, 5000);">
        <?php else: ?>
        <div class="pl-1" data-reveal>
        <?php endif; ?>
            <?php if ($type === 'single_choice'): $v = (string)$vals($id, ''); ?>
                <?= \Components\Assistant\Question::renderSingleChoice($current, (string)$id, (string)$v, $errs) ?>

            <?php elseif ($type === 'single_choice_rich'): $v = (string)$vals($id, ''); ?>
                <?= \Components\Assistant\Question::renderSingleChoiceRich($current, (string)$id, (string)$v, $errs) ?>

            <?php elseif ($type === 'multi_choice'): $valsArr = (array)$vals($id, []); ?>
                <?= \Components\Assistant\Question::renderMultiChoice($current, (string)$id, (array)$valsArr, $errs) ?>

            <?php elseif ($type === 'text'): ?>
                <?= \Components\Assistant\Question::renderText($current, (string)$id, (string)$vals($id, ''), $errs, $step, isset($flowId) ? $flowId : '') ?>
            <?php endif; ?>
        </div>

        <?php
        // Provide minimal client-side validation metadata for the current item
        $clientMeta = [
                'id' => (string)$id,
                'type' => (string)$type,
                'required' => !empty($current['required']),
                'validate' => $current['validate'] ?? null,
        ];
        ?>
        <!-- Composer (Out-Of-Band) updates footer controls -->
        <?php if ($type !== 'text'): ?>
            <!--      NOT USED -->
            <div id="assistant-composer" hx-swap-oob="true">
                <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="flex items-end justify-center gap-2"
                      data-assistant-form="1"
                      data-item-meta='<?= \Components\Base::h(json_encode($clientMeta)) ?>'>
                    <?= MH_POST_TOKEN ?>
                    <input type="hidden" name="step_id" value="<?= \Components\Base::h($step['id']) ?>"/>
                    <input type="hidden" name="flow" value="<?= \Components\Base::h(isset($flowId) ? $flowId : '') ?>"/>
                    <input type="hidden" name="module"
                           value="<?= \Components\Base::h(\Components\Assistant\FlowUtils::req('module')) ?>"/>


                    <!-- Input / Controls (center) -->
                    <label class="relative flex-1">
                        <div class="space-y-2">
                            <label class="sr-only"
                                   for="f-<?= \Components\Base::h($id) ?>"><?= \Components\Base::h($current['label'] ?? $id) ?></label>

                            <?php if ($type === 'text'): ?>
                                <input id="f-<?= \Components\Base::h($id) ?>" name="<?= \Components\Base::h($id) ?>"
                                       type="text"
                                       value="<?= \Components\Base::h((string)$vals($id, '')) ?>"
                                       placeholder="<?= \Components\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="w-full rounded-xl border border-gray-200 bg-white px-3 py-2 pr-10 text-sm outline-none focus:ring-2 focus:ring-brand dark:border-white/10 dark:bg-white/5 dark:text-white"/>
                            <?php endif; ?>

                            <?php if ($type === 'text'): ?>
                                <?php $hasErr = !empty($errs[$id]);
                                $errMsg = $hasErr ? (string)$errs[$id] : ''; ?>
                                <p id="err-<?= \Components\Base::h($id) ?>"
                                   data-error-for="<?= \Components\Base::h($id) ?>" role="alert"
                                   class="text-sm mt-1 text-red-600 <?= $hasErr ? '' : 'invisible' ?>"
                                   style="min-height: 1.25rem;"><?= \Components\Base::h($errMsg) ?></p>
                            <?php endif; ?>
                        </div>
                    </label>

                    <!-- Back / Tools (left) -->
                    <div class="flex items-top gap-1">
                        <!--            <button type="button" class="h-10 rounded-xl px-3 text-sm text-gray-600 hover:text-gray-800"-->
                        <!--                    hx-get="-->
                        <?php //= \Components\Router::url('assistant_back', ['partial' => 1]); ?><!--"-->
                        <!--                    hx-target="#assistant-step"-->
                        <!--                    hx-swap="innerHTML">Back</button>-->
                        <!-- extra tools could go here (hidden for now) -->
                    </div>
                    <!-- Submit (right) -->
                    <button type="submit"
                            class="h-10 rounded-xl bg-brand px-3 text-sm font-medium text-white hover:bg-brand-700">
                        <?php if ($type === 'text'): ?>Send<?php else: ?>Continue<?php endif; ?>
                    </button>
                </form>
            </div>
        <?php else: ?>
            <div id="assistant-composer" hx-swap-oob="true"></div>
        <?php endif; ?>
    <?php endif; ?>
</div>




