<div id="stage-tree" class="shadow-md border border-zinc-200 rounded-lg flex flex-col gap-2 p-2 w-full h-fit overflow-x-scroll">
    <h3 class="text-zinc-500 text-sm pb-2 border-b border-zinc-200">Directorio de etapas</h3>
    <ul class="list-none">
        <?php renderStageTree($project->stages); ?>
    </ul>
</div>

<?php
    function renderStageTree(array $stages, bool $isRoot = true) {
        if ($isRoot) {
            echo '<div class="flex justify-end p-2"><button class="add-root-stage-btn text-sm text-[#393784] hover:bg-[#eeedfa] hover:transition-all ease-in-out px-2 rounded-lg cursor-pointer">+ Crear Etapa Raíz</button></div>';
        }
        foreach ($stages as $stage) renderStageItem($stage, 0);
    }

    function renderStageItem($stage, int $level) {
        $statusColors = [
            'rojo' => '#dc2626',      // rojo
            'amarillo' => '#ca8a04',  // amarillo
            'verde' => '#16a34a',     // verde
        ];

        $color = $statusColors[$stage->status_traffic_light] ?? '#27272a'; // color por defecto
        
        $hasChildren = !empty($stage->children);

        echo '<div class="stage-item flex flex-col gap-1">';
        echo '<div data-parent-id="' . $stage->id . '" class="flex items-center gap-2 stage-header justify-between px-2 pr-4 rounded-lg text-zinc-800 hover:bg-[#eeedfa] transition-all ease-in-out cursor-pointer" data-stage-id="' . $stage->id . '" style="margin-left:' . ($level * 10) . 'px">';

        echo '<div class="stage-title flex items-center gap-1 overflow-hidden whitespace-nowrap text-ellipsis max-w-[calc(100%-4rem)]">';

        // Mostrar flecha solo si tiene hijos
        if ($hasChildren) {
            echo '<svg class="h-4 w-4 stage-toggle cursor-pointer transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>';
        } else {
            // para alinear igual, ponemos un espacio vacío
            echo '<span class="w-4"></span>';
        }

        echo "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='currentColor' style='color: $color;' class='h-4 w-4'>
                    <path d='M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z'/>
                </svg>";
        echo '<span class="ml-1 font-medium">' . htmlspecialchars($stage->name) . '</span>';
        echo '</div>'; // stage-title

        echo '<button class="add-stage-btn ml-auto text-xs text-[#393784] cursor-pointer flex-shrink-0" data-parent-id="' . $stage->id . '" title="Agregar etapa hija">+ Etapa</button>';
        echo '</div>';

        if ($hasChildren) {
            echo '<div class="stage-children hidden">';
            foreach ($stage->children as $child) renderStageItem($child, $level + 1);
            echo '</div>';
        }
        echo '</div>';
    }
?>