#version 330 core
in vec2 vUV;
out vec4 FragColor;

uniform sampler2D uTex;
uniform vec2 uTexelSize;
uniform float uThreshold;
uniform float uIntensity;

const float weights[5] = float[](0.204164, 0.304005, 0.093913, 0.010381, 0.000336);

vec3 blur(vec2 uv, vec2 dir) {
    vec3 sum = vec3(0.0);
    for (int i = -4; i <= 4; ++i) {
        int index = abs(i);
        vec2 offset = dir * float(i);
        vec3 col = texture(uTex, uv + offset).rgb;

        float brightness = dot(col, vec3(0.2126, 0.7152, 0.0722)); // luminance
        float mask = smoothstep(uThreshold, uThreshold + 0.05, brightness);

        sum += col * mask * weights[index];
    }
    return sum;
}

void main() {
    vec3 color = texture(uTex, vUV).rgb;

    // Blur only bright pixels (thresholded inside blur)
    vec3 blurH = blur(vUV, vec2(uTexelSize.x, 0.0));
    vec3 blurV = blur(vUV, vec2(0.0, uTexelSize.y));
    vec3 bloom = (blurH + blurV) * 0.5 * uIntensity;

    // Final composition
    vec3 finalColor = color + bloom;

    FragColor = vec4(finalColor, 1.0);
}
