#version 330 core
out vec4 FragColor;
uniform sampler2D iChannel0;
uniform vec3 iResolution;
uniform float iTime;
uniform float uAlpha;
uniform float uStartDelay;

float rand(vec2 co){ return fract(sin(dot(co.xy, vec2(12.9898,78.233))) * 43758.5453); }

void mainImage(out vec4 fragColor, in vec2 fragCoord)
{
    vec2 uv = fragCoord.xy / iResolution.xy;

    vec3 orig = texture(iChannel0, uv).rgb;

    // passthrough before startDelay
    if (iTime < uStartDelay)
    {
        fragColor = vec4(orig, 1.0);
        return;
    }

    float t = iTime * 0.5;
    // chroma offset in texture-space: scale by 1/width to convert px->uv
    float off = sin(uv.y * 50.0 + t * 5.0) * (4.0 / iResolution.x);

    vec3 col;
    col.r = texture(iChannel0, uv + vec2(off, 0.0)).r;
    col.g = texture(iChannel0, uv).g;
    col.b = texture(iChannel0, uv - vec2(off, 0.0)).b;

    // scanline: use pixel coordinate (fragCoord.y)
    float scan = sin(fragCoord.y * 1.5) * 0.04;
    col -= scan;

    // noise
    float n = rand(uv + iTime);
    col += (n - 0.5) * 0.05;

    // mix processed effect over original using uAlpha as blend factor
    vec3 outcol = mix(orig, col, clamp(uAlpha, 0.0, 1.0));
    fragColor = vec4(outcol, 1.0);
}

void main()
{
    mainImage(FragColor, gl_FragCoord.xy);
}