/**
 * InfiniteGridBG
 * Animated infinite-scrolling grid pattern with a "flashlight" reveal layer
 * that follows the mouse — even when the cursor is over text/UI on top.
 *
 * Key: mousemove é ouvido no window e as coordenadas são calculadas relativas
 * ao próprio container, então o efeito funciona mesmo quando o ponteiro
 * passa por cima de elementos com z-index maior (texto, mockup, etc).
 *
 * O elemento NÃO captura eventos (pointer-events: none no CSS) — todo o
 * tracking acontece via window listener.
 */
const InfiniteGridBG = () => {
  const containerRef = React.useRef(null);
  const subtlePatternRef = React.useRef(null);
  const activePatternRef = React.useRef(null);
  const flashlightRef = React.useRef(null);
  const offsetRef = React.useRef({ x: 0, y: 0 });
  const mouseRef = React.useRef({ x: -9999, y: -9999, active: false });
  const rafRef = React.useRef(null);

  const GRID_SIZE = 56;
  const SPEED_X = 0.35;
  const SPEED_Y = 0.35;
  const FLASHLIGHT_R = 320;

  React.useEffect(() => {
    const tick = () => {
      // Advance scroll offsets
      offsetRef.current.x = (offsetRef.current.x + SPEED_X) % GRID_SIZE;
      offsetRef.current.y = (offsetRef.current.y + SPEED_Y) % GRID_SIZE;
      const { x, y } = offsetRef.current;

      if (subtlePatternRef.current) {
        subtlePatternRef.current.setAttribute('x', x);
        subtlePatternRef.current.setAttribute('y', y);
      }
      if (activePatternRef.current) {
        activePatternRef.current.setAttribute('x', x);
        activePatternRef.current.setAttribute('y', y);
      }

      // Update flashlight mask position
      if (flashlightRef.current) {
        const m = mouseRef.current;
        const mask = m.active
          ? `radial-gradient(${FLASHLIGHT_R}px circle at ${m.x}px ${m.y}px, black 0%, black 25%, transparent 75%)`
          : 'radial-gradient(0px circle at 50% 50%, transparent, transparent)';
        flashlightRef.current.style.maskImage = mask;
        flashlightRef.current.style.webkitMaskImage = mask;
      }

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

    // Window listener — funciona mesmo quando o cursor está sobre o texto
    const onMove = (e) => {
      const el = containerRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const inside =
        e.clientX >= rect.left && e.clientX <= rect.right &&
        e.clientY >= rect.top && e.clientY <= rect.bottom;
      if (inside) {
        mouseRef.current.x = e.clientX - rect.left;
        mouseRef.current.y = e.clientY - rect.top;
        mouseRef.current.active = true;
      } else {
        mouseRef.current.active = false;
      }
    };
    window.addEventListener('mousemove', onMove, { passive: true });

    return () => {
      cancelAnimationFrame(rafRef.current);
      window.removeEventListener('mousemove', onMove);
    };
  }, []);

  return (
    <div ref={containerRef} className="infinite-grid-bg">
      {/* Layer 1: Subtle baseline grid */}
      <svg className="igb-layer igb-subtle" aria-hidden="true">
        <defs>
          <pattern
            ref={subtlePatternRef}
            id="igb-pattern-subtle"
            width={GRID_SIZE}
            height={GRID_SIZE}
            patternUnits="userSpaceOnUse"
          >
            <path
              d={`M ${GRID_SIZE} 0 L 0 0 0 ${GRID_SIZE}`}
              fill="none"
              stroke="rgba(255,255,255,0.10)"
              strokeWidth="1"
            />
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill="url(#igb-pattern-subtle)" />
      </svg>

      {/* Layer 2: Highlighted grid revealed by flashlight */}
      <div ref={flashlightRef} className="igb-layer igb-flashlight">
        <svg className="igb-layer igb-active" aria-hidden="true">
          <defs>
            <pattern
              ref={activePatternRef}
              id="igb-pattern-active"
              width={GRID_SIZE}
              height={GRID_SIZE}
              patternUnits="userSpaceOnUse"
            >
              <path
                d={`M ${GRID_SIZE} 0 L 0 0 0 ${GRID_SIZE}`}
                fill="none"
                stroke="rgba(57,255,122,1)"
                strokeWidth="1.4"
              />
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill="url(#igb-pattern-active)" />
        </svg>
      </div>
    </div>
  );
};

window.InfiniteGridBG = InfiniteGridBG;
