export class Fragment {
    constructor(p5, x, y, hexColor){
        this.p5 = p5;
        this.hexColor = hexColor;
        this.collected = false;
        this.baseY = y // this Y will be used for bobbing math
        this.bobAngle = p5.random(0, 360); // so they are not all in sync 

        // not a solid body so player can pass through 
        this.sprite = new p5.Sprite(x,y,20,20);
        this.sprite.image = '/assets/Fragment.png';
        this.sprite.collider = 'none';
        this.sprite.rotationLock = true;
    }

    // call it every frame 
    // callback function when picked up 
    update(playerSprite, onCollect){
       if (this.collected) return;

        // bob up and down based on sine wave 
        this.bobAngle += 2;
        this.sprite.y = this.baseY + Math.sin(this.bobAngle * 0.04) * 7;

        // slow spin for funsies 
        this.sprite.rotation += 1;

        // check if player overlap with fragment 
        if (playerSprite.overlaps(this.sprite)){
            //console.log('Player collected fragment');
            this.collect(onCollect);
        }
    }

    collect(onCollect) {
        this.collected = true;
        // save position BEFORE removing the sprite
        const x = this.sprite.x;
        const y = this.sprite.y;
        this.sprite.remove();
        onCollect(this.hexColor, x, y);
    }
    // draw color glow around fragment 
    // before drawing the sprite
    drawGlow(){
        if (this.collected) return;

        this.p5.push();
        this.p5.noStroke();

        // glow pulsates based on sine wave
        const pulse = Math.sin(this.bobAngle * 0.08) * 8;
        const glowSize = 45 + pulse;

        const col = this.p5.color(this.hexColor);
        col.setAlpha(60);
        this.p5.fill(col);
        this.p5.circle(this.sprite.x, this.sprite.y, glowSize);

        this.p5.pop();

    }
}