import React from 'react';
import { styled, keyframes } from '@mui/system';

const particles = 62;
const particleSize = 8;
const radius = 80;
const lapDuration = 3;

const spinLeft = keyframes`
  from {
    opacity: 0.0;
  }
  to {
    opacity: 0.6;
    transform: translate3d(-${particleSize / 2}px, -${particleSize / 2}px, 570px);
  }
`;

const spinRight = keyframes`
  from {
    opacity: 0.0;
  }
  to {
    opacity: 0.6;
    transform: translate3d(${particleSize / 2}px, ${particleSize / 2}px, 570px) rotate(720deg);
  }
`;

const Wrapper = styled('div')`
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 2;
  perspective: 500px;
  background: #3e6fa3;
  transform: translate(-50%, -50%);
`;

const Particle = styled('i')`
  display: block;
  position: absolute;
  width: ${particleSize}px;
  height: ${particleSize}px;
  border-radius: ${particleSize}px;
  opacity: 0;
  background: rgba(0, 0, 255, 0.5);
  box-shadow: 0px 0px 10px rgba(0, 0, 255, 1);
  animation: ${spinLeft} ${lapDuration}s infinite ease-in-out;
`;

const RedParticle = styled('i')`
  display: block;
  position: absolute;
  width: ${particleSize}px;
  height: ${particleSize}px;
  border-radius: ${particleSize}px;
  opacity: 0;
  background: rgba(255, 0, 0, 0.5);
  box-shadow: 0px 0px 10px rgba(255, 0, 0, 1);
  animation: ${spinRight} ${lapDuration}s infinite ease-in-out;
`;

const CloudSpiralBackground = ({ children }) => {
  const particlesArray = Array.from({ length: particles });

  return (
    <Wrapper>
      {particlesArray.map((_, i) => {
        const angle = (i / particles) * 720;
        const delay = i * (lapDuration / particles);
        const transform = `rotate(${angle}deg) translate3d(${radius}px, 0, 0)`;

        return (
          <React.Fragment key={i}>
            <Particle
              style={{
                transform,
                animationDelay: `${delay}s`,
              }}
            />
            <RedParticle
              style={{
                transform,
                animationDelay: `${delay}s`,
              }}
            />
          </React.Fragment>
        );
      })}
      {children}
    </Wrapper>
  );
};

export default CloudSpiralBackground;
