/* NITRO68 reactive lights, C99. Coordinates are normalized to 0..255.
 * reset on mode change, palette for custom 0xRRGGBB colours, press on make edges.
 * Pass edge=-1/0/+1 for first/interior/last physical key of the pressed row.
 * Sample side_rgb around the clockwise perimeter (zero at top centre), and
 * key_rgb at each key centre. Apply board-specific LED mapping/calibration last.
 * Sample once at idle as well, so the strip and switches settle on their base colours.
 */
#ifndef NITRO_SIDE_EFFECTS_H
#define NITRO_SIDE_EFFECTS_H
#include <stdint.h>
enum { NITRO_INK, NITRO_RALLY, NITRO_VEIL };
typedef struct { uint32_t at; float x,y; int edge; } NitroHit;
typedef struct { uint16_t age; uint8_t x,y,start_level; } NitroKeyGlow;
enum { NITRO_APM_BIN_MS=100, NITRO_APM_BINS=31, NITRO_FULL_APM=720 };
typedef struct {
    union { NitroHit hits[16]; NitroKeyGlow keys[68]; } history;
    uint32_t last,base,accent;
    unsigned effect,next,count;
    float rally_from,rally_delta,rally_ms,rally_start_level;
    /* Both rails share a path. Ages and crossing times are relative to last. */
    uint16_t rally_old_age[99],rally_crossing[99];
    uint32_t charge_frame,breath_start;
    uint32_t apm_bin_start;
    uint8_t apm_bins[NITRO_APM_BINS],apm_head;
    float charge;
    unsigned charge_cached,breathing,full_latched;
} NitroSide;
static inline unsigned nitro_min(unsigned a,unsigned b) { return a<b?a:b; }
static inline float nitro_abs(float x) { return x<0?-x:x; }
static inline float nitro_ease(float x) {
    if (x<=0) return 0;
    if (x>=1) return 1;
    return x*x*(3-2*x);
}
static inline unsigned nitro_side_position(unsigned x, unsigned y) {
    int dx=(int)nitro_min(x,255)*2-255, dy=(int)nitro_min(y,255)*2-255;
    int ax=dx<0?-dx:dx, ay=dy<0?-dy:dy;
    int phase;
    if (ay>=ax) phase=dy<0 ? 49*dx/ay : 128-49*dx/ay;
    else phase=dx>0 ? 64+15*dy/ax : 192-15*dy/ax;
    return (unsigned)phase&255u;
}

static inline void nitro_side_palette(NitroSide *s,uint32_t base,uint32_t accent) {
    s->base=base; s->accent=accent;
    if(s->effect==NITRO_RALLY) {
        /* Lift the selected base at palette application, keeping its hue and
         * leaving progressively more headroom as the colour approaches white. */
        unsigned r=(base>>16)&255, g=(base>>8)&255, b=base&255;
        unsigned peak=r>g?r:g;
        if(b>peak) peak=b;
        float gain=1.f+.68f*(1.f-peak/255.f);
        s->base=((uint32_t)(r*gain+.5f)<<16) |
                ((uint32_t)(g*gain+.5f)<<8) | (uint32_t)(b*gain+.5f);
    }
}
static inline void nitro_side_reset(NitroSide *s,unsigned effect) {
    *s=(NitroSide){0};
    s->effect=effect;
    static const uint32_t base[]={0xA6BAC8,0x374756,0xBDCEDD};
    static const uint32_t accent[]={0x192B3D,0xBFEAFF,0x526B9B};
    nitro_side_palette(s,base[effect%3],accent[effect%3]);
}
/* Both rails follow the same horizontal trajectory, even across a row change. */
static inline float nitro_rally_progress(float u) {
    if(u>=1) return 1;
    float remaining=1-u;
    return 1-remaining*remaining*remaining*(1+3*u);
}
static inline float nitro_rally_location(const NitroSide *s,uint32_t age) {
    float u=age/s->rally_ms;
    if(u>=1) return s->rally_from+s->rally_delta;
    return s->rally_from+s->rally_delta*nitro_rally_progress(u);
}
static inline float nitro_rally_level(const NitroSide *s,uint32_t age) {
    float since_arrival=(float)age-s->rally_ms;
    float attack=s->rally_start_level+(1-s->rally_start_level)*nitro_ease(age/75.f);
    return attack*(1-nitro_ease((since_arrival-800)/460.f));
}
enum { NITRO_WAKE_MS=1850, NITRO_NOT_CROSSED=65535 };
static inline float nitro_wake_fade(unsigned age) {
    return (1-nitro_ease(age/(float)NITRO_WAKE_MS))*
           (.34f+.42f*(1-nitro_ease(age/490.f)))/.76f;
}
static inline float nitro_rally_key_level(unsigned age,unsigned start) {
    float attack=nitro_ease(age/35.f);
    return (attack+(1-attack)*start/255.f)*nitro_wake_fade(age);
}
static inline unsigned nitro_rally_mark_age(const NitroSide *s,uint32_t elapsed,unsigned col) {
    unsigned crossing=s->rally_crossing[col];
    if(crossing!=NITRO_NOT_CROSSED && elapsed>=crossing)
        return nitro_min(elapsed-crossing,NITRO_WAKE_MS);
    return nitro_min(s->rally_old_age[col]+nitro_min(elapsed,NITRO_WAKE_MS),NITRO_WAKE_MS);
}
/* Find when this eased stroke actually passes a column. Calculated only on
 * keydown, so trail decay does not depend on the render loop's frame rate. */
static inline unsigned nitro_rally_crossing(float from,float delta,float duration,int x) {
    if(delta==0) return NITRO_NOT_CROSSED;
    float fraction=(x-from)/delta;
    if(fraction<0 || fraction>1) return NITRO_NOT_CROSSED;
    float lo=0,hi=1;
    for(unsigned n=0;n<10;++n) {
        float mid=(lo+hi)*.5f;
        if(nitro_rally_progress(mid)<fraction) lo=mid; else hi=mid;
    }
    return (unsigned)(hi*duration+.5f);
}
static inline void nitro_side_press(NitroSide *s,uint32_t now,unsigned x,unsigned y,int edge) {
    if(s->effect==NITRO_RALLY) {
        float target=((float)nitro_min(x,255)/255.f-.5f)*88.f;
        uint32_t age=now-s->last;
        float level=s->count?nitro_rally_level(s,age):0;
        float from=s->rally_ms>0?nitro_rally_location(s,age):target;
        float duration=from==target?75.f:180.f+3.f*nitro_abs(target-from);
        for(int xcol=-49;xcol<=49;++xcol) {
            unsigned col=(unsigned)(xcol+49);
            s->rally_old_age[col]=s->count?nitro_rally_mark_age(s,age,col):NITRO_WAKE_MS;
            s->rally_crossing[col]=nitro_rally_crossing(from,target-from,duration,xcol);
        }
        s->rally_from=from; s->rally_delta=target-from;
        s->rally_ms=duration;
        s->rally_start_level=level;
        /* Keep one glow per physical key: fast typing or retriggering a key
         * must not evict another key before its wake has faded. */
        unsigned active=0,start=0;
        x=nitro_min(x,255); y=nitro_min(y,255);
        for(unsigned i=0;i<s->count;++i) {
            NitroKeyGlow key=s->history.keys[i];
            unsigned elapsed=key.age+nitro_min(age,NITRO_WAKE_MS);
            if(elapsed>=NITRO_WAKE_MS) continue;
            if(key.x==x && key.y==y) {
                start=(unsigned)(255*nitro_rally_key_level(elapsed,key.start_level)+.5f);
            } else {
                key.age=(uint16_t)elapsed;
                s->history.keys[active++]=key;
            }
        }
        if(active==68) active--; /* Only possible for non-layout coordinates. */
        s->history.keys[active++]=(NitroKeyGlow){0,(uint8_t)x,(uint8_t)y,(uint8_t)start};
        s->count=active;
    } else {
        if(s->effect==NITRO_VEIL) {
            /* Advance from the previous bin boundary, including across timer wrap. */
            uint32_t elapsed=now-s->apm_bin_start;
            unsigned steps=elapsed/NITRO_APM_BIN_MS;
            if(!s->count || steps>=NITRO_APM_BINS) {
                for(unsigned i=0;i<NITRO_APM_BINS;++i) s->apm_bins[i]=0;
                s->apm_head=0;
                s->apm_bin_start=now;
            } else {
                for(unsigned i=0;i<steps;++i) {
                    s->apm_head=(s->apm_head+1)%NITRO_APM_BINS;
                    s->apm_bins[s->apm_head]=0;
                }
                s->apm_bin_start+=steps*NITRO_APM_BIN_MS;
            }
            if(s->apm_bins[s->apm_head]<255) ++s->apm_bins[s->apm_head];
        }
        s->history.hits[s->next]=(NitroHit){now,nitro_min(x,255)/255.f,nitro_min(y,255)/255.f,edge};
        s->next=(s->next+1)%16; s->count=nitro_min(s->count+1,16);
    }
    s->last=now;
    s->charge_cached=0;
}
static inline float nitro_energy(const NitroSide *s,uint32_t now) {
    /* Three rolling one-second windows. Each can fill only its own third,
     * so a rapid burst cannot bank enough hits to replace sustained speed. */
    unsigned elapsed=now-s->apm_bin_start, skip=elapsed/NITRO_APM_BIN_MS;
    if(!s->count || skip>=NITRO_APM_BINS) return 0;
    float fraction=(elapsed%NITRO_APM_BIN_MS)/(float)NITRO_APM_BIN_MS;
    float total=0,per_second=NITRO_FULL_APM/60.f;
    for(int start=0;start<30;start+=10) {
        float count=0;
        for(int j=0;j<=10;++j) {
            int back=start+j-(int)skip;
            if(back<0) continue;
            unsigned index=(s->apm_head+NITRO_APM_BINS-back)%NITRO_APM_BINS;
            float weight=j==0?fraction:j==10?1-fraction:1;
            count+=s->apm_bins[index]*weight;
        }
        total+=count<per_second?count:per_second;
    }
    return total/(3*per_second);
}
enum { NITRO_BREATH_PERIOD=1400, NITRO_BREATH_END=3*NITRO_BREATH_PERIOD,
       NITRO_BREATH_RELEASE=550 };
static inline void nitro_charge_frame(NitroSide *s,uint32_t now) {
    if(s->charge_cached && s->charge_frame==now) return;
    s->charge_cached=1;
    s->charge_frame=now;
    s->charge=nitro_energy(s,now);
    if(s->breathing && now-s->breath_start>=NITRO_BREATH_END+NITRO_BREATH_RELEASE)
        s->breathing=0;
    if(!s->breathing && s->charge<.68f) s->full_latched=0;
    if(!s->full_latched && s->charge>=1.f) {
        s->breathing=s->full_latched=1;
        s->breath_start=now;
    }
}
static inline unsigned nitro_side_idle(NitroSide *s,uint32_t now) {
    unsigned duration=s->effect==NITRO_VEIL?NITRO_APM_BINS*NITRO_APM_BIN_MS:1350u;
    if(s->effect==NITRO_RALLY) duration=(unsigned)s->rally_ms+NITRO_WAKE_MS+1u;
    if(s->effect==NITRO_VEIL) nitro_charge_frame(s,now);
    if (s->count && now-s->last>=duration) s->count=0;
    return !s->count && !s->breathing;
}
static inline uint32_t nitro_mix(const NitroSide *s,float amount,float gain) {
    uint32_t rgb=0;
    for(int shift=16;shift>=0;shift-=8) {
        float a=(s->base>>shift)&255, b=(s->accent>>shift)&255;
        rgb|=(uint32_t)((a+(b-a)*amount)*gain+.5f)<<shift;
    }
    return rgb;
}
/* Interpolate from the idle switch colour (74% base) to the selected RGB. */
static inline uint32_t nitro_key_glow(const NitroSide *s,float pulse) {
    float gain=.74f+.26f*pulse;
    return nitro_mix(s,pulse/gain,gain);
}
static inline uint32_t nitro_sample(const NitroSide *s,uint32_t now,float x,float y,int side,float side_depth,int key) {
    float strength=0, gain=1.f;
    if (s->effect==NITRO_VEIL) {
        float charge=s->charge;
        // Both long edges reach their ends before either short edge fills.
        float distance=side ? 1.f+side_depth : nitro_abs(2*x-1);
        strength=nitro_ease((charge*(1.f+15.f/98.f+.13f)-distance)/.13f);
        if(s->breathing) {
            uint32_t age=now-s->breath_start;
            float phase=(age%NITRO_BREATH_PERIOD)/(float)NITRO_BREATH_PERIOD;
            float depth=nitro_ease(phase<.5f?phase*2:(1-phase)*2);
            float gain_full=1-.20f*nitro_ease(age/650.f)-.26f*depth;
            float release=0;
            if(age>=NITRO_BREATH_END) {
                gain_full=.80f;
                release=nitro_ease((age-NITRO_BREATH_END)/(float)NITRO_BREATH_RELEASE);
            }
            strength=1+release*(strength-1);
            gain=gain_full+release*(1-gain_full);
        }
    } else {
        for (unsigned i=0;i<s->count;++i) {
            NitroHit h=s->history.hits[i];
            uint32_t ms=now-h.at;
            if(ms>=1350 || (side && h.edge!=side)) continue;
            float t=ms/1350.f;
            float envelope=nitro_ease(ms/100.f)*(1-nitro_ease((t-.59f)/.41f));
            float pulse;
            if(key) {
                float dx=(x-h.x)*14,dy=(y-h.y)*4.4f;
                float halo=1-nitro_ease((dx*dx+dy*dy)/3.f);
                pulse=(dx==0 && dy==0?1.f:.55f*halo)*(1-nitro_ease((t-.09f)/.48f));
            } else if(side) {
                /* Row centres run from 0.1 (Esc row) to 0.9 (bottom row).
                 * Anchor the outer rows at the ends of the short strip. */
                float origin=(h.y*255.f-26.f)/204.f;
                if(origin<0) origin=0;
                if(origin>1) origin=1;
                float distance=nitro_abs(y-origin);
                float front=1.16f*nitro_ease(t);
                pulse=1-nitro_ease(nitro_abs(distance-front)/.16f);
                if(y<origin) pulse*=nitro_ease(y/.16f);
                if(y>origin) pulse*=nitro_ease((1-y)/.16f);
            } else {
                if(h.edge) continue;
                float distance=nitro_abs(x-h.x);
                float front=1.16f*nitro_ease(t);
                pulse=1-nitro_ease(nitro_abs(distance-front)/.15f);
                // Interior keys fade along the long edges before the corner.
                pulse*=nitro_ease((x<.5f?x:1-x)/.12f);
            }
            strength+=(1-strength)*pulse*envelope;
        }
    }
    return key?nitro_key_glow(s,strength):nitro_mix(s,strength,gain);
}
static inline uint32_t nitro_side_rgb(NitroSide *s,uint32_t now,unsigned phase) {
    int p=(int)(phase&255u);
    if(s->effect==NITRO_VEIL) nitro_charge_frame(s,now);
    if(s->effect==NITRO_RALLY) {
        if(!s->count) return s->base;
        int x;
        if(p<=49 || p>=207) x=p<=49?p:p-256;
        else if(p>=79 && p<=177) x=128-p;
        else return s->base;
        uint32_t age=now-s->last;
        /* One soft pool, about two key widths from edge to edge on a long rail. */
        float spot=1-nitro_ease(nitro_abs(x-nitro_rally_location(s,age))/5.8f);
        spot*=nitro_rally_level(s,age);
        unsigned mark=nitro_rally_mark_age(s,age,(unsigned)(x+49));
        float wake=.76f*nitro_wake_fade(mark);
        return nitro_mix(s,spot+(1-spot)*wake,1);
    }
    if(p<49 || p>207) return nitro_sample(s,now,.5f+(p<=49?p:p-256)/98.f,0,0,0,0);
    if(p>79 && p<177) return nitro_sample(s,now,.5f+(128-p)/98.f,1,0,0,0);
    int right=p<=79, middle=right?64:192;
    return nitro_sample(s,now,right?1.f:0.f,(right?p-49:207-p)/30.f,right?1:-1,(15-nitro_abs(p-middle))/98.f,0);
}
static inline uint32_t nitro_key_rgb(const NitroSide *s,uint32_t now,unsigned x,unsigned y) {
    if(s->effect==NITRO_RALLY) {
        float pulse=0;
        x=nitro_min(x,255); y=nitro_min(y,255);
        for(unsigned i=0;i<s->count;++i) {
            NitroKeyGlow key=s->history.keys[i];
            if(key.x==x && key.y==y) {
                pulse=nitro_rally_key_level(key.age+nitro_min(now-s->last,NITRO_WAKE_MS),key.start_level);
                break;
            }
        }
        /* Let the selected hue dim first. Mixing the pale base back into it
         * from the start made a red key look grey well before the wake ended. */
        float tint=nitro_ease(pulse/.055f);
        float accent_light=tint*(.58f+.42f*pulse);
        float gain=.86f*(1-tint)+accent_light;
        return nitro_mix(s,accent_light/gain,gain);
    }
    if(s->effect==NITRO_VEIL) {
        float pulse=0, kx=nitro_min(x,255)/255.f, ky=nitro_min(y,255)/255.f;
        for(unsigned i=0;i<s->count;++i) {
            NitroHit h=s->history.hits[i];
            uint32_t ms=now-h.at;
            if(h.x!=kx || h.y!=ky) continue;
            float v=nitro_ease(ms/35.f)*(1-nitro_ease(((float)ms-170)/205.f));
            if(v>pulse) pulse=v;
        }
        return nitro_key_glow(s,pulse);
    }
    return nitro_sample(s,now,nitro_min(x,255)/255.f,nitro_min(y,255)/255.f,0,0,1);
}
#endif
