//
// Created by slinky on 5/11/26.
//

#include "UISceneGraph.h"

#include "Components.h"
#include "imgui.h"
#include "Scene.h"

void UISceneGraph::update(EditorContext &ctx) {
    ImGui::Begin("Hierarchy");

    if (ImGui::IsWindowHovered() && ImGui::IsMouseClicked(ImGuiMouseButton_Left))
    {
        ctx.selectedEntity = entt::null;
    }

    Scene* scene = ctx.scene;
    if (!scene) return;

    draw_children(scene->get_root(), scene, ctx);

    ImGui::End();
}

void UISceneGraph::draw_children(entt::entity parent, Scene *scene, EditorContext& ctx) {
    std::vector<entt::entity> children = scene->get_children(parent);
    for (const auto e : children) {
        const auto& rel = scene->fetch_component<Components::Relationship>(e);
        ImGuiTreeNodeFlags flags =
            ImGuiTreeNodeFlags_OpenOnArrow |
            ImGuiTreeNodeFlags_SpanFullWidth;

        if (rel.first_child == entt::null) {
            flags |= ImGuiTreeNodeFlags_Leaf;
        }

        const auto& [name] = scene->fetch_component<Components::Tag>(e);
        if (ImGui::TreeNodeEx((void*)(intptr_t)e, flags, "%s", name.data()))
        {
            draw_children(e, scene, ctx);
            ImGui::TreePop();
        }

        if (ImGui::IsItemClicked())
        {
            ctx.selectedEntity = e;
        }
    }
}


