// Particle network — port of ParticleNetwork.astro. 40 gold nodes drifting on canvas.
function ParticleNetwork() {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let w = 0, h = 0, dpr = Math.min(window.devicePixelRatio || 1, 1.75);
    const cfg = { count: 40, dist: 160, speed: 0.3, nodeOpacity: 0.4, lineOpacity: 0.12, minR: 1, maxR: 2.5 };
    let particles = [];
    let running = true;

    const resize = () => {
      w = canvas.parentElement.clientWidth; h = canvas.parentElement.clientHeight;
      canvas.width = w * dpr; canvas.height = h * dpr;
      canvas.style.width = w + 'px'; canvas.style.height = h + 'px';
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    const create = () => {
      particles = Array.from({ length: cfg.count }, () => {
        const a = Math.random() * Math.PI * 2;
        const s = (0.2 + Math.random() * 0.8) * cfg.speed;
        return { x: Math.random() * w, y: Math.random() * h,
          vx: Math.cos(a) * s, vy: Math.sin(a) * s,
          r: cfg.minR + Math.random() * (cfg.maxR - cfg.minR) };
      });
    };
    const draw = () => {
      ctx.clearRect(0, 0, w, h);
      for (let i = 0; i < particles.length; i++) {
        for (let j = i + 1; j < particles.length; j++) {
          const dx = particles[i].x - particles[j].x, dy = particles[i].y - particles[j].y;
          const d = Math.hypot(dx, dy);
          if (d < cfg.dist) {
            ctx.globalAlpha = (1 - d / cfg.dist) * cfg.lineOpacity;
            ctx.strokeStyle = '#fdb912'; ctx.lineWidth = 0.5;
            ctx.beginPath(); ctx.moveTo(particles[i].x, particles[i].y);
            ctx.lineTo(particles[j].x, particles[j].y); ctx.stroke();
          }
        }
      }
      for (const p of particles) {
        ctx.globalAlpha = cfg.nodeOpacity; ctx.fillStyle = '#fdb912';
        ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2); ctx.fill();
      }
      ctx.globalAlpha = 1;
    };
    const update = () => {
      for (const p of particles) {
        p.x += p.vx; p.y += p.vy;
        if (p.x < -20) p.x = w + 20; if (p.x > w + 20) p.x = -20;
        if (p.y < -20) p.y = h + 20; if (p.y > h + 20) p.y = -20;
      }
    };
    const loop = () => { if (!running) return; update(); draw(); requestAnimationFrame(loop); };
    resize(); create(); loop();
    const onResize = () => { resize(); create(); };
    window.addEventListener('resize', onResize);
    return () => { running = false; window.removeEventListener('resize', onResize); };
  }, []);
  return (
    <div style={{position:'absolute',inset:0,pointerEvents:'none',zIndex:1}}>
      <canvas ref={ref} style={{width:'100%',height:'100%',display:'block'}} />
    </div>
  );
}
window.ParticleNetwork = ParticleNetwork;
