export class ParticleSystem {
  constructor() {
    this.list = [];
    this.enabled = true;
  }

  clear() {
    this.list.length = 0;
  }

  spawn(x, y, kind, extra = {}) {
    if (!this.enabled) return;
    const n = extra.n || (kind === 'splash' ? 28 : kind === 'win' ? 48 : 12);
    for (let i = 0; i < n; i++) {
      const a =
        extra.angle != null
          ? extra.angle + (Math.random() - 0.5) * (extra.spread || 1.2)
          : Math.random() * Math.PI * 2;
      const spd =
        (extra.speed || 80) * (0.4 + Math.random() * 0.9) *
        (kind === 'win' ? 1.6 : 1);
      const life = extra.life || (kind === 'spark' ? 0.45 : kind === 'win' ? 1.4 : 0.7);
      this.list.push({
        x,
        y,
        vx: Math.cos(a) * spd,
        vy: Math.sin(a) * spd,
        life,
        max: life,
        r: extra.r || (kind === 'drip' ? 2.2 : 2 + Math.random() * 2.4),
        kind,
        color: extra.color || '#5cffd4',
        g: extra.g != null ? extra.g : kind === 'splash' || kind === 'drip' ? 380 : 40,
      });
    }
  }

  drip(x, y, color) {
    if (!this.enabled) return;
    if (Math.random() > 0.35) return;
    this.list.push({
      x: x + (Math.random() - 0.5) * 6,
      y: y + (Math.random() - 0.5) * 6,
      vx: (Math.random() - 0.5) * 12,
      vy: 18 + Math.random() * 24,
      life: 0.5 + Math.random() * 0.35,
      max: 0.7,
      r: 1.4 + Math.random() * 1.6,
      kind: 'drip',
      color,
      g: 220,
    });
  }

  update(dt) {
    const list = this.list;
    for (let i = list.length - 1; i >= 0; i--) {
      const p = list[i];
      p.life -= dt;
      if (p.life <= 0) {
        list.splice(i, 1);
        continue;
      }
      p.vy += p.g * dt;
      p.x += p.vx * dt;
      p.y += p.vy * dt;
      p.vx *= 0.98;
    }
    if (list.length > 700) list.splice(0, list.length - 700);
  }

  draw(ctx) {
    for (const p of this.list) {
      const t = p.life / p.max;
      ctx.globalAlpha = Math.max(0, t);
      ctx.fillStyle = p.color;
      ctx.beginPath();
      ctx.arc(p.x, p.y, p.r * (0.6 + 0.4 * t), 0, Math.PI * 2);
      ctx.fill();
    }
    ctx.globalAlpha = 1;
  }
}
