#version 300 es

precision highp float;

uniform sampler2D uPassTex;
uniform sampler2D uMainTex;
uniform float uRate;
uniform float u_aspect_ratio;

in vec2 vUV;
in vec2 vRevUV;

out vec4 fragColor;

// Rounded Rectangle SDF
float roundedRectSDF(vec2 p, vec2 size, float r) {
    vec2 pp = vec2(p.x * u_aspect_ratio, p.y);
    vec2 d = abs(pp) - size;
    return length(max(d, 0.0)) - r;
}

// Rounded Rectangle SDF
float circleSDF(vec2 p, float r) {
    return length(vec2(p.x * u_aspect_ratio, p.y)) - r;
}

// Highlight effect structure
struct HighlightResult {
    vec3 color;
    float edge_weight;
};

// Calculate highlight effect
HighlightResult calculate_highlight(vec2 uv, float dist, vec2 center, float time) {
    HighlightResult result;
    float highlight_width = 0.01;
    float highlight_falloff = 2.0;
    vec2 to_light = normalize(vec2(cos(time), sin(time)));
    result.edge_weight = smoothstep(-highlight_width, highlight_width * 0.1, dist);
    result.edge_weight *= result.edge_weight;

    vec2 self_dir = normalize(uv - center);
    float dot_light = dot(self_dir, to_light);
    float angle_falloff = 2.0;
    float side_weight = mix(0.5, 1.0, (dot_light + 1.0) * 0.5);
    float light_weight = abs(dot_light) * side_weight;

    float highlight_intensity = 1.5;
    result.color = mix(vec3(0.7), vec3(1.0), light_weight * highlight_intensity);

    float edge_falloff = 0.5;
    result.edge_weight *= mix(0.5, 1.0, (dot_light + 1.0) * 0.5);
    result.edge_weight *= mix(0.2, 1.0, abs(dot_light));

    return result;
}

void main()
{

    vec2 pos = vec2(0.5 * uRate, 0.5);

    // Calculate rounded rectangle SDF with aspect ratio correction
    vec2 size = vec2(0.37 * u_aspect_ratio, 0.03); // Adjust height for aspect ratio
    float radius = 0.15;
    //float radius = 0.03;
    //float dist = roundedRectSDF(vUV - pos, size, radius);
    float dist = circleSDF(vUV - pos, radius);



    // Calculate highlight
    HighlightResult highlight = calculate_highlight(vUV, dist, vec2(pos.x, pos.y), 150.0);

    vec4 blurCol = texture(uPassTex, vRevUV);
    vec4 bgCol = texture(uMainTex, vUV);

    dist = smoothstep(0.001, -0.001, dist);


    // Mix color with highlight
    vec3 circle_color = mix(blurCol.rgb, highlight.color, highlight.edge_weight);

    blurCol.rgb = mix(blurCol.rgb, circle_color, dist);


    fragColor = mix(bgCol, blurCol, dist);
}