/* global React */
const { useEffect, useRef } = React;

function AnimatedBackground({ enabled = true }) {
  const canvasRef = useRef(null);
  const rafRef = useRef(0);

  useEffect(() => {
    if (!enabled) return;
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const dpr = Math.min(window.devicePixelRatio || 1, 2);

    let w = 0, h = 0, scrollY = 0;
    const resize = () => {
      w = window.innerWidth;
      h = window.innerHeight;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      canvas.style.width = w + 'px';
      canvas.style.height = h + 'px';
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    const onScroll = () => { scrollY = window.scrollY || window.pageYOffset || 0; };
    resize();
    onScroll();
    window.addEventListener('resize', resize);
    window.addEventListener('scroll', onScroll, { passive: true });

    const getAccent = () => {
      const v = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim();
      return v || '#3ee4d4';
    };

    const docH = () => Math.max(document.documentElement.scrollHeight, h * 4);
    const PARTICLES = 90;
    const particles = Array.from({ length: PARTICLES }, () => ({
      x: Math.random() * (w || 1400),
      y: Math.random() * docH(),
      r: 0.4 + Math.random() * 1.6,
      vx: (Math.random() - 0.5) * 0.15,
      vy: (Math.random() - 0.5) * 0.15,
      a: 0.15 + Math.random() * 0.5,
      phase: Math.random() * Math.PI * 2,
    }));

    const _hexCache = {};
    function hexWithAlpha(color, alpha) {
      let rgb = _hexCache[color];
      if (!rgb) {
        const probe = document.createElement('div');
        probe.style.color = color;
        document.body.appendChild(probe);
        const computed = getComputedStyle(probe).color;
        document.body.removeChild(probe);
        const m = computed.match(/\d+/g);
        rgb = m ? `${m[0]}, ${m[1]}, ${m[2]}` : '62, 228, 212';
        _hexCache[color] = rgb;
      }
      return `rgba(${rgb}, ${alpha})`;
    }

    let t = 0;
    const draw = () => {
      t += 0.004;
      ctx.clearRect(0, 0, w, h);
      const accent = getAccent();

      const BAND_H = 900;
      const layers = [
        { amp: 70, freq: 0.0035, speed: 0.6, off: 0, alpha: 0.045 },
        { amp: 100, freq: 0.0025, speed: 0.4, off: 320, alpha: 0.035 },
        { amp: 130, freq: 0.0018, speed: 0.25, off: 640, alpha: 0.030 },
      ];

      const firstBand = Math.floor((scrollY - BAND_H) / BAND_H);
      const lastBand = Math.ceil((scrollY + h + BAND_H) / BAND_H);

      layers.forEach((L, idx) => {
        for (let b = firstBand; b <= lastBand; b++) {
          const yOffDoc = b * BAND_H + L.off;
          const yOff = yOffDoc - scrollY;
          if (yOff < -L.amp - 50 || yOff > h + L.amp + 50) continue;
          ctx.beginPath();
          ctx.moveTo(0, yOff + L.amp + 200);
          for (let x = 0; x <= w; x += 8) {
            const y = yOff +
              Math.sin(x * L.freq + t * L.speed * 8 + b * 0.7) * L.amp +
              Math.cos(x * L.freq * 1.7 + t * L.speed * 5 + idx + b) * (L.amp * 0.4);
            ctx.lineTo(x, y);
          }
          ctx.lineTo(w, yOff + L.amp + 200);
          ctx.closePath();
          const grad = ctx.createLinearGradient(0, yOff - L.amp, 0, yOff + L.amp + 200);
          grad.addColorStop(0, hexWithAlpha(accent, 0));
          grad.addColorStop(0.5, hexWithAlpha(accent, L.alpha));
          grad.addColorStop(1, hexWithAlpha(accent, 0));
          ctx.fillStyle = grad;
          ctx.fill();
        }
      });

      // Aurora blob
      const bx = w * 0.5 + Math.sin(t * 0.6) * w * 0.2;
      const by = h * 0.4 + Math.cos(t * 0.5) * h * 0.15;
      const blobR = Math.min(w, h) * 0.55;
      const blobGrad = ctx.createRadialGradient(bx, by, 0, bx, by, blobR);
      blobGrad.addColorStop(0, hexWithAlpha(accent, 0.08));
      blobGrad.addColorStop(0.5, hexWithAlpha(accent, 0.025));
      blobGrad.addColorStop(1, hexWithAlpha(accent, 0));
      ctx.fillStyle = blobGrad;
      ctx.fillRect(0, 0, w, h);

      // Particles
      const dh = docH();
      particles.forEach((p) => {
        p.x += p.vx + Math.sin(t * 2 + p.phase) * 0.05;
        p.y += p.vy + Math.cos(t * 1.5 + p.phase) * 0.04;
        if (p.x < -10) p.x = w + 10;
        if (p.x > w + 10) p.x = -10;
        if (p.y < -10) p.y = dh + 10;
        if (p.y > dh + 10) p.y = -10;
        const yView = p.y - scrollY;
        if (yView < -10 || yView > h + 10) return;
        ctx.beginPath();
        ctx.arc(p.x, yView, p.r, 0, Math.PI * 2);
        ctx.fillStyle = hexWithAlpha(accent, p.a * (0.5 + 0.5 * Math.sin(t * 3 + p.phase)));
        ctx.fill();
      });

      rafRef.current = requestAnimationFrame(draw);
    };
    draw();

    return () => {
      cancelAnimationFrame(rafRef.current);
      window.removeEventListener('resize', resize);
      window.removeEventListener('scroll', onScroll);
    };
  }, [enabled]);

  if (!enabled) return null;
  return React.createElement('canvas', { ref: canvasRef, className: 'bg-canvas', 'aria-hidden': 'true' });
}

window.AnimatedBackground = AnimatedBackground;
