// Canvas starfield with constellations, drifting fog, and (in esoteric) a
// faint zodiac arc. Pure decoration — runs at low fps and pauses if hidden.

function Starfield({ variant = 'night', mode = 'dark' }) {
  const canvasRef = React.useRef();
  React.useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    let raf;
    let w, h;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);

    const stars = [];
    const constellations = [];

    function resize() {
      w = canvas.clientWidth;
      h = canvas.clientHeight;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      ctx.scale(dpr, dpr);
      seed();
    }
    function seed() {
      stars.length = 0;
      constellations.length = 0;
      const count = Math.floor((w * h) / 2400);
      for (let i = 0; i < count; i++) {
        stars.push({
          x: Math.random() * w,
          y: Math.random() * h,
          r: Math.random() ** 3 * 1.6 + 0.2,
          tw: Math.random() * Math.PI * 2,
          tws: 0.4 + Math.random() * 1.4,
          big: Math.random() < 0.012,
        });
      }
      // 4 constellations
      for (let k = 0; k < 4; k++) {
        const cx = Math.random() * w;
        const cy = Math.random() * h;
        const pts = [];
        const n = 4 + Math.floor(Math.random() * 3);
        let ax = cx, ay = cy;
        for (let i = 0; i < n; i++) {
          ax += (Math.random() - 0.5) * 80;
          ay += (Math.random() - 0.5) * 80;
          pts.push({ x: ax, y: ay });
        }
        constellations.push(pts);
      }
    }

    function read(varName) {
      return getComputedStyle(document.documentElement)
        .getPropertyValue(varName).trim() || '#fff';
    }

    function draw(time) {
      const starA = read('--t-starA');
      const starB = read('--t-starB');
      const line  = read('--t-line');
      ctx.clearRect(0, 0, w, h);

      // constellation lines
      ctx.strokeStyle = line;
      ctx.lineWidth = 0.6;
      for (const pts of constellations) {
        ctx.beginPath();
        for (let i = 0; i < pts.length; i++) {
          if (i === 0) ctx.moveTo(pts[i].x, pts[i].y);
          else ctx.lineTo(pts[i].x, pts[i].y);
        }
        ctx.stroke();
        // node markers
        for (const p of pts) {
          ctx.beginPath();
          ctx.fillStyle = starB;
          ctx.arc(p.x, p.y, 1.4, 0, Math.PI * 2);
          ctx.fill();
        }
      }

      // stars
      for (const s of stars) {
        const tw = 0.4 + 0.6 * (0.5 + 0.5 * Math.sin(time * 0.001 * s.tws + s.tw));
        ctx.beginPath();
        ctx.fillStyle = s.big ? starB : starA;
        ctx.globalAlpha = (s.big ? 0.9 : 0.55) * tw;
        ctx.arc(s.x, s.y, s.r, 0, Math.PI * 2);
        ctx.fill();
        if (s.big) {
          ctx.globalAlpha = 0.18 * tw;
          ctx.beginPath();
          ctx.arc(s.x, s.y, s.r * 5, 0, Math.PI * 2);
          ctx.fill();
        }
      }
      ctx.globalAlpha = 1;
      raf = requestAnimationFrame(draw);
    }

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

  return <canvas ref={canvasRef} style={{
    position: 'absolute', inset: 0, width: '100%', height: '100%',
    pointerEvents: 'none', zIndex: 1,
  }} />;
}

// Slow-drifting blurred fog blobs (used in dreamlike + as background ambiance)
function FogBlobs({ t, count = 4 }) {
  const blobs = React.useMemo(
    () => Array.from({ length: count }).map((_, i) => ({
      x: Math.random() * 100, y: Math.random() * 100,
      size: 35 + Math.random() * 45,
      hue: i % 2 === 0 ? t.accent : t.accent2,
      delay: Math.random() * -40,
    })),
    [count, t.accent, t.accent2]
  );
  return (
    <div style={{
      position: 'absolute', inset: 0, overflow: 'hidden',
      pointerEvents: 'none', zIndex: 0,
    }}>
      {blobs.map((b, i) => (
        <div key={i} style={{
          position: 'absolute',
          left: `${b.x}%`, top: `${b.y}%`,
          width: `${b.size}vw`, height: `${b.size}vw`,
          borderRadius: '50%',
          background: `radial-gradient(circle, ${b.hue}55 0%, ${b.hue}00 65%)`,
          filter: 'blur(60px)',
          animation: `oneiro-fog 60s ease-in-out infinite`,
          animationDelay: `${b.delay}s`,
        }} />
      ))}
    </div>
  );
}

window.Starfield = Starfield;
window.FogBlobs = FogBlobs;
