// SpiralCanvas.jsx — the AUFN PUNKT background anchor: a slowly turning,
// gently breathing neon spiral drawn on a canvas. Capped, pauses when the
// tab is hidden, honors prefers-reduced-motion. z-index:-1, pointer-events:none.
function SpiralCanvas({ opacity = 0.55 }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const canvas = ref.current;
    const ctx = canvas.getContext('2d');
    let raf, t = 0, running = true;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    function resize() {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      canvas.width = canvas.offsetWidth * dpr;
      canvas.height = canvas.offsetHeight * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    }
    resize();
    window.addEventListener('resize', resize);

    function draw() {
      const w = canvas.offsetWidth, h = canvas.offsetHeight;
      const cx = w / 2, cy = h * 0.46;
      ctx.clearRect(0, 0, w, h);
      const breathe = reduce ? 1 : 1 + Math.sin(t * 0.012) * 0.04;
      const rot = reduce ? 0 : t * 0.0016;
      const turns = 4.2, steps = 520;
      const maxR = Math.min(w, h) * 0.5 * breathe;
      const b = maxR / (turns * Math.PI * 2);

      // two offset strokes — cyan + magenta — for the neon double-line look
      const passes = [
        { col: 'rgba(0,255,255,0.85)', off: 0, lw: 2.4, blur: 18 },
        { col: 'rgba(255,0,170,0.55)', off: 0.5, lw: 1.6, blur: 14 },
      ];
      passes.forEach(p => {
        ctx.beginPath();
        for (let i = 0; i <= steps; i++) {
          const a = (i / steps) * turns * Math.PI * 2;
          const r = b * a;
          const x = cx + r * Math.cos(a + rot + p.off);
          const y = cy + r * Math.sin(a + rot + p.off);
          i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
        }
        ctx.strokeStyle = p.col;
        ctx.lineWidth = p.lw;
        ctx.shadowColor = p.col;
        ctx.shadowBlur = p.blur;
        ctx.stroke();
      });
      ctx.shadowBlur = 0;
      if (!reduce) t += 1;
    }

    function loop() { if (running) { draw(); raf = requestAnimationFrame(loop); } }
    loop();
    if (reduce) { cancelAnimationFrame(raf); draw(); }

    const onVis = () => {
      running = !document.hidden;
      if (running && !reduce) loop(); else cancelAnimationFrame(raf);
    };
    document.addEventListener('visibilitychange', onVis);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', resize);
      document.removeEventListener('visibilitychange', onVis);
    };
  }, []);
  return <canvas ref={ref} className="spiral-canvas" style={{ opacity }} aria-hidden="true" />;
}
window.SpiralCanvas = SpiralCanvas;
