#version 300 es
precision highp float;
precision highp int;

uniform vec2 uResolution;
uniform float uTime;
uniform float uOpen;
uniform int uLightMode;
uniform int uCamMode;

out vec4 fragColor;

// ============================================================================
// 07_sakura_pink_healing_blossom.glsl
// Graceful 3D SAKURA ROSE-PINK & PEARL-WHITE stylized cel-shaded healing
// blossom vortex hovering above a dark matte ink-grouted charcoal tiled arena
// floor:
//   - Sculpted multi-tiered ink-outlined sakura rose bloom at center
//   - 3 sweeping S-curved pearl-pink cel-shaded energy ribbons + wisps
//   - 6 orbiting stylized 5-petal notched cherry blossoms + drifting petals
//   - Crisp warm cream-gold 4-point comic star sparkles
//   - 3-second seamless animation loop (`uTime`), bloom expansion (`uOpen`)
// ============================================================================

const float PI  = 3.14159265359;
const float TAU = 6.28318530718;

// Stylized Sakura & Ink Palette (linear space; gamma 2.2 encoded at output)
const vec3 COL_FLOOR_BASE   = vec3(0.08, 0.09, 0.12);
const vec3 COL_INK          = vec3(0.004, 0.003, 0.006);
const vec3 COL_ROSE_INK     = vec3(0.048, 0.006, 0.020);
const vec3 COL_SAKURA_DEEP  = vec3(0.66, 0.07, 0.25);
const vec3 COL_SAKURA_MID   = vec3(0.95, 0.26, 0.46);
const vec3 COL_SAKURA_LIGHT = vec3(1.00, 0.60, 0.74);
const vec3 COL_PEARL_SHADOW = vec3(0.54, 0.38, 0.48);
const vec3 COL_PEARL_WHITE  = vec3(0.98, 0.94, 0.88);
const vec3 COL_CREAM_GOLD   = vec3(1.00, 0.88, 0.56);
const vec3 COL_WARM_GOLD    = vec3(0.96, 0.64, 0.18);

// Material IDs
const float MAT_FLOOR   = 1.0;
const float MAT_ROSE    = 2.0;
const float MAT_RIBBON  = 3.0;
const float MAT_BLOSSOM = 4.0;
const float MAT_PETAL   = 5.0;

// Smooth 3-second loop phase in [0, 1)
float loopPhase() {
    return fract(uTime / 3.0);
}

mat2 rot2(float a) {
    float c = cos(a), s = sin(a);
    return mat2(c, -s, s, c);
}

vec3 safeNormalize(vec3 v) {
    return v / max(length(v), 1e-5);
}

float hash21(vec2 p) {
    vec3 p3 = fract(vec3(p.xyx) * 0.1031);
    p3 += dot(p3, p3.yzx + 33.33);
    return fract((p3.x + p3.y) * p3.z);
}

float vnoise2(vec2 p) {
    vec2 i = floor(p);
    vec2 f = fract(p);
    vec2 u = f * f * (3.0 - 2.0 * f);
    float a = hash21(i);
    float b = hash21(i + vec2(1.0, 0.0));
    float c = hash21(i + vec2(0.0, 1.0));
    float d = hash21(i + vec2(1.0, 1.0));
    return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}

float fbm2(vec2 p) {
    float v = 0.0;
    float a = 0.5;
    for (int i = 0; i < 3; i++) {
        v += a * vnoise2(p);
        p = p * 2.03 + vec2(17.1, 31.7);
        a *= 0.5;
    }
    return v;
}

float smin(float a, float b, float k) {
    float h = max(k - abs(a - b), 0.0) / max(k, 1e-5);
    return min(a, b) - h * h * k * 0.25;
}

// Quantized 3-band stylized cel shading helper
float cel3(float ndl) {
    float b1 = smoothstep(0.06, 0.12, ndl);
    float b2 = smoothstep(0.48, 0.54, ndl);
    return 0.28 + 0.38 * b1 + 0.34 * b2;
}

// ============================================================================
// SCULPTED LAYERED SAKURA ROSE BLOOM SDF
// ============================================================================

struct RoseEval {
    float d;
    float tier;      // 0 = outer pearl, 1 = mid rose, 2 = inner rose, 3 = spiral heart
    float crease;    // 0..1 petal seam / ink crease mask
    float radial;    // 0..1 radial position along petal
};

// Single sculpted cupped rose petal ring using N-fold angular repetition
vec3 evalPetalRing(
    vec3 p,
    float nPetals,
    float angleOffset,
    float baseR,
    float petalLen,
    float petalWidth,
    float tiltAngle,
    float cupDepth,
    float thickness
) {
    float ang = atan(p.z, p.x) + angleOffset;
    float sector = TAU / nPetals;
    float localAng = mod(ang + 0.5 * sector, sector) - 0.5 * sector;
    float r = length(p.xz);

    // Local coordinates along the petal (u = radial out, v = across width, w = normal/height)
    vec2 q = vec2(r * cos(localAng) - baseR, r * sin(localAng));
    float t = clamp(q.x / max(petalLen, 1e-4), 0.0, 1.0);

    // Sculpted teardrop / rounded-notched petal silhouette
    float widthProfile = sin(pow(t, 0.72) * PI);
    // Subtle organic wave along outer rim
    float rimNotch = 1.0 - 0.14 * exp(-pow(q.y / max(petalWidth * 0.22, 1e-4), 2.0)) * smoothstep(0.65, 1.0, t);
    float halfW = petalWidth * widthProfile * rimNotch;

    // Cupped upward curve along petal length + concave bowl across width
    float yCurve = sin(t * PI * 0.62) * petalLen * sin(tiltAngle)
                 + cupDepth * (q.y * q.y) / max(petalWidth * petalWidth, 1e-4);

    // Signed distance to curved thin petal shell
    float dy = p.y - yCurve;
    float dx = max(q.x - petalLen * rimNotch, -q.x);
    float dz = abs(q.y) - halfW;
    float dPlanar = length(max(vec2(dx, dz), 0.0)) + min(max(dx, dz), 0.0);
    float d = length(max(vec2(dPlanar, abs(dy) - thickness), 0.0))
            + min(max(dPlanar, abs(dy) - thickness), 0.0);

    // Crease mask near petal outer rim and between adjacent petals
    float edgeMask = smoothstep(0.055, 0.008, abs(dPlanar));
    return vec3(d * 0.78, edgeMask, t);
}

RoseEval evalRoseBloom(vec3 pWorld, float openAmt, float phase) {
    RoseEval res;
    res.d = 1e5;
    res.tier = 0.0;
    res.crease = 0.0;
    res.radial = 0.0;

    // Hover center with gentle breathing bob
    float bob = 0.035 * sin(phase * TAU);
    vec3 p = pWorld - vec3(0.0, 0.58 + bob, 0.0);
    // Slight slow graceful twist (seamless 3s oscillation)
    float gentleTwist = 0.10 * sin(phase * TAU);
    p.xz = rot2(gentleTwist) * p.xz;

    // Bounding sphere quick-out
    float scale = mix(0.78, 1.08, openAmt);
    float dBound = length(p) - 1.35 * scale;
    if (dBound > 0.35) {
        res.d = dBound;
        return res;
    }

    p /= scale;
    float bloomSpread = mix(0.68, 1.05, openAmt);

    // Tier 0: Outer broad pearl-white petals (7 petals, low wide sweep)
    vec3 r0 = evalPetalRing(
        p - vec3(0.0, -0.06, 0.0),
        7.0, 0.18,
        0.34, 0.62 * bloomSpread, 0.30,
        0.24, 0.08, 0.042
    );
    res.d = r0.x;
    res.tier = 0.0;
    res.crease = r0.y;
    res.radial = r0.z;

    // Tier 1: Mid-outer rose-pink sculpted petals (7 petals, staggered)
    vec3 r1 = evalPetalRing(
        p - vec3(0.0, 0.02, 0.0),
        7.0, 0.18 + PI / 7.0,
        0.22, 0.50 * bloomSpread, 0.25,
        0.48, 0.10, 0.038
    );
    if (r1.x < res.d) {
        res.d = r1.x;
        res.tier = 1.0;
        res.crease = r1.y;
        res.radial = r1.z;
    } else if (abs(r1.x - res.d) < 0.028) {
        res.crease = max(res.crease, 0.85);
    }

    // Tier 2: Mid-inner rose-pink cupped petals (6 petals, upright)
    vec3 r2 = evalPetalRing(
        p - vec3(0.0, 0.09, 0.0),
        6.0, 0.55,
        0.13, 0.34 * bloomSpread, 0.19,
        0.74, 0.11, 0.034
    );
    if (r2.x < res.d) {
        res.d = r2.x;
        res.tier = 2.0;
        res.crease = r2.y;
        res.radial = r2.z;
    } else if (abs(r2.x - res.d) < 0.026) {
        res.crease = max(res.crease, 0.85);
    }

    // Tier 3: Tightly spiraling rose heart dome
    vec3 ph = p - vec3(0.0, 0.17, 0.0);
    float rh = length(ph.xz);
    float ah = atan(ph.z, ph.x);
    // Logarithmic spiral ridge for the iconic rose swirl
    float spiralArg = ah + 5.8 * log(max(rh + 0.045, 0.045)) - 0.35 * sin(phase * TAU);
    float spiralWave = 0.5 + 0.5 * sin(spiralArg * 2.0);
    float heartR = 0.25 * mix(0.85, 1.05, openAmt);
    vec3 qh = ph / vec3(heartR, heartR * 0.78, heartR);
    float dHeart = (length(qh) - 1.0) * heartR * 0.75 - 0.018 * spiralWave * smoothstep(0.28, 0.04, rh);
    float spiralInk = smoothstep(0.16, 0.03, abs(fract(spiralArg / PI) - 0.5))
                    * smoothstep(0.26, 0.05, rh)
                    * smoothstep(0.015, 0.05, rh);

    if (dHeart < res.d) {
        res.d = dHeart;
        res.tier = 3.0;
        res.crease = max(spiralInk, smoothstep(0.04, 0.0, abs(dHeart - r2.x)));
        res.radial = clamp(rh / max(heartR, 1e-4), 0.0, 1.0);
    } else if (abs(dHeart - res.d) < 0.022) {
        res.crease = max(res.crease, 0.85);
    }

    res.d *= scale;
    return res;
}

// ============================================================================
// 3 SWEEPING S-CURVED PEARL-PINK ENERGY RIBBONS SDF
// ============================================================================

struct RibbonEval {
    float d;
    float u;      // 0..1 along ribbon from inner root to sweeping outer tip
    float v;      // -1..1 across ribbon width
    float id;     // ribbon index 0..2
};

RibbonEval evalRibbons(vec3 pWorld, float openAmt, float phase) {
    RibbonEval res;
    res.d = 1e5;
    res.u = 0.0;
    res.v = 0.0;
    res.id = 0.0;

    // Quick bounding cylinder check
    float rXZ = length(pWorld.xz);
    float yRel = pWorld.y - 0.65;
    if (rXZ > 4.6 || abs(yRel) > 1.35) {
        res.d = max(rXZ - 4.3, abs(yRel) - 1.15);
        return res;
    }

    float rMin = mix(0.62, 0.72, openAmt);
    float rMax = mix(2.75, 3.65, openAmt);
    float rClamped = clamp(rXZ, rMin, rMax);
    float u = (rClamped - rMin) / max(rMax - rMin, 1e-4);

    float ang = atan(pWorld.z, pWorld.x);
    // Gentle seamless spiral rotation in 3s loop
    float spin = phase * TAU / 3.0;

    // 3-fold rotational symmetry with dramatic S-curve inflection
    // S-curve: sweeps CCW near bloom, inflects CW mid-way, then gracefully flares out
    float sCurve = 1.65 * u + 0.68 * sin(u * PI * 1.45 - 0.35) - 0.25 * u * u;
    float baseAng = ang - spin - sCurve;

    // Fold into 3 sectors
    float sector = TAU / 3.0;
    float sectorIdx = floor((baseAng + 0.5 * sector) / sector);
    float localAng = mod(baseAng + 0.5 * sector, sector) - 0.5 * sector;

    // Arc distance across the ribbon centerline
    float arcDist = localAng * max(rXZ, 0.35);

    // Graceful 3D vertical wave along the S-curve
    float yCenter = 0.44 + 0.38 * u + 0.22 * sin(u * PI * 1.8 - phase * TAU + sectorIdx * 2.094);
    float dy = pWorld.y - yCenter;

    // Ribbon twist along its length so it catches light like a silk banner
    float twist = 0.42 * sin(u * PI * 1.35 + 0.4) + 0.22;
    vec2 crossP = rot2(twist) * vec2(arcDist, dy);

    // Ribbon width profile: tapers smoothly at inner root and sweeps wide & crisp outward,
    // then tapers to a graceful calligraphy tip at rMax
    float widthEnv = smoothstep(0.0, 0.18, u) * smoothstep(1.0, 0.78, u);
    float halfW = (0.14 + 0.16 * smoothstep(0.15, 0.75, u)) * mix(0.75, 1.08, openAmt) * widthEnv;
    float thick = 0.022 * mix(0.6, 1.0, widthEnv);

    // Radial endpoint cap distance
    float dRadEnd = max(rMin - rXZ, rXZ - rMax);
    float dWidth = abs(crossP.x) - halfW;
    float dThick = abs(crossP.y) - thick;

    vec3 dBox = vec3(dWidth, dThick, dRadEnd);
    float dMain = length(max(dBox, 0.0)) + min(max(dBox.x, max(dBox.y, dBox.z)), 0.0);

    // Secondary thin wispy trailing energy filament parallel to each ribbon
    float arcWisp = (localAng - 0.24 * (0.4 + 0.6 * u)) * max(rXZ, 0.35);
    float yWisp = yCenter + 0.06 * sin(u * PI * 2.5);
    float wispEnv = smoothstep(0.08, 0.30, u) * smoothstep(0.95, 0.65, u);
    float dWisp = length(vec2(arcWisp, pWorld.y - yWisp)) - 0.024 * wispEnv * mix(0.7, 1.0, openAmt);
    dWisp = max(dWisp, max(rMin + 0.15 - rXZ, rXZ - (rMax - 0.15)));

    // Use conservative Lipschitz scale (0.55) because of polar S-curve curvature
    float dFinal = min(dMain, dWisp) * 0.55;

    res.d = dFinal;
    res.u = u;
    res.v = clamp(crossP.x / max(halfW, 1e-4), -1.0, 1.0);
    res.id = mod(sectorIdx, 3.0);
    return res;
}

// ============================================================================
// ORBITING STYLIZED 5-PETAL CHERRY BLOSSOMS SDF
// ============================================================================

struct BlossomEval {
    float d;
    float centerMask; // 1 near golden stamen center
    float crease;     // 1 along petal seams / notch
    float radial;     // 0..1 center to petal tip
};

// Evaluate a single 5-petal notched cherry blossom in its local space
vec4 evalSingleSakura(vec3 lp, float rad) {
    float r = length(lp.xz);
    float a = atan(lp.z, lp.x);

    // 5-fold symmetry
    float sector = TAU / 5.0;
    float la = mod(a + 0.5 * sector, sector) - 0.5 * sector;
    float absLa = abs(la);

    // Iconic sakura petal shape: rounded lobe with a crisp V-notch at the tip!
    float lobe = cos(la * 2.35);
    float notch = 0.20 * exp(-pow(la / 0.13, 2.0));
    float rProfile = rad * (0.34 + 0.66 * max(lobe, 0.0) - notch);

    // Gentle upward cup curvature
    float cupY = 0.12 * rad * (r / max(rad, 1e-4)) * (r / max(rad, 1e-4));
    float dPlanar = r - rProfile;
    float thick = 0.024 * (rad / 0.28);
    float d = length(max(vec2(dPlanar, abs(lp.y - cupY) - thick), 0.0))
            + min(max(dPlanar, abs(lp.y - cupY) - thick), 0.0);

    // Stamen center mask and inter-petal crease lines
    float centerM = smoothstep(rad * 0.28, rad * 0.12, r);
    float seam = smoothstep(0.08, 0.015, abs(absLa - 0.5 * sector)) * smoothstep(rad * 0.14, rad * 0.35, r);
    float notchCrease = smoothstep(0.06, 0.01, absLa) * smoothstep(rad * 0.68, rad * 0.84, r);
    float crease = max(seam, notchCrease * 0.8);

    return vec4(d * 0.72, centerM, crease, clamp(r / max(rad, 1e-4), 0.0, 1.0));
}

BlossomEval evalBlossoms(vec3 pWorld, float openAmt, float phase) {
    BlossomEval res;
    res.d = 1e5;
    res.centerMask = 0.0;
    res.crease = 0.0;
    res.radial = 0.0;

    // Quick bounding ring check
    float rXZ = length(pWorld.xz);
    if (rXZ < 0.55 || rXZ > 2.85 || pWorld.y < 0.12 || pWorld.y > 1.65) {
        res.d = max(max(0.65 - rXZ, rXZ - 2.65), max(0.2 - pWorld.y, pWorld.y - 1.5));
        return res;
    }

    float orbitScale = mix(0.82, 1.08, openAmt);
    float spin = phase * TAU / 3.0;

    // 6 orbiting cherry blossoms arranged gracefully around the bloom & ribbons
    for (int i = 0; i < 6; i++) {
        float fi = float(i);
        float baseTheta = fi * (TAU / 6.0) + 0.38 + spin;
        float orbitR = (1.18 + 0.36 * mod(fi, 2.0) + 0.14 * sin(fi * 2.1)) * orbitScale;
        float yPos = 0.66 + 0.14 * sin(fi * 1.9 + phase * TAU) + 0.08 * mod(fi, 2.0);
        vec3 center = vec3(cos(baseTheta) * orbitR, yPos, sin(baseTheta) * orbitR);

        float rad = (0.24 + 0.06 * sin(fi * 2.7)) * mix(0.84, 1.06, openAmt);
        vec3 lp = pWorld - center;
        float dSphere = length(lp) - (rad + 0.10);
        if (dSphere > res.d) continue;

        // Tilt blossom slightly to face the viewer gracefully + gentle spin
        lp.xz = rot2(-baseTheta + 0.45 * sin(phase * TAU + fi)) * lp.xz;
        lp.xy = rot2(0.28 * sin(fi * 1.7 + 0.5)) * lp.xy;
        lp.yz = rot2(0.24 * cos(fi * 1.3)) * lp.yz;

        vec4 s = evalSingleSakura(lp, rad);
        if (s.x < res.d) {
            res.d = s.x;
            res.centerMask = s.y;
            res.crease = s.z;
            res.radial = s.w;
        }
    }

    return res;
}

// ============================================================================
// DRIFTING LOOSE SAKURA PETALS SDF
// ============================================================================

float evalLoosePetals(vec3 pWorld, float openAmt, float phase) {
    float rXZ = length(pWorld.xz);
    if (rXZ < 0.65 || rXZ > 2.6 || pWorld.y < 0.18 || pWorld.y > 1.55) {
        return max(max(0.75 - rXZ, rXZ - 2.45), max(0.22 - pWorld.y, pWorld.y - 1.45));
    }

    float dMin = 1e5;
    float spread = mix(0.85, 1.12, openAmt);
    float spin = phase * TAU / 3.0;

    for (int i = 0; i < 8; i++) {
        float fi = float(i);
        float a = fi * (TAU / 8.0) + 0.72 + spin * 1.5;
        float rad = (1.02 + 0.62 * fract(fi * 0.618)) * spread;
        float y = 0.48 + 0.42 * fract(fi * 0.37) + 0.10 * sin(phase * TAU + fi * 1.7);
        vec3 c = vec3(cos(a) * rad, y, sin(a) * rad);

        vec3 lp = pWorld - c;
        if (length(lp) - 0.14 > dMin) continue;

        lp.xz = rot2(-a + phase * TAU * 0.5 + fi) * lp.xz;
        lp.xy = rot2(0.55 * sin(phase * TAU + fi * 2.3)) * lp.xy;

        // Teardrop curved petal
        vec3 q = lp / vec3(0.095, 0.014, 0.055);
        float d = (length(q) - 1.0) * 0.032;
        dMin = min(dMin, d);
    }

    return dMin;
}

// ============================================================================
// COMBINED SCENE MAP
// ============================================================================

vec2 mapScene(vec3 p) {
    float openAmt = clamp(uOpen, 0.0, 1.0);
    float phase = loopPhase();

    // Arena floor at y = 0
    vec2 res = vec2(p.y, MAT_FLOOR);

    // Central sculpted sakura rose
    RoseEval rose = evalRoseBloom(p, openAmt, phase);
    if (rose.d < res.x) {
        res = vec2(rose.d, MAT_ROSE);
    }

    // 3 sweeping S-curved pearl-pink ribbons
    RibbonEval rib = evalRibbons(p, openAmt, phase);
    if (rib.d < res.x) {
        res = vec2(rib.d, MAT_RIBBON);
    }

    // 6 orbiting 5-petal cherry blossoms
    BlossomEval blos = evalBlossoms(p, openAmt, phase);
    if (blos.d < res.x) {
        res = vec2(blos.d, MAT_BLOSSOM);
    }

    // Drifting loose sakura petals
    float dPetals = evalLoosePetals(p, openAmt, phase);
    if (dPetals < res.x) {
        res = vec2(dPetals, MAT_PETAL);
    }

    return res;
}

vec3 calcNormal(vec3 p, float t) {
    float e = clamp(0.0018 * t, 0.0015, 0.007);
    vec2 k = vec2(1.0, -1.0);
    vec3 n = k.xyy * mapScene(p + k.xyy * e).x
           + k.yyx * mapScene(p + k.yyx * e).x
           + k.yxy * mapScene(p + k.yxy * e).x
           + k.xxx * mapScene(p + k.xxx * e).x;
    return safeNormalize(n);
}

vec2 raymarch(vec3 ro, vec3 rd, float tMax) {
    float t = 0.05;
    float matId = -1.0;
    for (int i = 0; i < 96; i++) {
        vec3 p = ro + rd * t;
        vec2 h = mapScene(p);
        if (h.x < 0.0015 * max(t, 1.0)) {
            matId = h.y;
            return vec2(t, matId);
        }
        t += h.x;
        if (t > tMax) break;
    }
    return vec2(-1.0, -1.0);
}

// ============================================================================
// DARK MATTE INK-GROUTED CHARCOAL TILED ARENA FLOOR
// ============================================================================

vec3 shadeFloor(vec3 p, vec3 rd, float tHit, float openAmt, float phase, bool neutral) {
    // Tilted grid tiles matching the dramatic arena perspective
    vec2 gp = rot2(0.24) * p.xz * 0.72;
    vec2 tileId = floor(gp);
    vec2 tileUv = fract(gp);

    // Crisp dark ink grout lines with subtle AA
    float fw = clamp(0.008 * tHit, 0.006, 0.035);
    vec2 edgeDist = min(tileUv, 1.0 - tileUv);
    float minEdge = min(edgeDist.x, edgeDist.y);
    float groutMask = 1.0 - smoothstep(0.018, 0.018 + fw, minEdge);

    // Subtle chamfer highlight just inside the grout
    float bevelMask = smoothstep(0.018, 0.032, minEdge) * (1.0 - smoothstep(0.032, 0.065, minEdge));

    // Matte charcoal tile variation + subtle ink-scuff texture
    float tileTone = hash21(tileId);
    float grain = fbm2(gp * 3.8 + tileTone * 11.0);
    float scuff = smoothstep(0.68, 0.82, fbm2(gp * 9.5 + 3.1));

    vec3 baseCol = neutral ? vec3(0.024) : (COL_FLOOR_BASE * 0.24);
    // Slight tile-to-tile tonal variation (rich dark matte charcoal, never washed out)
    vec3 col = baseCol * (0.84 + 0.28 * tileTone + 0.16 * (grain - 0.5));
    col += (neutral ? vec3(0.008) : vec3(0.009, 0.010, 0.015)) * bevelMask;
    col *= 1.0 - 0.22 * scuff;

    // Subtle curved arena boundary ring & muted crimson trim in background
    float rArena = length(p.xz);
    float rimStripe = smoothstep(0.11, 0.02, abs(rArena - 5.2));
    float rimInk = smoothstep(0.16, 0.04, abs(rArena - 5.2)) * (1.0 - rimStripe);
    vec3 trimCol = neutral ? vec3(0.06) : vec3(0.14, 0.022, 0.045);
    col = mix(col, trimCol, rimStripe * 0.90);
    col = mix(col, neutral ? vec3(0.004) : COL_INK, rimInk * 0.90);

    // Apply crisp dark ink grout lines
    col = mix(col, neutral ? vec3(0.004) : COL_INK, groutMask * 0.92);

    // Graphic hovering shadow directly underneath the central bloom
    float rCenter = length(p.xz);
    float bloomShadow = 1.0 - 0.58 * smoothstep(1.25, 0.55, rCenter);
    col *= bloomShadow;

    // Localized stylized cel-stepped rose light spill directly around the bloom
    float spillRaw = exp(-rCenter * rCenter * (0.72 - 0.14 * openAmt)) * smoothstep(2.6, 0.8, rCenter);
    float spillCel = 0.55 * smoothstep(0.08, 0.16, spillRaw) + 0.45 * smoothstep(0.32, 0.42, spillRaw);
    float pulse = 0.92 + 0.08 * sin(phase * TAU);
    vec3 glowTint = neutral ? vec3(0.09) : mix(COL_SAKURA_DEEP, COL_SAKURA_MID, 0.55);
    col += glowTint * spillCel * (0.055 + 0.045 * openAmt) * pulse;

    // Tight ribbon light spill directly under the 3 S-curved ribbons
    RibbonEval ribFloor = evalRibbons(vec3(p.x, 0.58, p.z), openAmt, phase);
    float ribGlow = smoothstep(0.28, 0.04, max(ribFloor.d, 0.0)) * smoothstep(3.6, 0.9, rCenter);
    col += (neutral ? vec3(0.045) : COL_SAKURA_MID) * ribGlow * (0.045 + 0.03 * openAmt);

    // Gentle distance fog blending into dark matte charcoal backdrop
    float fog = 1.0 - exp(-tHit * tHit * 0.0075);
    vec3 fogCol = neutral ? vec3(0.018) : vec3(0.012, 0.014, 0.020);
    col = mix(col, fogCol, clamp(fog, 0.0, 0.72));

    return col;
}

// ============================================================================
// STYLIZED CEL-SHADED SURFACE SHADING
// ============================================================================

vec3 shadeHit(vec3 p, vec3 rd, float matId, float tHit) {
    float openAmt = clamp(uOpen, 0.0, 1.0);
    float phase = loopPhase();
    bool neutral = (uLightMode == 1);

    if (matId == MAT_FLOOR) {
        return shadeFloor(p, rd, tHit, openAmt, phase, neutral);
    }

    vec3 n = calcNormal(p, tHit);
    vec3 v = -rd;
    vec3 lDir = safeNormalize(vec3(0.45, 0.84, 0.32));
    float ndl = dot(n, lDir);
    float ndv = clamp(dot(n, v), 0.0, 1.0);

    // Stylized 3-band cel diffuse + crisp bold black-ink Fresnel contour
    float cel = cel3(ndl);
    float inkFresnel = smoothstep(0.44, 0.20, ndv);

    vec3 inkCol = neutral ? vec3(0.005) : COL_INK;
    vec3 col = vec3(0.5);

    if (matId == MAT_ROSE) {
        RoseEval rose = evalRoseBloom(p, openAmt, phase);
        vec3 baseLight, baseMid, baseShadow;

        if (rose.tier < 0.5) {
            // Outer sculpted pearl-white petals with crisp rose-blush base shadow
            baseLight  = mix(COL_PEARL_WHITE, COL_CREAM_GOLD, 0.18);
            baseMid    = mix(COL_PEARL_WHITE, COL_SAKURA_LIGHT, 0.34 * (1.0 - rose.radial));
            baseShadow = mix(COL_PEARL_SHADOW, COL_SAKURA_DEEP, 0.42 * (1.0 - rose.radial));
        } else if (rose.tier < 2.5) {
            // Mid layered vibrant rose-pink petals with crisp pearl-white rim
            float tipBlend = smoothstep(0.58, 0.94, rose.radial);
            baseLight  = mix(COL_SAKURA_LIGHT, COL_PEARL_WHITE, 0.68 * tipBlend);
            baseMid    = mix(COL_SAKURA_MID, COL_SAKURA_LIGHT, 0.30 * tipBlend);
            baseShadow = COL_SAKURA_DEEP;
        } else {
            // Inner spiraling rose heart: saturated rose core with pearl edge highlights
            baseLight  = mix(COL_PEARL_WHITE, COL_SAKURA_LIGHT, 0.35);
            baseMid    = COL_SAKURA_MID;
            baseShadow = COL_SAKURA_DEEP;
        }

        // Quantized 3-band cel color selection
        vec3 c1 = mix(baseShadow, baseMid, smoothstep(0.34, 0.52, cel));
        col = mix(c1, baseLight, smoothstep(0.70, 0.86, cel));

        // Subtle warm pearl rim glow from the heart
        float heartGlow = exp(-length(p.xz) * 2.4) * (0.10 + 0.12 * openAmt);
        col += mix(COL_SAKURA_LIGHT, COL_CREAM_GOLD, 0.35) * heartGlow;

        // Crisp dark maroon-ink creases between petals & spiral heart + bold black-ink silhouette
        vec3 creaseInk = neutral ? vec3(0.012) : COL_ROSE_INK;
        col = mix(col, creaseInk, smoothstep(0.15, 0.65, rose.crease) * 0.90);
        col = mix(col, inkCol, inkFresnel * 0.96);

    } else if (matId == MAT_RIBBON) {
        RibbonEval rib = evalRibbons(p, openAmt, phase);

        // Stylized multi-band silk ribbon coloring (matching 07.png):
        //   inner half: warm pearl-cream
        //   outer half: vibrant sakura-pink & deeper rose-pink cel band
        float bandMid = smoothstep(-0.16, -0.06, rib.v);
        float bandEdge = smoothstep(0.32, 0.42, rib.v);
        vec3 ribBase = mix(mix(COL_PEARL_WHITE, COL_CREAM_GOLD, 0.55), COL_SAKURA_LIGHT, bandMid);
        ribBase = mix(ribBase, COL_SAKURA_MID, bandEdge);

        // Subtle flowing comic speed-line striations along the ribbon
        float streak = 0.5 + 0.5 * sin(rib.v * 22.0 + sin(rib.u * 10.0 - phase * TAU * 2.0) * 1.6);
        float streakMask = smoothstep(0.76, 0.90, streak) * smoothstep(0.08, 0.25, rib.u);
        ribBase = mix(ribBase, COL_PEARL_WHITE, streakMask * 0.35);

        // Strong 3-band cel shading across ribbon twist
        vec3 ribShadow = mix(COL_SAKURA_DEEP, ribBase * 0.55, 0.35);
        col = mix(ribShadow, ribBase, smoothstep(0.32, 0.58, cel));
        col = mix(col, COL_PEARL_WHITE, smoothstep(0.84, 0.96, cel) * 0.22);

        // Bold black-ink outline along both edges of the ribbon + Fresnel
        float edgeInk = smoothstep(0.70, 0.84, abs(rib.v));
        // Crisp inner ink divider line between cream and pink bands
        float innerInk = smoothstep(0.065, 0.015, abs(rib.v + 0.11)) * 0.55;
        col = mix(col, COL_ROSE_INK, innerInk);
        col = mix(col, inkCol, max(edgeInk * 0.96, inkFresnel * 0.92));

    } else if (matId == MAT_BLOSSOM) {
        BlossomEval blos = evalBlossoms(p, openAmt, phase);

        // 3-band saturated sakura pink petals with deep magenta-rose base & pearl rim
        vec3 baseCol = mix(COL_SAKURA_MID, COL_SAKURA_LIGHT, smoothstep(0.28, 0.88, blos.radial));
        vec3 shadCol = COL_SAKURA_DEEP;
        col = mix(shadCol, baseCol, smoothstep(0.32, 0.62, cel));
        col = mix(col, COL_PEARL_WHITE, smoothstep(0.80, 0.94, cel) * 0.40);

        // Warm golden stamen center
        col = mix(col, COL_WARM_GOLD, blos.centerMask * 0.94);

        // Crisp inter-petal crease ink & bold black-ink Fresnel outline
        col = mix(col, COL_ROSE_INK, smoothstep(0.15, 0.65, blos.crease) * 0.88);
        col = mix(col, inkCol, inkFresnel * 0.95);

    } else if (matId == MAT_PETAL) {
        // Drifting loose cel-shaded sakura petals
        col = mix(COL_SAKURA_DEEP, COL_SAKURA_MID, smoothstep(0.30, 0.55, cel));
        col = mix(col, COL_SAKURA_LIGHT, smoothstep(0.72, 0.90, cel));
        col = mix(col, inkCol, inkFresnel * 0.94);
    }

    if (neutral) {
        float lum = dot(col, vec3(0.2126, 0.7152, 0.0722));
        col = vec3(lum);
    }

    return col;
}

// ============================================================================
// CRISP WARM CREAM-GOLD 4-POINT COMIC STAR SPARKLES + SOFT HALO
// ============================================================================

vec3 evalSparklesAndGlow(vec3 ro, vec3 rd, float tMax, float openAmt, float phase, bool neutral) {
    vec3 acc = vec3(0.0);

    // Subtle localized sakura-pearl aura hovering behind/around the central bloom
    vec3 bloomPos = vec3(0.0, 0.62, 0.0);
    float tAura = dot(bloomPos - ro, rd);
    if (tAura > 0.0 && tAura < tMax + 0.4) {
        vec3 closest = ro + rd * tAura;
        float dist = length(closest - bloomPos);
        float aura = exp(-dist * dist * 1.95) * (0.08 + 0.09 * openAmt);
        vec3 auraCol = neutral ? vec3(0.14) : mix(COL_SAKURA_MID, COL_CREAM_GOLD, 0.35);
        acc += auraCol * aura * smoothstep(tAura - 0.25, tAura + 0.35, tMax);
    }

    // Build camera-facing tangent basis for crisp 4-point comic stars
    vec3 camRight = safeNormalize(cross(rd, vec3(0.0, 1.0, 0.0)));
    vec3 camUp = safeNormalize(cross(camRight, rd));

    // 6 crisp 4-point cream-gold comic star sparkles arranged around the blossom & ribbons
    vec3 starPos[6];
    starPos[0] = vec3(-0.08, 1.28, -1.35); // Large top hero star
    starPos[1] = vec3( 0.78, 1.12, -0.92); // Upper-right star
    starPos[2] = vec3( 1.62, 1.02, -0.32); // Far-right ribbon star
    starPos[3] = vec3(-1.42, 0.88,  0.62); // Lower-left star
    starPos[4] = vec3(-0.62, 0.74,  1.05); // Mid-lower-left star
    starPos[5] = vec3( 0.06, 0.82,  1.45); // Bottom hero star

    float starSize[6];
    starSize[0] = 0.28;
    starSize[1] = 0.16;
    starSize[2] = 0.23;
    starSize[3] = 0.24;
    starSize[4] = 0.15;
    starSize[5] = 0.25;

    float spread = mix(0.84, 1.06, openAmt);
    float scaleBoost = mix(0.72, 1.12, openAmt);

    for (int i = 0; i < 6; i++) {
        float fi = float(i);
        vec3 sp = starPos[i] * vec3(spread, 1.0, spread);
        // Gentle floating bob in 3s loop
        sp.y += 0.045 * sin(phase * TAU + fi * 1.15);

        float tS = dot(sp - ro, rd);
        if (tS <= 0.1 || tS > tMax) continue;

        vec3 diff = (ro + rd * tS) - sp;
        vec2 p2 = vec2(dot(diff, camRight), dot(diff, camUp));

        // Twinkle pulse in 3s loop
        float twinkle = 0.82 + 0.18 * sin(phase * TAU * 2.0 + fi * 1.4);
        float sz = starSize[i] * scaleBoost * twinkle;
        vec2 q = abs(p2) / max(sz, 1e-4);

        // Concave 4-point comic diamond star SDF: sqrt(qx) + sqrt(qy) <= 1
        // Slightly taller vertical spike like classic anime/Hades sparkles
        q.x *= 1.18;
        float astroid = sqrt(q.x + 1e-5) + sqrt(q.y + 1e-5);
        float starCore = 1.0 - smoothstep(0.86, 0.98, astroid);
        float starHalo = exp(-dot(p2, p2) / max(sz * sz * 0.20, 1e-4)) * 0.36;

        vec3 coreCol = neutral ? vec3(0.92) : COL_CREAM_GOLD;
        vec3 haloCol = neutral ? vec3(0.45) : COL_WARM_GOLD;
        acc += coreCol * starCore * 0.96 + haloCol * starHalo;
    }

    return acc;
}

// ============================================================================
// ENVIRONMENT & ACES FILMIC TONE MAPPING
// ============================================================================

vec3 evalBackdrop(vec3 rd, bool neutral) {
    float g = clamp(rd.y * 0.5 + 0.5, 0.0, 1.0);
    vec3 low = neutral ? vec3(0.016) : vec3(0.012, 0.014, 0.020);
    vec3 high = neutral ? vec3(0.028) : vec3(0.020, 0.022, 0.032);
    return mix(low, high, g);
}

vec3 acesToneMap(vec3 x) {
    x = max(x, vec3(0.0));
    const float a = 2.51;
    const float b = 0.03;
    const float c = 2.43;
    const float d = 0.59;
    const float e = 0.14;
    return clamp((x * (a * x + b)) / max(x * (c * x + d) + e, vec3(1e-5)), 0.0, 1.0);
}

void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * uResolution.xy) / max(uResolution.y, 1.0);
    float openAmt = clamp(uOpen, 0.0, 1.0);
    float phase = loopPhase();
    bool neutral = (uLightMode == 1);

    // Camera framing:
    //   uCamMode == 0 : High-angle 3/4 hero view matching 07.png
    //   uCamMode == 1 : Macro close-up on the central sculpted sakura rose & ink contours
    vec3 ro, ta;
    float fov;
    if (uCamMode == 1) {
        ro = vec3(0.22, 1.82, 1.55);
        ta = vec3(0.00, 0.62, 0.00);
        fov = 1.65;
    } else {
        ro = vec3(0.08, 3.65, 2.72);
        ta = vec3(0.00, 0.52, -0.04);
        fov = 1.42;
    }

    vec3 cw = safeNormalize(ta - ro);
    vec3 cu = safeNormalize(cross(cw, vec3(0.0, 1.0, 0.0)));
    vec3 cv = cross(cu, cw);
    vec3 rd = safeNormalize(uv.x * cu + uv.y * cv + fov * cw);

    float tMax = 16.0;
    vec2 hit = raymarch(ro, rd, tMax);

    vec3 col;
    float volMaxT = tMax;
    if (hit.x > 0.0) {
        vec3 p = ro + rd * hit.x;
        col = shadeHit(p, rd, hit.y, hit.x);
        volMaxT = hit.x;
    } else {
        col = evalBackdrop(rd, neutral);
    }

    // Crisp warm cream-gold 4-point comic star sparkles + soft bloom aura
    col += evalSparklesAndGlow(ro, rd, volMaxT, openAmt, phase, neutral);

    // Controlled exposure & mild vignette (keeps corners above black)
    col *= neutral ? 1.04 : 1.06;
    float vig = 1.0 - 0.14 * dot(uv, uv);
    col *= clamp(vig, 0.80, 1.0);

    // ACES Filmic Tone Mapping
    col = acesToneMap(col);

    if (neutral) {
        float lum = dot(col, vec3(0.2126, 0.7152, 0.0722));
        col = vec3(lum);
    }

    // sRGB gamma encode
    col = pow(max(col, vec3(0.0)), vec3(1.0 / 2.2));

    fragColor = vec4(col, 1.0);
}
