// floating_score_manager.cpp - Implementació del gestor de números flotantes
// © 2026 JailDesigner

#include "floating_score_manager.hpp"

#include <string>

namespace Effects {

    FloatingScoreManager::FloatingScoreManager(Rendering::Renderer* renderer)
        : text_(renderer) {
        // Inicialitzar todos los slots como inactius
        for (auto& pf : pool_) {
            pf.active = false;
        }
    }

    void FloatingScoreManager::crear(int points, const Vec2& position) {
        // 1. Trobar slot lliure
        FloatingScore* pf = findFreeSlot();
        if (pf == nullptr) {
            return;  // Pool ple (improbable)
        }

        // 2. Inicialitzar puntuación flotante
        pf->text = std::to_string(points);
        pf->position = position;
        pf->velocity = {.x = Defaults::FloatingScore::VELOCITY_X,
            .y = Defaults::FloatingScore::VELOCITY_Y};
        pf->elapsed_time = 0.0F;
        pf->max_lifetime = Defaults::FloatingScore::LIFETIME;
        pf->brightness = 1.0F;
        pf->active = true;
    }

    void FloatingScoreManager::update(float delta_time) {
        for (auto& pf : pool_) {
            if (!pf.active) {
                continue;
            }

            // 1. Actualitzar posición (deriva sin amunt)
            pf.position.x += pf.velocity.x * delta_time;
            pf.position.y += pf.velocity.y * delta_time;

            // 2. Actualitzar time de vida
            pf.elapsed_time += delta_time;

            // 3. Calcular brightness (fade lineal)
            float progress = pf.elapsed_time / pf.max_lifetime;  // 0.0 → 1.0
            pf.brightness = 1.0F - progress;                     // 1.0 → 0.0

            // 4. Desactivar cuando acaba el time
            if (pf.elapsed_time >= pf.max_lifetime) {
                pf.active = false;
            }
        }
    }

    void FloatingScoreManager::draw() {
        for (const auto& pf : pool_) {
            if (!pf.active) {
                continue;
            }

            // Renderizar centrat con brightness (fade)
            constexpr float SCALE = Defaults::FloatingScore::SCALE;
            constexpr float SPACING = Defaults::FloatingScore::SPACING;

            text_.renderCentered(pf.text, pf.position, SCALE, SPACING, pf.brightness);
        }
    }

    void FloatingScoreManager::reset() {
        for (auto& pf : pool_) {
            pf.active = false;
        }
    }

    auto FloatingScoreManager::getActiveCount() const -> int {
        int count = 0;
        for (const auto& pf : pool_) {
            if (pf.active) {
                count++;
            }
        }
        return count;
    }

    auto FloatingScoreManager::findFreeSlot() -> FloatingScore* {
        for (auto& pf : pool_) {
            if (!pf.active) {
                return &pf;
            }
        }
        return nullptr;  // Pool ple
    }

}  // namespace Effects
