<?php
// components/Assistant/views/step.php
if (!defined('BEEZUI_ROOT')) {
    // This file resides in <root>/components/Assistant/views
    define('BEEZUI_ROOT', dirname(dirname(dirname(__DIR__))));
}
require_once BEEZUI_ROOT . '/components/index.php';

use Components\Assistant\{Flow, State, FlowUtils};

// Resolve
[$flowId, $yaml] = FlowUtils::resolveFlowAndYaml();
$stateKey = FlowUtils::stateKeyFor($flowId);
$flow = new Flow($yaml);
$state = State::get($stateKey);

$id = mh_get('id', '', 'string') ?: ($state['current'] ?: $flow->firstStepId());
$step = $flow->stepById($id);
if (!$step) {
    http_response_code(404);
    echo '<div class="p-4 text-red-600">Step not found</div>';
    return;
}

// push to back stack when navigating forward via link
if (($state['current'] ?? null) && $state['current'] !== $id) {
    $stack = $state['stack'] ?? [];
    if (empty($stack) || end($stack) !== $state['current']) {
        $stack[] = $state['current'];
    }
    $state['stack'] = $stack;
}
$state['current'] = $id;

$answers = $state['answers'] ?? [];

// Determine current item index within this step for chat-like progression
$itemIndex = 0;
$items = $flow->itemsForStep($step, $answers);
if (!empty($items)) {
    $idxMap = $state['item_index'] ?? [];
    $rawIdx = (int)($idxMap[$id] ?? 0);
    $maxIdx = max(0, count($items) - 1);
    $itemIndex = max(0, min($rawIdx, $maxIdx));
}

\Components\Assistant\State::put($state, $stateKey);

$answers = $state['answers'] ?? [];
$errs = $errs ?? [];
$old = $old ?? [];

// Determine grouping behavior from YAML (support both no_grouping and no-grouping)
$cfg = $flow->config();
$noGrouping = !empty($cfg['no_grouping']) || !empty($cfg['no-grouping']);

// Build cross-step chat history when noGrouping is enabled
$historyItems = [];
if ($noGrouping) {
    $visited = array_values(array_unique(array_map('strval', $state['stack'] ?? [])));
    if (!in_array((string)$id, $visited, true)) { $visited[] = (string)$id; }
    foreach ($visited as $sid) {
        $s = $flow->stepById((string)$sid);
        if (!$s) continue;
        $sItems = $flow->itemsForStep($s, $answers);
        if (!$sItems) continue;
        if ((string)$sid === (string)$id) {
            // Only prior answered items within the current step
            for ($i = 0; $i < $itemIndex; $i++) {
                $it = $sItems[$i] ?? null;
                if (!$it) continue;
                $iid = $it['id'] ?? null;
                if ($iid !== null && array_key_exists($iid, $answers)) {
                    $historyItems[] = $it;
                }
            }
        } else {
            // All answered items of previously completed steps
            foreach ($sItems as $it) {
                $iid = $it['id'] ?? null;
                if ($iid !== null && array_key_exists($iid, $answers)) {
                    $historyItems[] = $it;
                }
            }
        }
    }
}

include BEEZUI_ROOT . '/components/Assistant/views/step_view.php';
