#ifndef EDITSCENE_EVENT_HANDLER_SYSTEM_HPP
#define EDITSCENE_EVENT_HANDLER_SYSTEM_HPP
#pragma once

#include "EventBus.hpp"
#include "../components/EventParams.hpp"
#include <flecs.h>
#include <Ogre.h>
#include <unordered_map>
#include <unordered_set>

class BehaviorTreeSystem;

/**
 * System that bridges EventBus events to behavior tree execution.
 *
 * When an entity has an EventHandlerComponent, this system subscribes
 * to the specified event. When the event fires, the referenced action's
 * behavior tree is executed for that entity. Event parameters are
 * injected into the entity's GoapBlackboard before the tree runs and
 * cleaned up when the tree completes.
 */
class EventHandlerSystem {
public:
	EventHandlerSystem(flecs::world &world, BehaviorTreeSystem *btSystem);
	~EventHandlerSystem();

	void update(float deltaTime);

private:
	struct ActiveHandler {
		flecs::entity_t entityId;
		Ogre::String actionName;
		editScene::EventParams eventParams;
		bool firstFrame = true;
	};

	void subscribeEntity(flecs::entity e,
			     const struct EventHandlerComponent &handler);
	void unsubscribeEntity(flecs::entity_t id);

	void onEvent(flecs::entity_t entityId, const Ogre::String &eventName,
		     const editScene::EventParams &params);

	void injectParams(flecs::entity e, const editScene::EventParams &params,
			  std::unordered_set<std::string> &outKeys);
	void removeParams(flecs::entity e,
			  const std::unordered_set<std::string> &keys);

	flecs::world &m_world;
	BehaviorTreeSystem *m_btSystem;

	// Map from entity ID to EventBus listener ID
	std::unordered_map<flecs::entity_t, EventBus::ListenerId>
		m_subscriptions;

	// Currently active handlers (entity ID -> handler state)
	std::unordered_map<flecs::entity_t, ActiveHandler> m_activeHandlers;

	// Keys injected into each entity's blackboard (for cleanup)
	std::unordered_map<flecs::entity_t, std::unordered_set<std::string> >
		m_injectedKeys;
};

#endif // EDITSCENE_EVENT_HANDLER_SYSTEM_HPP
