//
// Created by sebastian on 08.02.26.
//

#include "TileHighlightSystem.h"

#include "../../../../engine/core/ECS/TileRenderComponent.h"
#include "../../../../engine/core/ECS/TransformComponent.h"
#include "../components/TileGameplayComponent.h"
#include "../../../../engine/layer/entities/Camera.h"


void TileHighlightSystem::update(EntityManager &entityManager, const MousePicker& picker, const Camera& camera) {
    for (EntityID entityID : entityManager.getAllEntities()) {
        auto tileRenderComponent = entityManager.getComponent<TileRenderComponent>(entityID);
        auto transformComponent = entityManager.getComponent<TransformComponent>(entityID);
        auto tileGameplayComponent = entityManager.getComponent<TileGameplayComponent>(entityID);

        if (!tileRenderComponent || !transformComponent || !tileGameplayComponent) {
            continue;
        }

        glm::vec3 rayOrigin = camera.getPosition();
        glm::vec3 rayDirection = picker.getCurrentRay();
        glm::vec3 intersectionPoint;
        if (intersectTile(rayOrigin, rayDirection, transformComponent->position, tileGameplayComponent->radius, intersectionPoint)) {
            tileRenderComponent->isHighlighted = true;
        } else {
            tileRenderComponent->isHighlighted = false;
        }
    }
}

bool TileHighlightSystem::intersectTile(const glm::vec3 &rayOrigin, const glm::vec3 &rayDirection, glm::vec3 worldPos, float hexRadius, glm::vec3& intersectionPoint) {
    float t = -rayOrigin.y / rayDirection.y;
    if (t < 0) return false;

    intersectionPoint = rayOrigin + rayDirection * t;

    glm::vec2 diff(intersectionPoint.x - worldPos.x, intersectionPoint.z - worldPos.z);
    return glm::length(diff) <= hexRadius - 0.1f;
}
