import React, { useEffect, useRef } from 'react';
import { styled } from '@mui/system';

const CanvasWrapper = styled('div')`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
`;

const SimplexNoiseBackground = ({ children }) => {
  const canvasRef = useRef(null);

  useEffect(() => {
    // Dynamically load the simplex-noise script
    const script = document.createElement('script');
    script.src = 'https://rawgithub.com/jwagner/simplex-noise.js/master/simplex-noise.js';
    script.onload = () => {
      const SimplexNoise = window.SimplexNoise;
      const simplex = new SimplexNoise();
      const canvas = canvasRef.current;
      const ctx = canvas.getContext('2d');
      const imgdata = ctx.createImageData(canvas.width, canvas.height);
      const data = imgdata.data;
      let t = 0;

      const render = () => {
        for (let x = 0; x < canvas.width; x++) {
          for (let y = 0; y < canvas.height; y++) {
            const r = simplex.noise3D(x / 110, y / 300, t / 100);
            const g = simplex.noise3D(x / 140, y / 300, t / 100);
            const b = simplex.noise3D(x / 130, y / 330, t / 130);
            data[(x + y * canvas.width) * 4 + 0] = (r + b) * 255 / 3;
            data[(x + y * canvas.width) * 4 + 1] = (g + r) * 255 / 3;
            data[(x + y * canvas.width) * 4 + 2] = (b + r + g) * 255 / 3;
            data[(x + y * canvas.width) * 4 + 3] = 255;
          }
        }
        t++;
        ctx.putImageData(imgdata, 0, 0);
        requestAnimationFrame(render);
      };

      render();
    };
    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    };
  }, []);

  return (
    <CanvasWrapper>
      <canvas ref={canvasRef} width={256} height={256} style={{ width: '100%', height: '100%' }} />
      {children}
    </CanvasWrapper>
  );
};

export default SimplexNoiseBackground;
