#version 440

layout(location = 0) in vec2 qt_TexCoord0;
layout(location = 0) out vec4 fragColor;

layout(std140, binding = 0) uniform buf {
    mat4 qt_Matrix;
    float qt_Opacity;
    float time;
    float warpStrength;
    float flowSpeed;
    float scale;
} ubuf;

layout(binding = 1) uniform sampler2D source;

// Smooth noise function for organic liquid movement
float noise(vec2 p) {
    return sin(p.x * 1.5) * sin(p.y * 1.5);
}

// Fractal noise for more complex patterns
float fbm(vec2 p) {
    float value = 0.0;
    float amplitude = 0.5;

    for(int i = 0; i < 4; i++) {
        value += amplitude * noise(p);
        p *= 2.0;
        amplitude *= 0.5;
    }
    return value;
}

void main() {
    vec2 uv = qt_TexCoord0;

    // Create flowing liquid-like distortion
    vec2 flowDir1 = vec2(
        fbm(uv * ubuf.scale + ubuf.time * ubuf.flowSpeed),
        fbm(uv * ubuf.scale + ubuf.time * ubuf.flowSpeed + 100.0)
    );

    vec2 flowDir2 = vec2(
        fbm(uv * ubuf.scale * 0.7 - ubuf.time * ubuf.flowSpeed * 0.8 + 200.0),
        fbm(uv * ubuf.scale * 0.7 - ubuf.time * ubuf.flowSpeed * 0.8 + 300.0)
    );

    // Combine flows for more organic movement
    vec2 finalFlow = (flowDir1 + flowDir2 * 0.5) * ubuf.warpStrength * 0.01;

    // Apply subtle chromatic aberration like Apple's effect
    float aberration = length(finalFlow) * 0.5;

    vec2 distortedUV = uv + finalFlow;

    // Sample with slight chromatic separation
    float r = texture(source, distortedUV + vec2(aberration, 0.0)).r;
    float g = texture(source, distortedUV).g;
    float b = texture(source, distortedUV - vec2(aberration, 0.0)).b;

    fragColor = vec4(r, g, b, 1.0) * ubuf.qt_Opacity;
}

