shader_type canvas_item;

// Your original target color detection
uniform vec4 target_color : source_color = vec4(0.0, 0.007, 0.939, 1.0);
uniform float color_tolerance : hint_range(0.0, 1.0) = 0.05; 

uniform sampler2D screen_texture : hint_screen_texture, repeat_disable, filter_nearest;

// New uniforms for the smooth rainbow edge effect
uniform float color_shift_intensity : hint_range(0.0, 0.2) = 0.08;
uniform float edge_rainbow_spread : hint_range(0.1, 5.0) = 2.0; 
uniform float shift_speed : hint_range(0.0, 5.0) = 1.0;
uniform float scanline_intensity : hint_range(0.0, 1.0) = 0.15;

void fragment() {
	vec4 original_screen_color = texture(screen_texture, SCREEN_UV);

	if (distance(original_screen_color.rgb, target_color.rgb) > color_tolerance) {
		COLOR = original_screen_color;
	} else {
		vec2 uv = SCREEN_UV;

		vec2 center_offset = uv - vec2(0.5);
		float dist_from_center = length(center_offset);

		float edge_factor = pow(dist_from_center, edge_rainbow_spread);

		float time_sin = sin(TIME * shift_speed) - 1.2;
		float time_cos = cos(TIME * shift_speed * 0.8) - 1.2;
		//float time_sin = sin(dist_from_center * shift_speed);
		//float time_cos = cos(dist_from_center * shift_speed * 0.8);
		//vec2 red_offset = center_offset * color_shift_intensity * edge_factor * time_sin;
		//vec2 blue_offset = center_offset * color_shift_intensity * edge_factor * -time_cos;
		//vec2 green_offset = center_offset * color_shift_intensity * edge_factor * (time_sin * 0.5);
		vec2 red_offset = vec2(0.1, 0.5) * color_shift_intensity * time_sin;
		vec2 blue_offset = vec2(-0.1, 0.5) * color_shift_intensity * -time_cos;
		vec2 green_offset = vec2(-0.1, -0.5) * color_shift_intensity * (time_sin);

		float r = texture(screen_texture, uv + red_offset).r;
		float g = texture(screen_texture, uv + green_offset).g;
		float b = texture(screen_texture, uv + blue_offset).b;

		vec4 final_color = vec4(r, g, b, 1.0);

		//float scanline = sin(uv.y * 400.0 - TIME * 2.0) * 0.2 + 1.;
		//final_color.rgb *= scanline * scanline_intensity; 

		COLOR = final_color;
	}
}