import { useEffect } from 'react';
import confetti from 'canvas-confetti';

interface ConfettiProps {
  active?: boolean;
  duration?: number;
}

export const Confetti: React.FC<ConfettiProps> = ({ active = false, duration = 3000 }) => {
  useEffect(() => {
    if (!active) return;

    const end = Date.now() + duration;

    const colors = ['#007AFF', '#34C759', '#FF3B30', '#FF9500', '#AF52DE'];

    const frame = () => {
      confetti({
        particleCount: 2,
        angle: 60,
        spread: 55,
        origin: { x: 0 },
        colors: colors
      });

      confetti({
        particleCount: 2,
        angle: 120,
        spread: 55,
        origin: { x: 1 },
        colors: colors
      });

      if (Date.now() < end) {
        requestAnimationFrame(frame);
      }
    };

    frame();

    // Cleanup
    return () => {
      confetti.reset();
    };
  }, [active, duration]);

  return null;
};

// Celebration confetti burst
export const celebrationConfetti = () => {
  const count = 200;
  const defaults = {
    origin: { y: 0.7 }
  };

  function fire(particleRatio: number, opts: confetti.Options) {
    confetti({
      ...defaults,
      ...opts,
      particleCount: Math.floor(count * particleRatio)
    });
  }

  fire(0.25, {
    spread: 26,
    startVelocity: 55
  });

  fire(0.2, {
    spread: 60
  });

  fire(0.35, {
    spread: 100,
    decay: 0.91,
    scalar: 0.8
  });

  fire(0.1, {
    spread: 120,
    startVelocity: 25,
    decay: 0.92,
    scalar: 1.2
  });

  fire(0.1, {
    spread: 120,
    startVelocity: 45
  });
};
