#version 330 core

uniform vec3 iResolution;
uniform float iTime;
uniform float uAlpha;

out vec4 FragColor;

void mainImage(out vec4 O, vec2 C) {
    float s,l,d,q,r,h=.08,t=iTime;
    vec4 c,p,x;
    
    for(
        vec2 R=iResolution.xy
        ; ++s<90.
        ; r+=.4*d
        ) {
        
        p = r*normalize(vec3(C-.5*R,R.y)).xyzx;
        
        // Chaotic movement - multiple time scales
        p.z += t*1.3;
        p.xy += vec2(sin(t*.7+p.z*.1),cos(t*.9+p.z*.15))*.3;
        
        q = round(p.z/h)*h;
        
        for(
            d=l=4.
            ; --l>=-3.
            ; d = min(d,max(
                // Twisted plasma tubes with electric arcs
                length(x.xy-vec2(
                    1.2*sin(.4*(q+h*l)+x.y*.3+sin(x.y*2.+t)*.2),
                    .8*cos(.6*(q+h*l)+x.x*.4+cos(x.x*1.5+t*1.1)*.3)
                ))-(.12+.08*sin(x.y*4.+q*8.+t*3.)),
                abs(x.y)-5.
            ))
            )
            x = p
            , x.z -= q
            // Multi-axis chaos rotation
            , x.xy *= mat2(cos(q*4.+h*l*3.+t*.5+vec4(0,11,33,0)))
            , x.yz *= mat2(cos(q*2.+t*.3+vec4(0,11,33,0)))
            , x.xz *= mat2(cos(q*1.5+h*l+t*.7+vec4(0,11,33,0)))
            // Plasma distortion
            , x.x += .1*sin(x.y*6.+t*2.)
            , x.y += .08*cos(x.x*8.+t*2.5)
            ;
        
        d = abs(d)+1E-3;
        
        // Multi-frequency plasma colors with electric effects
        vec4 plasma1 = 1.+sin(4.*length(p.xy)+p.z*2.+vec4(0,1,2,3)-t*4.);
        vec4 plasma2 = 1.+sin(8.*length(p.xy)+p.z*4.+vec4(.5,1.5,2.5,0)-t*6.);
        vec4 plasma3 = 1.+sin(12.*length(p.xy)+p.z*1.+vec4(1,2,3,0)-t*8.);
        
        // Toned down lightning intensity
        float lightning = 1.+.8*sin(16.*length(p.xy)+p.z*8.+sin(p.z*20.+t*10.)*.5);
        
        // Combine plasma layers
        p = (plasma1*1.2 + plasma2*.8 + plasma3*.6) * lightning;
        
        // Reduced electric storm accumulation
        c += p.w/(d+.02)*p*.2;
    }
    
    // Milder tone mapping - less aggressive glow
    O = tanh(c/5E3);
}

void main()
{
    vec4 O;
    mainImage(O, gl_FragCoord.xy);
    O.a *= uAlpha;
    FragColor = O;
}
