<?php
// components/Ui/Stepper.php
namespace Components\Ui;

use Components\Base;

class Stepper
{
    /**
     * Render a Stepper UI component based on the provided mockup.
     *
     * @param array $steps List of steps: [ ['label' => 'Step 1', 'id' => 's1'], ... ]
     * @param int|string $current Current step index (0-based) or ID.
     * @return string
     */
    public static function render(array $steps, $current = 0): string
    {
        $currentIndex = is_int($current) ? $current : 0;
        if (is_string($current)) {
            foreach ($steps as $idx => $step) {
                if (($step['id'] ?? null) === $current) {
                    $currentIndex = $idx;
                    break;
                }
            }
        }

        $itemsHtml = '';
        $count = count($steps);

        $gridColsClass = 'grid-cols-1';
        switch ($count) {
            case 2: $gridColsClass = 'grid-cols-2'; break;
            case 3: $gridColsClass = 'grid-cols-3'; break;
            case 4: $gridColsClass = 'grid-cols-4'; break;
            case 5: $gridColsClass = 'grid-cols-5'; break;
        }

        foreach ($steps as $idx => $step) {
            $isLast = ($idx === $count - 1);
            $isCompleted = ($idx < $currentIndex);
            $isCurrent = ($idx === $currentIndex);

            $label = $step['label'] ?? '';
            $description = $step['description'] ?? '';
            $labelEsc = Base::h($label);
            $descEsc = Base::h($description);

            // Item color and state
            if ($isCurrent || $isCompleted) {
                $indicatorClass = "border-blue-600 bg-blue-50 text-blue-600";
                $titleClass = "text-blue-600";
            } else {
                $indicatorClass = "border-zinc-300 bg-white text-zinc-500";
                $titleClass = "text-zinc-700";
            }

            $stepNumber = $idx + 1;
            $itemsHtml .= <<<HTML
        <li class="relative min-w-0">
            <div class="flex items-start gap-3 text-left">
                <div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full border-2 {$indicatorClass} text-sm font-semibold">
                    {$stepNumber}
                </div>

                <div class="min-w-0">
                    <div class="flex items-center gap-2">
                        <p class="truncate text-sm font-semibold {$titleClass}">{$labelEsc}</p>
                    </div>
                    <p class="mt-0.5 line-clamp-2 text-xs leading-4 text-zinc-500">
                        {$descEsc}
                    </p>
                </div>
            </div>
        </li>
HTML;
        }

        return <<<HTML
<ol class="grid {$gridColsClass} gap-3">
    {$itemsHtml}
</ol>
HTML;
    }
}
