#version 330 core

in vec2 TexCoord;
flat in int TexIndex;
out vec4 FragColor;

uniform sampler2D Texture0;
uniform sampler2D Texture1;
uniform sampler2D Texture2;
uniform sampler2D Texture3;

uniform float u_time;
uniform float u_battery;
uniform vec2 u_resolution;

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

float hash(vec2 p) {
    p = fract(p * vec2(123.34, 456.21));
    p += dot(p, p + 45.32);
    return fract(p.x * p.y);
}

void main()
{
    vec4 texColor;
    switch (TexIndex) {
        case 0: texColor = texture(Texture0, TexCoord); break;
        case 1: texColor = texture(Texture1, TexCoord); break;
        case 2: texColor = texture(Texture2, TexCoord); break;
        case 3: texColor = texture(Texture3, TexCoord); break;
        default: texColor = vec4(1.0, 0.0, 0.0, 1.0); break;
    }

	if (TexIndex == 1) {
		vec2 uv = gl_FragCoord.xy / u_resolution.xy;
		uv.x *= u_resolution.x / u_resolution.y;
		float blockSize = 6.0;
		float strength =  1.0 - u_battery;

		vec2 blockUV = floor(gl_FragCoord.xy / blockSize);
		float noise = hash(blockUV + vec2(u_time * 3.0, u_time * 7.0));
		float noise2 = hash(blockUV + vec2(u_time * 13.0, u_time * 3.0));
		float noise3 = hash(blockUV + vec2(u_time * 17.0, u_time * 13.0));

		// Horizontal bands
		noise *= 0.9 + 0.1 * sin(uv.y * 400.0);
		noise2 *= 0.9 + 0.1 * sin(uv.y * 400.0);
		noise3 *= 0.9 + 0.1 * sin(uv.y * 400.0);

		float offset = 0.001 / (u_battery * u_battery + 0.001 );
		float r = texture(Texture1, TexCoord + vec2(offset * 5, 0.0)).r;
		float g = texture(Texture1, TexCoord + vec2(0.0, offset * 2.0)).g;
		float b = texture(Texture1, TexCoord - vec2(offset, 0.0)).b;
		vec3 color = vec3(r, g, b);

		vec3 noisyColor = mix(color.rgb, vec3(noise, noise2, noise3), strength / 2);
		// float flicker = 0.75 + sin(u_time * 6.0 + sin(u_time * 3)) * 0.25;
		float flicker = 0.75 + 0.25 * sin(u_time + sin(u_time * 7.0));

		FragColor = vec4(noisyColor, texColor.a * flicker);
	} else {
		FragColor = texColor;
	}
}

