/* SystemGridBackground.jsx
   Grid escuro discreto: pontos numa malha + linhas conectando vizinhos,
   com leve respiração/parallax. Canvas + requestAnimationFrame.
   - Baixa densidade (perf mobile), opacidade baixa, não atrapalha leitura.
   - prefers-reduced-motion: desenha 1 frame estático.
   Edite: SPACING (densidade), DOT/LINE colors, drift (velocidade). */
function SystemGridBackground() {
  const reduced = useReducedMotion();
  const canvasRef = React.useRef(null);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    let raf, w, h, dpr, nodes = [], t = 0, running = true;

    const SPACING = window.innerWidth < 640 ? 64 : 52; // px entre nós
    const css = getComputedStyle(document.documentElement);
    const blue = css.getPropertyValue("--blue").trim() || "#38BDF8";
    const green = css.getPropertyValue("--green").trim() || "#A3E635";

    function build() {
      dpr = Math.min(window.devicePixelRatio || 1, 2);
      w = canvas.clientWidth; h = canvas.clientHeight;
      canvas.width = w * dpr; canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      nodes = [];
      const cols = Math.ceil(w / SPACING) + 2;
      const rows = Math.ceil(h / SPACING) + 2;
      for (let i = 0; i < cols; i++) {
        for (let j = 0; j < rows; j++) {
          nodes.push({
            x: i * SPACING, y: j * SPACING,
            // pequena variação de fase para a "respiração"
            phase: (i * 0.7 + j * 1.3),
            // raros nós "ativos" piscam em verde/azul
            active: Math.random() < 0.05,
            hue: Math.random() < 0.5 ? blue : green,
          });
        }
      }
    }

    function draw() {
      ctx.clearRect(0, 0, w, h);
      const amp = 3.2; // deslocamento máx dos nós
      // posições animadas
      for (const n of nodes) {
        n.cx = n.x + Math.sin(t * 0.0006 + n.phase) * amp;
        n.cy = n.y + Math.cos(t * 0.0005 + n.phase) * amp;
      }
      // linhas para vizinhos à direita/baixo (malha)
      ctx.lineWidth = 1;
      ctx.strokeStyle = "rgba(148,163,184,0.06)";
      ctx.beginPath();
      const cols = Math.ceil(w / SPACING) + 2;
      const rows = Math.ceil(h / SPACING) + 2;
      const idx = (i, j) => i * rows + j;
      for (let i = 0; i < cols; i++) {
        for (let j = 0; j < rows; j++) {
          const a = nodes[idx(i, j)]; if (!a) continue;
          const r = nodes[idx(i + 1, j)];
          const d = nodes[idx(i, j + 1)];
          if (r) { ctx.moveTo(a.cx, a.cy); ctx.lineTo(r.cx, r.cy); }
          if (d) { ctx.moveTo(a.cx, a.cy); ctx.lineTo(d.cx, d.cy); }
        }
      }
      ctx.stroke();
      // pontos
      for (const n of nodes) {
        if (n.active) {
          const pulse = 0.35 + 0.35 * (0.5 + 0.5 * Math.sin(t * 0.0018 + n.phase));
          ctx.fillStyle = n.hue;
          ctx.globalAlpha = pulse * 0.5;
          ctx.beginPath(); ctx.arc(n.cx, n.cy, 1.8, 0, Math.PI * 2); ctx.fill();
          ctx.globalAlpha = 1;
        } else {
          ctx.fillStyle = "rgba(148,163,184,0.16)";
          ctx.beginPath(); ctx.arc(n.cx, n.cy, 1, 0, Math.PI * 2); ctx.fill();
        }
      }
    }

    function loop(now) {
      if (!running) return;
      t = now;
      draw();
      raf = requestAnimationFrame(loop);
    }

    build();
    if (reduced) { t = 1200; draw(); }
    else raf = requestAnimationFrame(loop);

    const onResize = () => { build(); if (reduced) draw(); };
    window.addEventListener("resize", onResize);
    // pausa quando a aba não está visível (economia de bateria)
    const onVis = () => {
      if (document.hidden) { running = false; cancelAnimationFrame(raf); }
      else if (!reduced) { running = true; raf = requestAnimationFrame(loop); }
    };
    document.addEventListener("visibilitychange", onVis);

    return () => {
      running = false; cancelAnimationFrame(raf);
      window.removeEventListener("resize", onResize);
      document.removeEventListener("visibilitychange", onVis);
    };
  }, [reduced]);

  return (
    <canvas
      ref={canvasRef}
      aria-hidden="true"
      style={{
        position: "fixed", inset: 0, width: "100%", height: "100%",
        zIndex: 0, pointerEvents: "none",
        // máscara radial: mais visível nas bordas, some no centro p/ não atrapalhar leitura
        WebkitMaskImage: "radial-gradient(120% 90% at 50% 30%, transparent 28%, #000 100%)",
        maskImage: "radial-gradient(120% 90% at 50% 30%, transparent 28%, #000 100%)",
        opacity: 0.9,
      }}
    />
  );
}

Object.assign(window, { SystemGridBackground });
