in vec2 texCoord;
out vec4 fragColor;

uniform sampler2D texture0;
uniform float w;
uniform float h;
uniform float vignetteAmount;
uniform float vignetteStart;
uniform float vignetteEnd;
uniform float fillBorders; // 0.0 = black, 1.0 = stretched pillar blur

#define DEFAULT_W 16.0
#define DEFAULT_H 9.0

void main()
{
    float baseAspect = DEFAULT_W / DEFAULT_H;
    float targetAspect = (w > 0.0 && h > 0.0) ? (w / h) : baseAspect;

    vec2 halfVisibleSize = vec2(0.5, 0.5);
    float barsAlpha = 0.0;
    bool isInBorder = false;
    vec2 borderUv = texCoord;

    // Always use vertical bars (left/right sides) for pillar blur
    float visibleWidth = targetAspect / baseAspect;
    float halfVisibleWidth = visibleWidth * 0.5;
    halfVisibleSize.x = halfVisibleWidth;
    
    // Check if we're in the side border area
    if (abs(texCoord.x - 0.5) > halfVisibleWidth) {
        barsAlpha = 1.0;
        isInBorder = true;
        // Clamp to edge and stretch vertically
        float edgeX = texCoord.x < 0.5 ? (0.5 - halfVisibleWidth) : (0.5 + halfVisibleWidth);
        borderUv = vec2(edgeX, texCoord.y);
    }

    vec2 fakeUv = (texCoord - 0.5) / halfVisibleSize;
    float vignetteRadius = length(fakeUv);
    float vignetteAlpha = smoothstep(vignetteStart, vignetteEnd, vignetteRadius) * vignetteAmount * (1.0 - barsAlpha);

    if (isInBorder && fillBorders > 0.5) {
        // Sample and blur the border area
        vec4 borderColor = vec4(0.0);
        float blurSize = 0.005;
        int samples = 3;
        
        for (int i = -samples; i <= samples; i++) {
            for (int j = -samples; j <= samples; j++) {
                vec2 offset = vec2(float(i), float(j)) * blurSize;
                borderColor += texture(texture0, borderUv + offset);
            }
        }
        
        float totalSamples = float((samples * 2 + 1) * (samples * 2 + 1));
        borderColor /= totalSamples;
        borderColor.rgb *= 0.4; // Darken the stretched area
        borderColor.a = 1.0; // Fully opaque
        
        fragColor = borderColor;
    } else if (isInBorder) {
        // Black borders when fillBorders is disabled
        fragColor = vec4(0.0, 0.0, 0.0, 1.0);
    } else {
        // Pass through original texture with optional vignette
        vec4 originalColor = texture(texture0, texCoord);
        fragColor = mix(originalColor, vec4(0.0, 0.0, 0.0, 1.0), vignetteAlpha);
    }
}
