/* WaveBg — subtle dotted waves canvas, fills parent.
 * Props: color (rgb string, e.g. "110,201,214"), density (0.5..1.5), dim (0..1 max alpha)
 */
/* global React */
const { useEffect: _useEffect, useRef: _useRef } = React;

function WaveBg({ color = "110,201,214", density = 1, dim = 0.55 }) {
  const ref = _useRef(null);

  _useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    let W = 0, H = 0, raf = 0;

    const resize = () => {
      const r = canvas.getBoundingClientRect();
      W = r.width; H = r.height;
      canvas.width = Math.floor(W * dpr);
      canvas.height = Math.floor(H * dpr);
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(canvas);

    const t0 = performance.now();
    function frame(now) {
      const t = (now - t0) / 1000;
      ctx.clearRect(0, 0, W, H);

      // Dot grid spacing — adjusted by density
      const spacing = 14 / density;
      // 3 superposed sine layers for organic wave
      const waves = [
        { amp: 18, freq: 0.018, speed: 0.6, phase: 0 },
        { amp: 10, freq: 0.034, speed: -0.9, phase: 1.7 },
        { amp: 6,  freq: 0.07,  speed: 1.4,  phase: 3.1 },
      ];

      ctx.globalCompositeOperation = "lighter";
      for (let y = -10; y < H + 10; y += spacing) {
        for (let x = -10; x < W + 10; x += spacing) {
          // sum of waves drives a vertical offset
          let off = 0;
          for (const w of waves) {
            off += Math.sin(x * w.freq + t * w.speed + w.phase + y * 0.005) * w.amp;
          }
          const yy = y + off;
          // alpha depends on horizontal sine for a soft band feel
          const a = (0.5 + 0.5 * Math.sin(x * 0.012 + t * 0.4 + y * 0.01)) * dim;
          if (a < 0.04) continue;
          const r = 0.9 + 0.8 * Math.sin(x * 0.02 + t * 0.6 + y * 0.01);
          ctx.fillStyle = `rgba(${color}, ${a})`;
          ctx.beginPath();
          ctx.arc(x, yy, Math.max(0.4, r), 0, Math.PI * 2);
          ctx.fill();
        }
      }

      raf = requestAnimationFrame(frame);
    }
    raf = requestAnimationFrame(frame);
    return () => { cancelAnimationFrame(raf); ro.disconnect(); };
  }, [color, density, dim]);

  return <canvas ref={ref} className="wave-bg" aria-hidden="true" />;
}

Object.assign(window, { WaveBg });
