// stars-bg.jsx — ambient star field with back + front layers + mouse parallax
const { useEffect: _seffect, useRef: _sref } = React;

function StarsBackground() {
  const backRef = _sref(null);
  const frontRef = _sref(null);

  _seffect(() => {
    const backCanvas = backRef.current;
    const frontCanvas = frontRef.current;
    if (!backCanvas || !frontCanvas) return;
    const backCtx = backCanvas.getContext('2d');
    const frontCtx = frontCanvas.getContext('2d');

    let w = window.innerWidth, h = window.innerHeight;
    let dpr = Math.min(window.devicePixelRatio || 1, 2);
    const sizeCanvas = (cv, cx) => {
      cv.width = w * dpr;
      cv.height = h * dpr;
      cv.style.width = w + 'px';
      cv.style.height = h + 'px';
      cx.setTransform(1, 0, 0, 1, 0, 0);
      cx.scale(dpr, dpr);
    };
    sizeCanvas(backCanvas, backCtx);
    sizeCanvas(frontCanvas, frontCtx);

    // 80% of stars in BACK layer, 20% in FOREGROUND (closer = brighter, larger, faster mouse parallax)
    const TOTAL = Math.min(4500, Math.floor((w * h) / 350));
    const BACK_COUNT = Math.floor(TOTAL * 0.82);
    const FRONT_COUNT = TOTAL - BACK_COUNT;

    const stars = [];
    const docHeight = () => Math.max(document.body.scrollHeight, h * 4);
    let dh = docHeight();

    // Back stars — same as before
    for (let i = 0; i < BACK_COUNT; i++) {
      stars.push({
        layer: 'back',
        x: Math.random() * w,
        y: Math.random() * dh,
        r: Math.random() * 1.0 + 0.3,
        depth: 0.2 + Math.random() * 0.9,
        twinklePhase: Math.random() * Math.PI * 2,
        twinkleSpeed: 0.5 + Math.random() * 1.5,
        baseAlpha: 0.35 + Math.random() * 0.5,
        // mouse parallax factor — small for back stars
        mouseFactor: 0.02 + Math.random() * 0.05
      });
    }
    // Foreground stars — bigger, brighter, more mouse-reactive, less twinkle
    for (let i = 0; i < FRONT_COUNT; i++) {
      stars.push({
        layer: 'front',
        x: Math.random() * w,
        y: Math.random() * dh,
        r: Math.random() * 1.8 + 0.8,
        depth: 0.6 + Math.random() * 0.6,
        twinklePhase: Math.random() * Math.PI * 2,
        twinkleSpeed: 0.4 + Math.random() * 1.2,
        baseAlpha: 0.55 + Math.random() * 0.4,
        // mouse parallax factor — strong for foreground stars
        mouseFactor: 0.15 + Math.random() * 0.2
      });
    }

    const getAccentRGB = () => {
      try {
        const c = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim();
        const cv = document.createElement('canvas'); cv.width = cv.height = 1;
        const cx = cv.getContext('2d');
        cx.fillStyle = '#000'; cx.fillStyle = c;
        cx.fillRect(0, 0, 1, 1);
        const [r, g, b] = cx.getImageData(0, 0, 1, 1).data;
        return [r, g, b];
      } catch (e) {}
      return [245, 245, 245];
    };
    let accent = getAccentRGB();
    // re-read quickly at first to catch the late --accent application
    setTimeout(() => { accent = getAccentRGB(); }, 50);
    setTimeout(() => { accent = getAccentRGB(); }, 300);
    const accentInt = setInterval(() => { accent = getAccentRGB(); }, 800);

    // Mouse-driven parallax — same approach as the hero sphere
    let targetMx = 0, targetMy = 0;
    let mx = 0, my = 0;
    const onMove = (e) => {
      // -1 .. 1 normalized
      targetMx = (e.clientX / window.innerWidth) * 2 - 1;
      targetMy = (e.clientY / window.innerHeight) * 2 - 1;
    };
    window.addEventListener('mousemove', onMove);

    const onResize = () => {
      w = window.innerWidth; h = window.innerHeight;
      dpr = Math.min(window.devicePixelRatio || 1, 2);
      sizeCanvas(backCanvas, backCtx);
      sizeCanvas(frontCanvas, frontCtx);
      dh = docHeight();
      stars.forEach(s => {
        if (s.x > w) s.x = Math.random() * w;
        if (s.y > dh) s.y = Math.random() * dh;
      });
    };
    window.addEventListener('resize', onResize);

    let raf, t = 0;
    const animate = () => {
      t += 0.016;
      // smooth mouse
      mx += (targetMx - mx) * 0.06;
      my += (targetMy - my) * 0.06;

      const scrollY = window.scrollY;
      backCtx.clearRect(0, 0, w, h);
      frontCtx.clearRect(0, 0, w, h);

      for (let i = 0; i < stars.length; i++) {
        const s = stars[i];
        const drawY = s.y - scrollY * s.depth;
        const wrapY = ((drawY % dh) + dh) % dh;
        const onScreenY = wrapY > h ? wrapY - dh : wrapY;
        if (onScreenY < -20 || onScreenY > h + 20) continue;

        // mouse parallax offset (proportional to mouseFactor)
        const offsetX = -mx * 80 * s.mouseFactor;
        const offsetY = -my * 60 * s.mouseFactor;
        const finalX = s.x + offsetX;
        const finalY = onScreenY + offsetY;

        const twinkle = (Math.sin(t * s.twinkleSpeed + s.twinklePhase) + 1) * 0.5;
        const alpha = s.baseAlpha * (0.4 + twinkle * 0.6);
        const r = accent[0], g = accent[1], b = accent[2];

        const ctx = s.layer === 'front' ? frontCtx : backCtx;

        ctx.beginPath();
        ctx.arc(finalX, finalY, s.r, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(${r},${g},${b},${alpha})`;
        ctx.fill();

        // glow on big stars (foreground gets it more often)
        const glowChance = s.layer === 'front' ? 0.55 : 0.7;
        if (s.r > 0.8 && twinkle > glowChance) {
          ctx.beginPath();
          ctx.arc(finalX, finalY, s.r * 3.2, 0, Math.PI * 2);
          ctx.fillStyle = `rgba(${r},${g},${b},${alpha * 0.18})`;
          ctx.fill();
        }
      }

      // Punch holes in the front layer where portfolio cards are visible,
      // so foreground stars never sit on top of website mockups.
      const punchEls = document.querySelectorAll('.portfolio-card');
      if (punchEls.length) {
        frontCtx.save();
        frontCtx.globalCompositeOperation = 'destination-out';
        frontCtx.fillStyle = 'rgba(0,0,0,1)';
        punchEls.forEach(el => {
          const r = el.getBoundingClientRect();
          if (r.bottom < -50 || r.top > h + 50 || r.right < -50 || r.left > w + 50) return;
          const pad = 12, radius = 16;
          const x = r.left - pad, y = r.top - pad, ww = r.width + pad*2, hh = r.height + pad*2;
          frontCtx.beginPath();
          frontCtx.moveTo(x + radius, y);
          frontCtx.arcTo(x + ww, y, x + ww, y + hh, radius);
          frontCtx.arcTo(x + ww, y + hh, x, y + hh, radius);
          frontCtx.arcTo(x, y + hh, x, y, radius);
          frontCtx.arcTo(x, y, x + ww, y, radius);
          frontCtx.closePath();
          frontCtx.fill();
        });
        frontCtx.restore();
      }

      raf = requestAnimationFrame(animate);
    };
    animate();

    const dhInt = setInterval(() => { dh = docHeight(); }, 2000);

    return () => {
      cancelAnimationFrame(raf);
      clearInterval(accentInt);
      clearInterval(dhInt);
      window.removeEventListener('resize', onResize);
      window.removeEventListener('mousemove', onMove);
    };
  }, []);

  return (
    <>
      {/* Back layer — behind everything */}
      <canvas
        ref={backRef}
        style={{
          position: 'fixed',
          inset: 0,
          width: '100%',
          height: '100%',
          pointerEvents: 'none',
          zIndex: 0,
          background: 'var(--bg)'
        }}
      />
      {/* Foreground layer — above content, like the sphere particles popping out */}
      <canvas
        ref={frontRef}
        style={{
          position: 'fixed',
          inset: 0,
          width: '100%',
          height: '100%',
          pointerEvents: 'none',
          zIndex: 60,
          background: 'transparent'
        }}
      />
    </>
  );
}

window.StarsBackground = StarsBackground;
