/* global React */
const { useEffect, useRef } = React;

function Starfield() {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    let w, h, stars, dpr;
    let raf;

    function resize() {
      dpr = window.devicePixelRatio || 1;
      w = window.innerWidth;
      h = window.innerHeight;
      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);
      // 3 layers for parallax + size variation
      stars = [];
      const density = (w * h) / 8000;
      for (let i = 0; i < density; i++) {
        const layer = Math.random();
        stars.push({
          x: Math.random() * w,
          y: Math.random() * h,
          r: layer < 0.7 ? Math.random() * 0.7 + 0.2 : Math.random() * 1.5 + 0.5,
          tw: Math.random() * Math.PI * 2,
          twSpeed: 0.3 + Math.random() * 0.8,
          baseA: 0.25 + Math.random() * 0.65
        });
      }
    }

    let t0 = performance.now();
    function tick(t) {
      const elapsed = (t - t0) / 1000;
      ctx.clearRect(0, 0, w, h);
      for (const s of stars) {
        const a = s.baseA * (0.6 + 0.4 * Math.sin(s.tw + elapsed * s.twSpeed));
        ctx.globalAlpha = a;
        ctx.fillStyle = s.r > 1 ? '#cfd8ff' : '#e8ecff';
        ctx.beginPath();
        ctx.arc(s.x, s.y, s.r, 0, Math.PI * 2);
        ctx.fill();
        if (s.r > 1) {
          ctx.globalAlpha = a * 0.3;
          ctx.beginPath();
          ctx.arc(s.x, s.y, s.r * 2.4, 0, Math.PI * 2);
          ctx.fill();
        }
      }
      ctx.globalAlpha = 1;
      raf = requestAnimationFrame(tick);
    }

    resize();
    window.addEventListener('resize', resize);
    raf = requestAnimationFrame(tick);
    return () => {
      window.removeEventListener('resize', resize);
      cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <canvas
      ref={canvasRef}
      style={{
        position: 'fixed',
        inset: 0,
        pointerEvents: 'none',
        zIndex: 0
      }}
    />
  );
}

window.Starfield = Starfield;
