// Confetti / celebration effect
const { useEffect, useRef } = React;

function Confetti({ trigger, palette = ['#F4D1D8', '#CFE8D7', '#C7DDEF', '#F6EFD9', '#FBF6EE'], burst = 60, origin = null }) {
  const canvasRef = useRef(null);
  const particlesRef = useRef([]);
  const rafRef = useRef(null);

  useEffect(() => {
    if (!trigger) return;
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const resize = () => {
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
    };
    resize();
    window.addEventListener('resize', resize);

    const ox = origin?.x ?? canvas.width / 2;
    const oy = origin?.y ?? canvas.height / 3;

    for (let i = 0; i < burst; i++) {
      particlesRef.current.push({
        x: ox + (Math.random() - 0.5) * 40,
        y: oy,
        vx: (Math.random() - 0.5) * 10,
        vy: -Math.random() * 12 - 4,
        rot: Math.random() * Math.PI * 2,
        vr: (Math.random() - 0.5) * 0.3,
        w: 8 + Math.random() * 8,
        h: 4 + Math.random() * 6,
        color: palette[Math.floor(Math.random() * palette.length)],
        life: 0,
        maxLife: 120 + Math.random() * 60,
        shape: Math.random() > 0.5 ? 'rect' : 'circle',
      });
    }

    const tick = () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      particlesRef.current = particlesRef.current.filter(p => {
        p.life++;
        p.vy += 0.35; // gravity
        p.vx *= 0.99;
        p.x += p.vx;
        p.y += p.vy;
        p.rot += p.vr;
        const alpha = Math.max(0, 1 - p.life / p.maxLife);
        ctx.save();
        ctx.globalAlpha = alpha;
        ctx.translate(p.x, p.y);
        ctx.rotate(p.rot);
        ctx.fillStyle = p.color;
        if (p.shape === 'rect') {
          ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);
        } else {
          ctx.beginPath();
          ctx.arc(0, 0, p.w / 2, 0, Math.PI * 2);
          ctx.fill();
        }
        ctx.restore();
        return p.life < p.maxLife && p.y < canvas.height + 50;
      });
      if (particlesRef.current.length > 0) {
        rafRef.current = requestAnimationFrame(tick);
      }
    };
    rafRef.current = requestAnimationFrame(tick);

    return () => {
      cancelAnimationFrame(rafRef.current);
      window.removeEventListener('resize', resize);
    };
  }, [trigger]);

  return (
    <canvas
      ref={canvasRef}
      style={{
        position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 9999,
      }}
    />
  );
}

window.Confetti = Confetti;
