#ifndef COMPONENTEDITOR_HPP
#define COMPONENTEDITOR_HPP
#pragma once
#include <imgui.h>
#include <flecs.h>
#include <typeindex>
#include <unordered_map>
#include <functional>
#include <memory>
#include <string>

class IComponentEditor {
public:
    virtual ~IComponentEditor() = default;
    virtual bool render(flecs::entity entity, void* component) = 0;
    virtual std::type_index getType() const = 0;
};

template<typename T>
class ComponentEditor : public IComponentEditor {
public:
    bool render(flecs::entity entity, void* component) override {
        return renderComponent(entity, *static_cast<T*>(component));
    }

    std::type_index getType() const override {
        return std::type_index(typeid(T));
    }

protected:
    virtual bool renderComponent(flecs::entity entity, T& component) = 0;
};

class ComponentEditorRegistry {
public:
    template<typename T>
    void registerEditor(std::unique_ptr<ComponentEditor<T>> editor) {
        m_editors[std::type_index(typeid(T))] = std::move(editor);
    }

    bool renderComponent(flecs::entity entity, flecs::type_t componentType, void* component) {
        // In flecs 4.1.4, we need to get the type ID properly
        // For now, we'll use a simpler approach - store editors by component ID
        auto it = m_editors_by_id.find(componentType);
        if (it != m_editors_by_id.end()) {
            return it->second->render(entity, component);
        }
        return false;
    }

    // Alternative: Register by type directly
    template<typename T>
    void registerEditor(std::unique_ptr<ComponentEditor<T>> editor) {
        m_editors_by_type[typeid(T)] = std::move(editor);
    }

    template<typename T>
    bool renderComponent(flecs::entity entity, T& component) {
        auto it = m_editors_by_type.find(typeid(T));
        if (it != m_editors_by_type.end()) {
            return it->second->render(entity, &component);
        }
        return false;
    }

private:
    std::unordered_map<std::type_index, std::unique_ptr<IComponentEditor>> m_editors_by_type;
    std::unordered_map<flecs::type_t, std::unique_ptr<IComponentEditor>> m_editors_by_id;
};
#endif // COMPONENTEDITOR_HPP
