/*
  Post-Rain Rainbow
  Draws a rainbow arc opposite the sun when rain is clearing and the sun is out.
  Real rainbows appear at ~42 degrees from the anti-solar point.
*/

#ifdef OVERWORLD

vec3 GetRainbowColor(float angle) {
    // Map the angle offset from the rainbow band center into a 0-1 parameter
    // and produce a smooth spectral gradient (red outside, violet inside)
    float t = clamp(angle, 0.0, 1.0);

    // Spectral colors: red -> orange -> yellow -> green -> cyan -> blue -> violet
    vec3 col;
    if (t < 0.167) {
        col = mix(vec3(1.0, 0.0, 0.2), vec3(1.0, 0.35, 0.0), t / 0.167);
    } else if (t < 0.333) {
        col = mix(vec3(1.0, 0.35, 0.0), vec3(1.0, 0.85, 0.0), (t - 0.167) / 0.167);
    } else if (t < 0.5) {
        col = mix(vec3(1.0, 0.85, 0.0), vec3(0.15, 0.9, 0.15), (t - 0.333) / 0.167);
    } else if (t < 0.667) {
        col = mix(vec3(0.15, 0.9, 0.15), vec3(0.0, 0.75, 0.9), (t - 0.5) / 0.167);
    } else if (t < 0.833) {
        col = mix(vec3(0.0, 0.75, 0.9), vec3(0.2, 0.3, 1.0), (t - 0.667) / 0.167);
    } else {
        col = mix(vec3(0.2, 0.3, 1.0), vec3(0.5, 0.15, 0.8), (t - 0.833) / 0.167);
    }

    return col;
}

void DrawRainbow(inout vec3 color, vec3 viewPos) {
    vec3 nViewPos = normalize(viewPos);

    // Anti-solar point: opposite the sun direction
    // lightVec points toward the active light source (sun during day)
    vec3 antiSolar = -lightVec;

    // Angle between view direction and anti-solar point
    float VoA = dot(nViewPos, antiSolar);
    float angle = acos(clamp(VoA, -1.0, 1.0));

    // Primary rainbow at ~42 degrees (0.733 radians)
    float rainbowAngle = 0.733;
    float bandWidth = 0.025;

    float dist = abs(angle - rainbowAngle);

    // Only draw if within the rainbow band
    if (dist > bandWidth * 1.5) return;

    // Map position within band to spectral parameter (0 = inner/violet, 1 = outer/red)
    float spectralPos = (angle - rainbowAngle + bandWidth) / (2.0 * bandWidth);
    spectralPos = clamp(spectralPos, 0.0, 1.0);

    // Soft edges
    float bandFade = 1.0 - smoothstep(bandWidth * 0.7, bandWidth * 1.5, dist);

    // Rainbow is only visible above the horizon
    float VoU = dot(nViewPos, upVec);
    float horizonFade = smoothstep(-0.02, 0.08, VoU);

    // Visibility: need sun AND wetness (rain recently ended or ending)
    // Rainbow appears when rain is clearing: low rainStrength, high wetness
    float rainbowVisibility = smoothstep(0.0, 0.3, wetness) *
                              smoothstep(0.8, 0.2, rainStrength) *
                              sunVisibility;

    // Fade the rainbow based on how much sun vs rain there is
    float intensity = bandFade * horizonFade * rainbowVisibility * RAINBOW_BRIGHTNESS;

    vec3 rainbowCol = GetRainbowColor(spectralPos);

    // Additive blend — rainbow glows over the sky
    color += rainbowCol * intensity * 0.06;
}

#endif
