#ifndef EDITSCENE_PHYSICSSYSTEM_HPP
#define EDITSCENE_PHYSICSSYSTEM_HPP
#pragma once

#include <flecs.h>
#include <Ogre.h>
#include <memory>
#include "../physics/physics.h"
#include "../components/RigidBody.hpp"
#include "../components/PhysicsCollider.hpp"

/**
 * Physics system for the editor
 * Manages Jolt physics world and creates/updates bodies from components
 */
class EditorPhysicsSystem {
public:
	EditorPhysicsSystem(flecs::world &world, Ogre::SceneManager *sceneMgr);
	~EditorPhysicsSystem();

	// Initialize physics world
	void initialize();

	// Update physics simulation
	void update(float deltaTime);

	// Process component changes and create/update bodies
	void syncBodies();

	// Update SceneNodes from physics for dynamic bodies
	void updateDynamicBodies();

	// Enable/disable physics stepping
	void setPhysicsEnabled(bool enable)
	{
		m_physicsEnabled = enable;
	}
	bool isPhysicsEnabled() const
	{
		return m_physicsEnabled;
	}

	// Enable/disable debug drawing
	void setDebugDraw(bool enable);
	bool isDebugDrawEnabled() const
	{
		return m_debugDraw;
	}

	bool isInitialized() const
	{
		return m_initialized;
	}

	// Remove a rigid body (public for external cleanup)
	void removeRigidBody(RigidBodyComponent &rigidBody);

	// Get physics wrapper for other systems (e.g., buoyancy)
	JoltPhysicsWrapper *getPhysicsWrapper() const
	{
		return m_physics.get();
	}

private:
	// Create a shape from collider component
	JPH::ShapeRefC createShape(PhysicsColliderComponent &collider);

	// Build compound shape from multiple colliders
	JPH::ShapeRefC buildCompoundShape(flecs::entity rigidBodyEntity);

	// Create or update a rigid body
	void updateRigidBody(flecs::entity entity,
			     RigidBodyComponent &rigidBody,
			     class TransformComponent &transform);

	flecs::world &m_world;
	Ogre::SceneManager *m_sceneMgr;

	std::unique_ptr<JoltPhysicsWrapper> m_physics;
	bool m_initialized = false;
	bool m_debugDraw = false;
	bool m_physicsEnabled = true;

	// Query for entities with RigidBody
	flecs::query<RigidBodyComponent, TransformComponent> m_rigidBodyQuery;
};

#endif // EDITSCENE_PHYSICSSYSTEM_HPP
