import React, { useEffect } from 'react';
import { styled } from '@mui/system';

const ConfettiWrapper = styled('div')`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  background: transparent;
  overflow: hidden;
`;

const ConfettiBackground = ({ children }) => {
  useEffect(() => {
    const canvas = document.getElementById('confettiCanvas');
    const ctx = canvas.getContext('2d');
    const confetti = [];

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    function Confetto(x, y) {
      this.x = x;
      this.y = y;
      this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
      this.size = Math.random() * 5 + 5;
      this.speed = Math.random() * 3 + 1;
      this.opacity = Math.random() * 0.5 + 0.5;
      this.angle = Math.random() * Math.PI * 2;
    }

    Confetto.prototype.update = function() {
      this.y += this.speed;
      this.x += Math.sin(this.angle);
      if (this.y > canvas.height) {
        this.y = 0;
        this.x = Math.random() * canvas.width;
      }
    };

    Confetto.prototype.draw = function() {
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
      ctx.fillStyle = `hsla(${Math.random() * 360}, 100%, 50%, ${this.opacity})`;
      ctx.fill();
    };

    function loop() {
      requestAnimationFrame(loop);

      ctx.clearRect(0, 0, canvas.width, canvas.height);

      let i = confetti.length;
      while (i--) {
        confetti[i].update();
        confetti[i].draw();
      }
    }

    function createConfetti() {
      let confettiCount = 100;
      while (confettiCount--) {
        confetti.push(new Confetto(Math.random() * canvas.width, Math.random() * canvas.height));
      }
    }

    createConfetti();
    loop();
  }, []);

  return (
    <ConfettiWrapper>
      <canvas id="confettiCanvas"></canvas>
      {children}
    </ConfettiWrapper>
  );
};

export default ConfettiBackground;
