// Animated "AI techy" background - particle neural mesh on a canvas.
const { useEffect: useEffectBg, useRef: useRefBg } = React;

function AIBackground() {
  const canvasRef = useRefBg(null);

  useEffectBg(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let raf, w, h, dpr;
    let nodes = [];
    const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    function readVar(name, fallback) {
      const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
      return v || fallback;
    }
    let accent = '61,122,255';
    let accent2 = '94,230,255';
    function hexToRgb(hex) {
      hex = hex.replace('#','');
      if (hex.length === 3) hex = hex.split('').map(c=>c+c).join('');
      const n = parseInt(hex, 16);
      return `${(n>>16)&255},${(n>>8)&255},${n&255}`;
    }
    function refreshColors() {
      const a = readVar('--accent', '#3D7AFF');
      const b = readVar('--accent-2', '#5EE6FF');
      if (a.startsWith('#')) accent = hexToRgb(a);
      if (b.startsWith('#')) accent2 = hexToRgb(b);
    }

    function resize() {
      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);
      const count = Math.round(Math.min(90, Math.max(36, (w * h) / 16000)));
      nodes = Array.from({ length: count }, () => ({
        x: Math.random() * w,
        y: Math.random() * h,
        vx: (Math.random() - 0.5) * 0.28,
        vy: (Math.random() - 0.5) * 0.28,
        r: Math.random() * 1.6 + 0.6,
        pulse: Math.random() * Math.PI * 2,
      }));
    }

    const mouse = { x: -9999, y: -9999 };
    function onMove(e) {
      const rect = canvas.getBoundingClientRect();
      mouse.x = e.clientX - rect.left;
      mouse.y = e.clientY - rect.top;
    }
    function onLeave() { mouse.x = -9999; mouse.y = -9999; }

    const LINK_DIST = 140;
    function draw(t) {
      ctx.clearRect(0, 0, w, h);

      for (const n of nodes) {
        n.x += n.vx; n.y += n.vy;
        if (n.x < 0 || n.x > w) n.vx *= -1;
        if (n.y < 0 || n.y > h) n.vy *= -1;
        // gentle mouse attraction
        const dxm = mouse.x - n.x, dym = mouse.y - n.y;
        const dm2 = dxm*dxm + dym*dym;
        if (dm2 < 200*200) {
          const f = (1 - Math.sqrt(dm2)/200) * 0.12;
          n.x += dxm * 0.0009 * f * 60;
          n.y += dym * 0.0009 * f * 60;
        }
      }

      // links
      for (let i = 0; i < nodes.length; i++) {
        for (let j = i + 1; j < nodes.length; j++) {
          const a = nodes[i], b = nodes[j];
          const dx = a.x - b.x, dy = a.y - b.y;
          const d = Math.sqrt(dx*dx + dy*dy);
          if (d < LINK_DIST) {
            const o = (1 - d / LINK_DIST) * 0.38;
            ctx.strokeStyle = `rgba(${accent},${o})`;
            ctx.lineWidth = 0.6;
            ctx.beginPath();
            ctx.moveTo(a.x, a.y);
            ctx.lineTo(b.x, b.y);
            ctx.stroke();
          }
        }
      }

      // nodes
      for (const n of nodes) {
        n.pulse += 0.02;
        const near = (mouse.x - n.x)**2 + (mouse.y - n.y)**2 < 160*160;
        const glow = near ? 2.0 : 1;
        const rr = n.r * (1 + 0.3 * Math.sin(n.pulse)) * glow;
        ctx.beginPath();
        ctx.arc(n.x, n.y, rr, 0, Math.PI * 2);
        ctx.fillStyle = near ? `rgba(${accent2},0.95)` : `rgba(${accent},0.7)`;
        ctx.fill();
      }

      raf = requestAnimationFrame(draw);
    }

    refreshColors();
    resize();
    if (prefersReduced) {
      // draw a single static frame
      draw(0);
      cancelAnimationFrame(raf);
    } else {
      raf = requestAnimationFrame(draw);
    }
    window.addEventListener('resize', resize);
    window.addEventListener('mousemove', onMove);
    canvas.addEventListener('mouseleave', onLeave);
    // re-read colors when tweaks change
    const colorPoll = setInterval(refreshColors, 1500);

    return () => {
      cancelAnimationFrame(raf);
      clearInterval(colorPoll);
      window.removeEventListener('resize', resize);
      window.removeEventListener('mousemove', onMove);
      canvas.removeEventListener('mouseleave', onLeave);
    };
  }, []);

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

Object.assign(window, { AIBackground });
