#include "RigidBodyEditor.hpp"
#include <imgui.h>

bool RigidBodyEditor::renderComponent(flecs::entity entity,
				      RigidBodyComponent &rigidBody)
{
	bool modified = false;

	if (ImGui::CollapsingHeader("Rigid Body",
				    ImGuiTreeNodeFlags_DefaultOpen)) {
		ImGui::Indent();

		// Enabled checkbox - controls if body is in physics world
		if (ImGui::Checkbox("Enabled", &rigidBody.enabled)) {
			rigidBody.markDirty();
			modified = true;
		}
		if (ImGui::IsItemHovered()) {
			ImGui::SetTooltip(
				"If unchecked, the body is removed from the physics world. "
				"When checked again, it will be re-added at the current position.");
		}

		ImGui::Separator();

		// Body type selector
		const char *bodyTypes[] = { "Static", "Dynamic", "Kinematic" };
		int currentType = static_cast<int>(rigidBody.bodyType);
		if (ImGui::Combo("Body Type", &currentType, bodyTypes,
				 IM_ARRAYSIZE(bodyTypes))) {
			rigidBody.bodyType =
				static_cast<RigidBodyComponent::BodyType>(currentType);
			rigidBody.markDirty();
			modified = true;
		}

		// Mass (only for dynamic bodies)
		bool isDynamic = rigidBody.bodyType ==
				 RigidBodyComponent::BodyType::Dynamic;
		if (isDynamic) {
			if (ImGui::DragFloat("Mass (kg)", &rigidBody.mass, 0.1f,
					     0.001f)) {
				if (rigidBody.mass < 0.001f) rigidBody.mass = 0.001f;
				rigidBody.markDirty();
				modified = true;
			}
		} else {
			ImGui::Text("Mass: N/A (infinite for static/kinematic)");
		}

		// Friction
		if (ImGui::DragFloat("Friction", &rigidBody.friction, 0.01f, 0.0f,
				     1.0f)) {
			rigidBody.markDirty();
			modified = true;
		}

		// Restitution (bounciness)
		if (ImGui::DragFloat("Restitution (Bounciness)",
				     &rigidBody.restitution, 0.01f, 0.0f, 1.0f)) {
			rigidBody.markDirty();
			modified = true;
		}

		// Is sensor
		if (ImGui::Checkbox("Is Sensor", &rigidBody.isSensor)) {
			rigidBody.markDirty();
			modified = true;
		}
		if (ImGui::IsItemHovered()) {
			ImGui::SetTooltip(
				"Sensors detect collisions but don't physically react");
		}

		// Status info
		ImGui::Separator();
		if (rigidBody.bodyCreated) {
			ImGui::Text("Status: Body created");
		} else {
			ImGui::Text("Status: Body not created");
		}
		if (rigidBody.bodyDirty) {
			ImGui::TextColored(ImVec4(1, 0.5f, 0, 1),
					   "(needs rebuild)");
		}

		ImGui::Unindent();
	}

	return modified;
}
