let canvas, ctx, particles = [], raf = null;

export function initCanvas() {
  canvas = document.getElementById('particles');
  if (!canvas) return;
  ctx = canvas.getContext('2d');
  resize();
  window.addEventListener('resize', resize);
}

function resize() {
  if (!canvas) return;
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
}

function loop() {
  if (!ctx) return;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  particles = particles.filter(p => {
    p.update();
    p.draw(ctx);
    return p.alive;
  });
  if (particles.length > 0) {
    raf = requestAnimationFrame(loop);
  } else {
    raf = null;
  }
}

function startLoop() {
  if (!raf) raf = requestAnimationFrame(loop);
}

export function confetti(x, y, count = 40) {
  const colors = ['#F5B731', '#00D4FF', '#8B5CF6', '#34D399', '#F87171', '#FBBF24'];
  for (let i = 0; i < count; i++) {
    const angle = (Math.PI * 2 * i) / count + (Math.random() - 0.5);
    const speed = 4 + Math.random() * 6;
    const size = 4 + Math.random() * 4;
    const color = colors[Math.floor(Math.random() * colors.length)];
    const spin = (Math.random() - 0.5) * 0.3;
    let life = 1;
    particles.push({
      x, y, vx: Math.cos(angle) * speed, vy: Math.sin(angle) * speed - 3,
      size, color, rotation: Math.random() * Math.PI * 2, spin, alive: true,
      update() {
        this.x += this.vx;
        this.y += this.vy;
        this.vy += 0.15;
        this.vx *= 0.98;
        this.rotation += this.spin;
        life -= 0.012;
        if (life <= 0 || this.y > canvas.height) this.alive = false;
      },
      draw(c) {
        c.save();
        c.translate(this.x, this.y);
        c.rotate(this.rotation);
        c.globalAlpha = life;
        c.fillStyle = this.color;
        c.fillRect(-this.size / 2, -this.size / 2, this.size, this.size * 0.6);
        c.restore();
      }
    });
  }
  startLoop();
}

export function coinBurst(x, y, count = 12) {
  for (let i = 0; i < count; i++) {
    const angle = -Math.PI / 2 + (Math.random() - 0.5) * 1.2;
    const speed = 3 + Math.random() * 4;
    let life = 1;
    particles.push({
      x, y, vx: Math.cos(angle) * speed, vy: Math.sin(angle) * speed,
      size: 6 + Math.random() * 3, alive: true,
      update() {
        this.x += this.vx;
        this.y += this.vy;
        this.vy += 0.12;
        life -= 0.018;
        if (life <= 0) this.alive = false;
      },
      draw(c) {
        c.globalAlpha = life;
        c.fillStyle = '#F5B731';
        c.beginPath();
        c.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        c.fill();
        c.globalAlpha = life * 0.6;
        c.fillStyle = '#FFF';
        c.beginPath();
        c.arc(this.x - this.size * 0.2, this.y - this.size * 0.2, this.size * 0.3, 0, Math.PI * 2);
        c.fill();
      }
    });
  }
  startLoop();
}
