// line_renderer.cpp - Implementación de renderizado de líneas (SDL3 GPU)
// © 2026 JailDesigner

#include "core/rendering/line_renderer.hpp"

#include "core/defaults.hpp"
#include "core/defaults/effects.hpp"

namespace Rendering {

    // Grosor global por defecto. Configurable via setLineThickness.
    float g_current_line_thickness = Defaults::Rendering::LINE_THICKNESS_DEFAULT;

    void linea(Renderer* renderer,
        int x1,
        int y1,
        int x2,
        int y2,
        float brightness,
        float thickness,
        SDL_Color color,
        float alpha) {
        if (renderer == nullptr) {
            return;
        }

        // Coords lógicas (1280×720). El shader hace el mapeo a NDC; el viewport
        // del SDLManager hace el letterbox a píxeles físicos.
        const auto FX1 = static_cast<float>(x1);
        const auto FY1 = static_cast<float>(y1);
        const auto FX2 = static_cast<float>(x2);
        const auto FY2 = static_cast<float>(y2);

        // color.alpha==0 → fallback a DEFAULT_LINE_COLOR (verd fòsfor). alpha>0 → color directo.
        const SDL_Color SOURCE = (color.a > 0) ? color : DEFAULT_LINE_COLOR;
        const float R = (static_cast<float>(SOURCE.r) * brightness) / 255.0F;
        const float G = (static_cast<float>(SOURCE.g) * brightness) / 255.0F;
        const float B = (static_cast<float>(SOURCE.b) * brightness) / 255.0F;

        const float W = (thickness > 0.0F) ? thickness : g_current_line_thickness;

        renderer->pushLine(FX1, FY1, FX2, FY2, W, R, G, B, alpha);
    }

    void lineaGlow(Renderer* renderer,
        int x1,
        int y1,
        int x2,
        int y2,
        float brightness,
        float thickness,
        SDL_Color color,
        SDL_Color glow_color) {
        // Color dels passes de halo: si glow_color té alpha>0, l'usem;
        // altrament fem servir el color de la línia.
        const SDL_Color HALO_COLOR = (glow_color.a > 0) ? glow_color : color;

        for (const auto& pass : Defaults::FX::Glow::Line::PASSES) {
            const bool IS_CORE = pass.thickness < 0.0F;
            const float PASS_T = IS_CORE ? thickness : pass.thickness;
            const SDL_Color PASS_C = IS_CORE ? color : HALO_COLOR;
            linea(renderer, x1, y1, x2, y2, brightness, PASS_T, PASS_C, pass.alpha);
        }
    }

    void setLineThickness(float thickness) {
        if (thickness > 0.0F) {
            g_current_line_thickness = thickness;
        }
    }

    auto getLineThickness() -> float { return g_current_line_thickness; }

}  // namespace Rendering
