// Cinematic ambient background: animated grid, floating glyphs, scanning beams
function AmbientBackground({ trend = 0 }) {
  const canvasRef = React.useRef(null);
  const trendRef = React.useRef(trend);
  React.useEffect(() => { trendRef.current = trend; }, [trend]);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    let raf;
    let w = 0, h = 0;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);

    const resize = () => {
      w = canvas.clientWidth;
      h = canvas.clientHeight;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    window.addEventListener("resize", resize);

    // Particles: floating currency glyphs
    const glyphs = ["$","€","£","¥","₩","₹","₣","฿","₺","₪","₱","R$","kr","A$","S$"];
    const particles = Array.from({ length: 28 }, () => ({
      x: Math.random() * 1600,
      y: Math.random() * 900,
      vy: 0.08 + Math.random() * 0.18,
      vx: (Math.random() - 0.5) * 0.05,
      size: 14 + Math.random() * 28,
      glyph: glyphs[Math.floor(Math.random() * glyphs.length)],
      opacity: 0.04 + Math.random() * 0.08,
      rot: Math.random() * Math.PI,
      vrot: (Math.random() - 0.5) * 0.002,
    }));

    // Data points (constellation)
    const dots = Array.from({ length: 60 }, () => ({
      x: Math.random(),
      y: Math.random(),
      phase: Math.random() * Math.PI * 2,
      speed: 0.4 + Math.random() * 0.8,
    }));

    let t0 = performance.now();

    const draw = () => {
      const now = performance.now();
      const t = (now - t0) / 1000;

      ctx.clearRect(0, 0, w, h);

      // Radial vignette glow (cyan/warm/cool based on trend)
      const cx = w * 0.5, cy = h * 0.55;
      const tr = trendRef.current || 0;
      const warm = Math.max(0, Math.min(1, tr * 50));   // up = warm amber
      const cool = Math.max(0, Math.min(1, -tr * 50));  // down = cool red
      const r = Math.round(60 + warm * 180 - cool * 30);
      const g = Math.round(220 - warm * 40 - cool * 100);
      const b = Math.round(200 - warm * 80 - cool * 40);
      const grad = ctx.createRadialGradient(cx, cy, 0, cx, cy, Math.max(w, h) * 0.7);
      grad.addColorStop(0, `rgba(${r}, ${g}, ${b}, 0.07)`);
      grad.addColorStop(0.5, "rgba(20, 60, 80, 0.02)");
      grad.addColorStop(1, "rgba(0, 0, 0, 0)");
      ctx.fillStyle = grad;
      ctx.fillRect(0, 0, w, h);

      // Subtle grid
      ctx.strokeStyle = "rgba(120, 200, 200, 0.04)";
      ctx.lineWidth = 1;
      const gridSize = 60;
      const off = (t * 8) % gridSize;
      for (let x = -off; x < w; x += gridSize) {
        ctx.beginPath();
        ctx.moveTo(x, 0); ctx.lineTo(x, h);
        ctx.stroke();
      }
      for (let y = -off; y < h; y += gridSize) {
        ctx.beginPath();
        ctx.moveTo(0, y); ctx.lineTo(w, y);
        ctx.stroke();
      }

      // Scanning beam (horizontal sweep)
      const beamY = ((t * 60) % (h + 200)) - 100;
      const beamGrad = ctx.createLinearGradient(0, beamY - 80, 0, beamY + 80);
      beamGrad.addColorStop(0, "rgba(60, 220, 200, 0)");
      beamGrad.addColorStop(0.5, "rgba(60, 220, 200, 0.06)");
      beamGrad.addColorStop(1, "rgba(60, 220, 200, 0)");
      ctx.fillStyle = beamGrad;
      ctx.fillRect(0, beamY - 80, w, 160);

      // Constellation dots (pulsing)
      ctx.fillStyle = "rgba(120, 220, 210, 1)";
      dots.forEach(d => {
        const pulse = 0.3 + 0.7 * (0.5 + 0.5 * Math.sin(t * d.speed + d.phase));
        ctx.globalAlpha = pulse * 0.35;
        ctx.beginPath();
        ctx.arc(d.x * w, d.y * h, 1.2, 0, Math.PI * 2);
        ctx.fill();
      });
      ctx.globalAlpha = 1;

      // Floating glyphs
      ctx.font = "300 28px 'JetBrains Mono', monospace";
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      particles.forEach(p => {
        p.y -= p.vy;
        p.x += p.vx;
        p.rot += p.vrot;
        if (p.y < -40) { p.y = h + 40; p.x = Math.random() * w; }
        if (p.x < -40) p.x = w + 40;
        if (p.x > w + 40) p.x = -40;

        ctx.save();
        ctx.translate(p.x, p.y);
        ctx.rotate(p.rot);
        ctx.font = `300 ${p.size}px 'JetBrains Mono', monospace`;
        ctx.fillStyle = `rgba(140, 230, 220, ${p.opacity})`;
        ctx.fillText(p.glyph, 0, 0);
        ctx.restore();
      });

      raf = requestAnimationFrame(draw);
    };
    draw();

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", resize);
    };
  }, []);

  return (
    <div className="bg-layer">
      <canvas ref={canvasRef} className="bg-canvas"></canvas>
      <div className="bg-noise"></div>
    </div>
  );
}

window.AmbientBackground = AmbientBackground;
