export class Effects {
  constructor() {
    this.particles = [];
    this.labels = [];
    this.flash = 0;
    this.shake = 0;
  }

  burst(x, y, color, text, harmful = false) {
    for (let i = 0; i < 18; i++) {
      const angle = Math.random() * Math.PI * 2;
      const speed = 55 + Math.random() * 170;
      this.particles.push({
        x, y,
        vx: Math.cos(angle) * speed,
        vy: Math.sin(angle) * speed,
        age: 0,
        life: .42 + Math.random() * .38,
        size: 2 + Math.random() * 4,
        color
      });
    }
    this.labels.push({ x, y, text, age: 0, life: .85, color });
    if (harmful) {
      this.flash = .22;
      this.shake = 8;
    }
  }

  explosion(x, y, color) {
    for (let i = 0; i < 95; i++) {
      const angle = Math.random() * Math.PI * 2;
      const speed = 90 + Math.random() * 420;
      this.particles.push({
        x, y,
        vx: Math.cos(angle) * speed,
        vy: Math.sin(angle) * speed,
        age: 0,
        life: .65 + Math.random() * 1.05,
        size: 3 + Math.random() * 8,
        color: Math.random() > .38 ? color : '#fff1b0'
      });
    }
    this.flash = .72;
    this.shake = 22;
  }

  get active() {
    return this.particles.length > 0 || this.labels.length > 0 || this.flash > 0 || this.shake > 0;
  }

  update(delta) {
    for (const p of this.particles) {
      p.age += delta;
      p.x += p.vx * delta;
      p.y += p.vy * delta;
      p.vx *= .97;
      p.vy *= .97;
      p.vy += 38 * delta;
    }
    for (const label of this.labels) {
      label.age += delta;
      label.y -= 42 * delta;
    }
    this.particles = this.particles.filter(p => p.age < p.life);
    this.labels = this.labels.filter(label => label.age < label.life);
    this.flash = Math.max(0, this.flash - delta);
    this.shake = Math.max(0, this.shake - delta * 24);
  }

  draw(ctx, width, height) {
    for (const p of this.particles) {
      const alpha = 1 - p.age / p.life;
      ctx.globalAlpha = alpha;
      ctx.fillStyle = p.color;
      ctx.fillRect(p.x, p.y, p.size, p.size);
    }
    ctx.globalAlpha = 1;

    for (const label of this.labels) {
      const alpha = 1 - label.age / label.life;
      ctx.globalAlpha = alpha;
      ctx.fillStyle = label.color;
      ctx.font = '800 18px Segoe UI, Arial';
      ctx.textAlign = 'center';
      ctx.fillText(label.text, label.x, label.y);
    }
    ctx.globalAlpha = 1;

    if (this.flash > 0) {
      ctx.fillStyle = `rgba(255,45,0,${this.flash})`;
      ctx.fillRect(0, 0, width, height);
    }
  }

  reset() {
    this.particles.length = 0;
    this.labels.length = 0;
    this.flash = 0;
    this.shake = 0;
  }
}
