#ifndef EDITSCENE_CHARACTERSYSTEM_HPP
#define EDITSCENE_CHARACTERSYSTEM_HPP
#pragma once

#include <flecs.h>
#include <Ogre.h>
#include <memory>
#include <unordered_map>

#include "../physics/physics.h"
#include "../components/Character.hpp"
#include "../components/Transform.hpp"
#include "../components/PhysicsCollider.hpp"

/**
 * System that manages JPH::Character instances for entities with
 * CharacterComponent.
 *
 * - Creates a capsule shape (plus child colliders) for each character
 * - Integrates linearVelocity each frame
 * - Syncs position/rotation between physics and SceneNode
 */
class CharacterSystem {
public:
	CharacterSystem(flecs::world &world, Ogre::SceneManager *sceneMgr);
	~CharacterSystem();

	void initialize();
	void update(float deltaTime);

	/**
	 * Disable physics for a character entity.
	 * Removes the JPH::Character's BodyID from the physics system
	 * but keeps the JPH::Character object alive so it can be re-added later.
	 * Sets CharacterComponent::physicsDisabled = true.
	 */
	void disablePhysics(flecs::entity e);

	/**
	 * Enable physics for a character entity.
	 * Re-adds the JPH::Character's BodyID to the physics system.
	 * Sets CharacterComponent::physicsDisabled = false.
	 */
	void enablePhysics(flecs::entity e);

private:
	struct CharacterState {
		JPH::Character *character = nullptr;
		Ogre::SceneNode *sceneNode = nullptr;
	};

	void setupEntity(flecs::entity e, CharacterComponent &cc);
	void teardownEntity(flecs::entity e);

	JPH::ShapeRefC buildCharacterShape(flecs::entity e,
					   CharacterComponent &cc);
	JPH::ShapeRefC createColliderShape(PhysicsColliderComponent &collider);
	void createHeadCollider(flecs::entity e, CharacterComponent &cc,
				const TransformComponent &transform);
	void createChestCollider(flecs::entity e, CharacterComponent &cc);

	flecs::world &m_world;
	Ogre::SceneManager *m_sceneMgr;
	JoltPhysicsWrapper *m_physics = nullptr;
	bool m_initialized = false;

	std::unordered_map<flecs::entity_t, CharacterState> m_states;
};

#endif // EDITSCENE_CHARACTERSYSTEM_HPP
