/* global React */
// Background.jsx — animated mesh blobs + concentric rings + grain + mouse parallax

function Background({ animMult }) {
  const wrapRef = React.useRef(null);
  const layersRef = React.useRef([]);

  // mouse parallax (disabled when animations are off)
  React.useEffect(() => {
    if (animMult <= 0) return;
    let raf = 0;
    let tx = 0, ty = 0, cx = 0, cy = 0;
    const onMove = (e) => {
      const w = window.innerWidth, h = window.innerHeight;
      tx = (e.clientX / w - 0.5);
      ty = (e.clientY / h - 0.5);
    };
    const tick = () => {
      cx += (tx - cx) * 0.06;
      cy += (ty - cy) * 0.06;
      layersRef.current.forEach((el, i) => {
        if (!el) return;
        const depth = (i + 1) * 14 * animMult;
        el.style.setProperty('--px', `${-cx * depth}px`);
        el.style.setProperty('--py', `${-cy * depth}px`);
      });
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener('mousemove', onMove);
    raf = requestAnimationFrame(tick);
    return () => { window.removeEventListener('mousemove', onMove); cancelAnimationFrame(raf); };
  }, [animMult]);

  const dur = (base) => animMult <= 0 ? '0s' : `${base / Math.max(animMult, 0.35)}s`;

  const blobs = [
    { c: 'var(--blob-1)', w: 620, h: 620, top: '-12%', left: '-8%',  anim: 'drift1', d: 22, depth: 0 },
    { c: 'var(--blob-2)', w: 540, h: 540, top: '30%',  left: '62%',  anim: 'drift2', d: 28, depth: 1 },
    { c: 'var(--blob-3)', w: 460, h: 460, top: '58%',  left: '4%',   anim: 'drift3', d: 25, depth: 2 },
    { c: 'var(--blob-4)', w: 380, h: 380, top: '-6%',  left: '52%',  anim: 'drift4', d: 30, depth: 1 },
  ];

  return (
    <div className="bg-wrap" ref={wrapRef}>
      {/* concentric rings */}
      <div
        className="bg-rings"
        ref={(el) => (layersRef.current[0] = el)}
        style={{ transform: 'translate(calc(-50% + var(--px,0px)), calc(-46% + var(--py,0px)))' }}
      >
        {[1400, 1080, 760, 460].map((s, i) => (
          <span key={i} style={{ width: s, height: s }} />
        ))}
      </div>

      {/* color blobs — parallax wrapper + animated inner */}
      {blobs.map((b, i) => (
        <div
          key={i}
          ref={(el) => (layersRef.current[i + 1] = el)}
          style={{
            position: 'absolute', top: b.top, left: b.left,
            transform: 'translate(var(--px,0px), var(--py,0px))',
          }}
        >
          <div
            className="blob"
            style={{
              width: b.w, height: b.h,
              background: b.c,
              animation: `${b.anim} ${dur(b.d)} ease-in-out infinite`,
            }}
          />
        </div>
      ))}

      <div className="bg-aurora" style={{ animationDuration: dur(18) }} />
      <div className="bg-grain" />
      <div className="bg-vignette" />
    </div>
  );
}

window.Background = Background;
