// BeamsBackground.jsx — cinematic light beams for hero & final CTA
// Inspired by /components/ui/beams-background.tsx (shadcn-style component).
// Renders a canvas of soft moving beams + fog + grain overlay.

function BeamsBackground({
  intensity = "medium",        // "subtle" | "medium" | "dramatic"
  beamCount = 18,
  tint = "neutral",            // "neutral" | "red" | "blue" | "mixed"
  showGrain = true,
  showParticles = false,
  particleCount = 24,
  className = "",
  style = {},
}) {
  const canvasRef = React.useRef(null);
  const rafRef = React.useRef(null);

  const intensityMap = { subtle: 0.45, medium: 0.85, dramatic: 1.25 };
  const energy = intensityMap[intensity] ?? 0.85;

  // Palette per tint — soft cinematic light. Mostly white/steel with brand tints.
  const palettes = {
    neutral: [
      [255, 255, 255],
      [210, 220, 235],
      [180, 195, 220],
    ],
    blue: [
      [255, 255, 255],
      [120, 170, 230],
      [79, 134, 198],
    ],
    red: [
      [255, 235, 230],
      [255, 130, 110],
      [237, 48, 36],
    ],
    mixed: [
      [255, 255, 255],
      [79, 134, 198],
      [237, 48, 36],
      [220, 220, 230],
    ],
  };

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

    const palette = palettes[tint] || palettes.neutral;

    function resize() {
      const parent = canvas.parentElement;
      const rect = parent.getBoundingClientRect();
      w = rect.width;
      h = rect.height;
      canvas.width = Math.floor(w * dpr);
      canvas.height = Math.floor(h * dpr);
      canvas.style.width = w + "px";
      canvas.style.height = h + "px";
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    }

    function makeBeam(i) {
      const color = palette[Math.floor(Math.random() * palette.length)];
      return {
        // anchor at the top
        x: Math.random() * w,
        // angle relative to vertical, in radians
        angle: (Math.random() - 0.5) * 0.7 + 0.05,
        // length spans well past the canvas
        length: h * (1.1 + Math.random() * 0.5),
        // beam width
        width: 60 + Math.random() * 240,
        // brightness
        alpha: (0.05 + Math.random() * 0.12) * energy,
        // drift speed in px/sec
        drift: (Math.random() - 0.5) * 18,
        // pulse parameters
        pulseSpeed: 0.4 + Math.random() * 1.4,
        pulsePhase: Math.random() * Math.PI * 2,
        color,
        // depth controls width scaling and brightness modulation
        depth: 0.5 + Math.random() * 0.5,
      };
    }

    function reset() {
      beams = new Array(beamCount).fill(0).map((_, i) => makeBeam(i));
    }

    let last = performance.now();
    function frame(now) {
      const dt = Math.min(0.05, (now - last) / 1000);
      last = now;

      // soft fade composite — slight trail
      ctx.globalCompositeOperation = "source-over";
      ctx.fillStyle = "rgba(0,0,0,0.18)";
      ctx.fillRect(0, 0, w, h);

      ctx.globalCompositeOperation = "lighter";

      const t = now / 1000;
      for (const b of beams) {
        b.x += b.drift * dt;
        if (b.x < -200) b.x = w + 200;
        if (b.x > w + 200) b.x = -200;

        const pulse = 0.6 + 0.4 * Math.sin(t * b.pulseSpeed + b.pulsePhase);
        const a = b.alpha * pulse;
        const wPx = b.width * b.depth;

        // Draw beam as a soft long gradient
        ctx.save();
        ctx.translate(b.x, -40);
        ctx.rotate(b.angle);
        const grad = ctx.createLinearGradient(0, 0, 0, b.length);
        const [r, g, bl] = b.color;
        grad.addColorStop(0.0, `rgba(${r},${g},${bl},${a * 0.9})`);
        grad.addColorStop(0.35, `rgba(${r},${g},${bl},${a * 0.5})`);
        grad.addColorStop(1.0, `rgba(${r},${g},${bl},0)`);
        ctx.fillStyle = grad;

        // soft, blurred-ish look via repeated drawing with varying width
        ctx.shadowColor = `rgba(${r},${g},${bl},${a * 0.4})`;
        ctx.shadowBlur = 60;
        ctx.beginPath();
        ctx.moveTo(-wPx / 2, 0);
        ctx.quadraticCurveTo(0, b.length * 0.3, -wPx / 8, b.length);
        ctx.lineTo(wPx / 8, b.length);
        ctx.quadraticCurveTo(0, b.length * 0.3, wPx / 2, 0);
        ctx.closePath();
        ctx.fill();
        ctx.restore();
      }

      rafRef.current = requestAnimationFrame(frame);
    }

    const ro = new ResizeObserver(() => { resize(); reset(); });
    ro.observe(canvas.parentElement);
    resize();
    reset();
    rafRef.current = requestAnimationFrame(frame);

    return () => {
      cancelAnimationFrame(rafRef.current);
      ro.disconnect();
    };
  }, [intensity, tint, beamCount]);

  // Floating particles (CSS-driven)
  const particles = showParticles
    ? new Array(particleCount).fill(0).map((_, i) => {
        const left = Math.random() * 100;
        const dur = 14 + Math.random() * 16;
        const delay = -Math.random() * dur;
        const size = 1 + Math.random() * 2;
        return (
          <span
            key={i}
            style={{
              left: `${left}%`,
              bottom: `-${10 + Math.random() * 20}px`,
              width: `${size}px`,
              height: `${size}px`,
              animationDuration: `${dur}s`,
              animationDelay: `${delay}s`,
              opacity: 0.5 + Math.random() * 0.4,
            }}
          />
        );
      })
    : null;

  return (
    <div className={`beams-stage ${className}`} style={style} aria-hidden="true">
      <canvas ref={canvasRef} className="beams-canvas" />
      <div className="beams-fog" />
      {showGrain && <div className="beams-grain" />}
      <div className="beams-vignette" />
      {showParticles && <div className="particles">{particles}</div>}
    </div>
  );
}

window.BeamsBackground = BeamsBackground;
