// InteractiveGradient.jsx
// Cursor-tracking, orbiting radial-gradient blobs — port of Framer's
// "Interactive_animated_gradient" component, vanilla React (no framer-motion),
// recolored to the Team Girl palette.

function TgInteractiveGradient({
  colors = ["#EA21A2", "#EF512C", "#FFA161"],   // magenta, orange, peach
  baseColor = "#7A0E55",                         // deep magenta wash behind blobs
  loopDuration = 16,                             // seconds per orbit
  orbitRadius = 28,                              // % of box
  followStrength = 0.42,                         // how much cursor tugs blob 1
  blur = 60,                                     // px
  brightness = 1.05,
  springStiffness = 0.18,                        // 0..1 — smoothing of cursor follow per frame (~60fps)
  reduceMotion = false,
  children,
  className = "",
  style = {},
}) {
  const wrapRef  = React.useRef(null);
  const blobRef  = React.useRef(null);
  const stateRef = React.useRef({
    tx: 50, ty: 50,   // target (cursor) — normalized 0..100
    cx: 50, cy: 50,   // current (smoothed)
    phase: 0,
    last: 0,
    inside: false,
  });

  // --- pointer tracking on the WRAPPER (so children can sit on top untouched) ---
  React.useEffect(() => {
    const el = wrapRef.current;
    if (!el) return;

    const handleMove = (e) => {
      const r = el.getBoundingClientRect();
      const x = ((e.clientX - r.left) / r.width)  * 100;
      const y = ((e.clientY - r.top)  / r.height) * 100;
      const s = stateRef.current;
      s.tx = Math.max(-10, Math.min(110, x));
      s.ty = Math.max(-10, Math.min(110, y));
      s.inside = true;
    };
    const handleLeave = () => {
      const s = stateRef.current;
      s.tx = 50;
      s.ty = 50;
      s.inside = false;
    };

    // window-level pointer so we get tracking even while hovering child elements
    const onWinMove = (e) => {
      const r = el.getBoundingClientRect();
      const pad = 24;
      const inside =
        e.clientX >= r.left - pad && e.clientX <= r.right  + pad &&
        e.clientY >= r.top  - pad && e.clientY <= r.bottom + pad;
      if (inside) handleMove(e);
      else if (stateRef.current.inside) handleLeave();
    };

    window.addEventListener("pointermove", onWinMove, { passive: true });
    return () => window.removeEventListener("pointermove", onWinMove);
  }, []);

  // --- animation loop: orbit phase + spring toward cursor ---
  React.useEffect(() => {
    if (reduceMotion) return;
    let raf = 0;
    const tick = (t) => {
      const s = stateRef.current;
      const dt = s.last ? Math.min(0.05, (t - s.last) / 1000) : 0.016;
      s.last = t;

      // smooth toward target (frame-rate-independent approx)
      const k = 1 - Math.pow(1 - springStiffness, dt * 60);
      s.cx += (s.tx - s.cx) * k;
      s.cy += (s.ty - s.cy) * k;

      // orbit phase
      s.phase += (dt / loopDuration) * Math.PI * 2;

      const x1 = 50 + (s.cx - 50) * followStrength;
      const y1 = 50 + (s.cy - 50) * followStrength;
      const x2 = 50 + Math.cos(s.phase) * orbitRadius;
      const y2 = 50 + Math.sin(s.phase) * orbitRadius;
      const x3 = 50 + Math.cos(s.phase + (2 * Math.PI) / 3) * orbitRadius;
      const y3 = 50 + Math.sin(s.phase + (2 * Math.PI) / 3) * orbitRadius;

      const b = blobRef.current;
      if (b) {
        b.style.setProperty("--x1", x1 + "%");
        b.style.setProperty("--y1", y1 + "%");
        b.style.setProperty("--x2", x2 + "%");
        b.style.setProperty("--y2", y2 + "%");
        b.style.setProperty("--x3", x3 + "%");
        b.style.setProperty("--y3", y3 + "%");
      }

      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [loopDuration, orbitRadius, followStrength, springStiffness, reduceMotion]);

  // The composite background — 3 stacked radial gradients, each driven by its own CSS vars.
  const gradient = `
    radial-gradient(circle at var(--x1) var(--y1),
      ${colors[0]} 0%, ${colors[0]} 22%, rgba(0,0,0,0) 60%),
    radial-gradient(circle at var(--x2) var(--y2),
      ${colors[1]} 0%, ${colors[1]} 22%, rgba(0,0,0,0) 60%),
    radial-gradient(circle at var(--x3) var(--y3),
      ${colors[2]} 0%, ${colors[2]} 22%, rgba(0,0,0,0) 60%)
  `;

  return (
    <div
      ref={wrapRef}
      className={className}
      style={{ position: "relative", overflow: "hidden", ...style }}
    >
      {/* Blurred gradient layer — sits behind everything; pointer-events: none so children get clicks. */}
      <div
        ref={blobRef}
        aria-hidden="true"
        style={{
          position: "absolute",
          // overscan so blur edges don't fade in at the corners
          inset: `-${blur + 20}px`,
          background: gradient,
          backgroundColor: baseColor,
          filter: `blur(${blur}px) brightness(${brightness})`,
          willChange: "background",
          pointerEvents: "none",
          // initial values so the very first paint isn't unstyled
          "--x1": "50%", "--y1": "50%",
          "--x2": "78%", "--y2": "50%",
          "--x3": "36%", "--y3": "74%",
        }}
      />
      {children}
    </div>
  );
}

window.TgInteractiveGradient = TgInteractiveGradient;
