#include "native_ui/radar_hud.hpp"

#include <cmath>
#include <algorithm>

namespace poe2::ui {

RadarLayout RadarHud::ComputeLayout(
    const std::vector<PoiSharedEntity>& pois,
    float playerWorldX,
    float playerWorldZ,
    float playerAngleDeg,
    int screenW,
    int screenH,
    int radarRadius,
    float maxRadarDistance
) {
    RadarLayout layout;
    layout.radius = radarRadius;

    // Đặt tâm Radar tại góc trên bên phải màn hình (cạnh góc Minimap chuẩn PoE)
    int cx = (screenW > 0) ? (screenW - radarRadius - 40) : (radarRadius + 40);
    int cy = radarRadius + 40;
    layout.center = Point{cx, cy};

    float rad = playerAngleDeg * (3.14159265358979323846f / 180.0f);
    float cosA = std::cos(rad);
    float sinA = std::sin(rad);

    float scale = (maxRadarDistance > 0.0f) ? (static_cast<float>(radarRadius) / maxRadarDistance) : 0.1f;

    for (const auto& poi : pois) {
        float dx = poi.world_x - playerWorldX;
        float dz = poi.world_z - playerWorldZ;
        float dist = std::sqrt(dx * dx + dz * dz);

        // Xoay vector hướng theo góc nhìn của Camera / Nhân vật
        float rotX = dx * cosA - dz * sinA;
        float rotZ = dx * sinA + dz * cosA;

        float mappedDist = dist * scale;
        bool isClamped = false;
        if (mappedDist > static_cast<float>(radarRadius - 10)) {
            mappedDist = static_cast<float>(radarRadius - 10);
            isClamped = true;
        }

        float normX = (dist > 0.0001f) ? (rotX / dist) : 0.0f;
        float normZ = (dist > 0.0001f) ? (rotZ / dist) : 0.0f;

        int mx = cx + static_cast<int>(normX * mappedDist);
        int my = cy - static_cast<int>(normZ * mappedDist); // Trục Y đảo ngược trên màn hình 2D

        RadarMarker marker;
        marker.screenX = mx;
        marker.screenY = my;
        marker.isClampedToBorder = isClamped;
        marker.label = poi.name;

        PoiType t = static_cast<PoiType>(poi.type);
        switch (t) {
            case PoiType::Boss:
                marker.color = colors::BrickRed;
                marker.symbol = "BOSS";
                layout.bossCount++;
                break;
            case PoiType::Strongbox:
                marker.color = colors::CyanStrongbox;
                marker.symbol = "BOX";
                layout.strongboxCount++;
                break;
            case PoiType::Shrine:
                marker.color = colors::YellowWarning;
                marker.symbol = "SHRINE";
                layout.shrineCount++;
                break;
            default:
                marker.color = colors::RewardGreen;
                marker.symbol = "POI";
                break;
        }

        layout.markers.push_back(std::move(marker));
    }

    return layout;
}

} // namespace poe2::ui
