/*
  End Void Lightning
  Rare, brief arcs of energy across the End sky.
  Uses time-based hashing to create infrequent flashes with
  branching bolt shapes and brief afterglow.
*/

#ifdef END

float EndBoltShape(vec2 coord, vec2 start, vec2 end, float seed) {
    vec2 dir = end - start;
    float len = length(dir);
    vec2 nDir = dir / max(len, 0.001);

    vec2 toPoint = coord - start;
    float t = clamp(dot(toPoint, nDir) / len, 0.0, 1.0);

    // Jagged displacement for bolt shape
    float jag = sin(t * 25.0 + seed * 10.0) * 0.012
              + sin(t * 55.0 - seed * 7.0)  * 0.005
              + sin(t * 120.0 + seed * 3.0) * 0.002;

    vec2 perp = vec2(-nDir.y, nDir.x);
    vec2 boltPos = start + nDir * t * len + perp * jag;

    float dist = length(coord - boltPos);

    // Tight core + modest glow — no wide ambient
    float core = exp(-dist * dist * 15000.0);
    float glow = exp(-dist * dist * 1500.0) * 0.35;

    return core + glow;
}

vec3 DrawEndLightning(vec3 viewPos, float dither) {
    vec3 nViewPos = normalize(viewPos);
    float VoU = dot(nViewPos, upVec);

    if (VoU < -0.1) return vec3(0.0);
    float vertFade = smoothstep(-0.1, 0.1, VoU);

    vec4 worldPos = gbufferModelViewInverse * vec4(nViewPos, 0.0);
    vec3 wDir = normalize(worldPos.xyz);

    vec2 skyCoord = wDir.xz / (abs(wDir.y) + 0.15);

    // Event timing
    float eventPeriod = END_LIGHTNING_INTERVAL;
    float eventSlot = floor(frametime / eventPeriod);
    float eventPhase = fract(frametime / eventPeriod);

    // Chance roll per slot
    float eventHash = fract(sin(eventSlot * 127.1) * 43758.5453);
    if (eventHash > END_LIGHTNING_CHANCE) return vec3(0.0);

    // Very brief flash — about 0.15 seconds at default interval
    float flashTime = eventPhase * eventPeriod; // time in seconds within this slot
    float flash = smoothstep(0.0, 0.02, flashTime) * smoothstep(0.15, 0.03, flashTime);

    if (flash < 0.001) return vec3(0.0);

    // Bolt position — random per event
    float h1 = fract(sin(eventSlot * 311.7) * 43758.5453);
    float h2 = fract(sin(eventSlot * 183.3) * 43758.5453);
    float h3 = fract(sin(eventSlot * 419.2) * 43758.5453);
    float h4 = fract(sin(eventSlot * 547.1) * 43758.5453);

    vec2 boltStart = vec2(h1 * 4.0 - 2.0, h2 * 2.0 - 1.0);
    vec2 boltEnd = boltStart + vec2(h3 * 1.5 - 0.75, h4 * 1.0 - 0.5);

    float bolt = EndBoltShape(skyCoord, boltStart, boltEnd, eventHash);

    // Optional branch
    float h5 = fract(sin(eventSlot * 673.3) * 43758.5453);
    if (h5 > 0.5) {
        vec2 branchStart = mix(boltStart, boltEnd, 0.3 + h5 * 0.3);
        vec2 branchEnd = branchStart + vec2(h4 * 0.5 - 0.25, h3 * 0.3 - 0.15);
        bolt += EndBoltShape(skyCoord, branchStart, branchEnd, eventHash + 1.0) * 0.5;
    }

    // Color
    vec3 boltColor = mix(vec3(0.85, 0.75, 1.0), endRiftCol * 1.5, 0.3);

    vec3 lightning = boltColor * bolt * flash * vertFade * END_LIGHTNING_BRIGHTNESS;

    return lightning * 0.15;
}

#endif
