import React from 'react';
import { styled, keyframes, css } from '@mui/system';

const num = 20;

const shadowValue = (radius, cosV, sinV, bokeh, lineColor) => {
  return `
    ${radius * cosV}px ${radius * sinV}px ${bokeh}px ${lineColor},
    ${(radius - 1) * cosV}px ${(radius - 1) * sinV}px ${bokeh}px ${lineColor},
    ${radius / 1.8 * cosV}px ${radius / 1.8 * sinV}px ${bokeh}px ${lineColor},
    ${(radius / 1.8 - 1) * cosV}px ${(radius / 1.8 - 1) * sinV}px ${bokeh}px ${lineColor},
    ${radius / 2 * cosV}px ${radius / 2 * sinV}px ${bokeh}px ${lineColor},
    ${radius / 10 * cosV}px ${radius / 10 * sinV}px ${bokeh}px ${lineColor}
  `;
};

const ringEffect = (n, radius, bokeh, lineColor) => {
  let value = '0px 0px #FFF';
  for (let i = 0; i <= n; i++) {
    const radian = ((360 / n) * i * Math.PI) / 180;
    value += `, ${shadowValue(radius, Math.cos(radian), Math.sin(radian), bokeh, lineColor)}`;
  }
  return value;
};

const patternAnimation = (i) => keyframes`
  0% {
    opacity: 0;
  }
  40% {
    opacity: 0;
    transform: scale(0.1);
  }
  50% {
    opacity: 1;
  }
  100% {
    transform: scale(${Math.random() * 7});
    opacity: 0;
  }
`;

const Firework = styled('div')`
  position: absolute;
  top: ${({ rand1 }) => rand1};
  left: ${({ rand2 }) => rand2};

  .ring_1,
  .ring_2 {
    width: 1px;
    height: 1px;
  }

  .ring_1 {
    box-shadow: ${({ color }) => ringEffect(30, 30, 0, color)};
  }

  .ring_2 {
    box-shadow: ${({ color }) => ringEffect(30, 30, 2, color)};
  }

  ${({ index }) =>
    css`
      animation: ${patternAnimation(index)} ${Math.random() * 8 + 2}s ease infinite;
    `}
`;

const FireworkerWrapper = styled('div')`
  overflow: hidden;
  height: 100%;
  background: radial-gradient(ellipse at bottom, #192e47 0%, #030617 100%);
  position: relative;
  width: 100%;
`;

const FireworkerBackground = ({ children }) => {
  return (
    <FireworkerWrapper>
      {Array.from({ length: num }).map((_, i) => {
        const rand1 = `${Math.random() * 100}%`;
        const rand2 = `${Math.random() * 100}%`;
        const color = `hsl(${Math.random() * 240}, 70%, 70%)`;

        return (
          <Firework key={i} rand1={rand1} rand2={rand2} color={color} index={i}>
            <div className="ring_1"></div>
            <div className="ring_2"></div>
          </Firework>
        );
      })}
      {children}
    </FireworkerWrapper>
  );
};

export default FireworkerBackground;
