// Heatmap canvas overlay for the Chernarus map.
// Renders density samples as a blurred alpha mask, then colorizes
// with a low→high gradient (cool blue → orange → red).

function MapHeatmap({ points, intensity = 0.7, blur = 28 }) {
  const ref = React.useRef(null);

  React.useEffect(() => {
    const cvs = ref.current;
    if (!cvs) return;
    const parent = cvs.parentElement;
    if (!parent) return;

    const draw = () => {
      const rect = parent.getBoundingClientRect();
      const dpr = window.devicePixelRatio || 1;
      const W = Math.max(1, Math.floor(rect.width));
      const H = Math.max(1, Math.floor(rect.height));
      cvs.width  = W * dpr;
      cvs.height = H * dpr;
      cvs.style.width  = W + "px";
      cvs.style.height = H + "px";

      const ctx = cvs.getContext("2d");
      ctx.clearRect(0, 0, cvs.width, cvs.height);
      ctx.scale(dpr, dpr);

      // 1) Draw alpha-only blobs.
      ctx.globalCompositeOperation = "source-over";
      const baseR = Math.max(W, H) * 0.06;
      for (const p of points) {
        const x = p.x * W, y = p.y * H;
        const r = baseR * (0.6 + (p.weight || 1) * 0.6);
        const g = ctx.createRadialGradient(x, y, 0, x, y, r);
        const a = Math.min(1, 0.18 * intensity * (p.weight || 1));
        g.addColorStop(0,   `rgba(0,0,0,${a})`);
        g.addColorStop(1,   "rgba(0,0,0,0)");
        ctx.fillStyle = g;
        ctx.beginPath();
        ctx.arc(x, y, r, 0, Math.PI * 2);
        ctx.fill();
      }

      // 2) Colorize alpha mask using source-in.
      ctx.globalCompositeOperation = "source-in";
      // Sample alpha vertically too — we want a gradient driven by density,
      // not position. Simulate by stacking many thin horizontal bands of
      // identical color but that's ineffective. Instead use a vertical
      // multistop gradient: looks decent because dense clusters bloom
      // through multiple bands.
      const grad = ctx.createLinearGradient(0, 0, W, 0);
      grad.addColorStop(0.0, "#2a6fdb");   // cold blue (low traffic)
      grad.addColorStop(0.35, "#7eb4d4");
      grad.addColorStop(0.6, "#e6c454");   // amber
      grad.addColorStop(0.85, "#d94a2b");  // hot red
      grad.addColorStop(1.0, "#ff4422");
      ctx.fillStyle = grad;
      ctx.fillRect(0, 0, W, H);

      // Reset for next paint.
      ctx.globalCompositeOperation = "source-over";
    };

    draw();
    const ro = new ResizeObserver(draw);
    ro.observe(parent);
    return () => ro.disconnect();
  }, [points, intensity, blur]);

  return (
    <canvas
      ref={ref}
      className="map-heatmap"
      style={{
        position: "absolute", inset: 0, pointerEvents: "none",
        filter: `blur(${blur}px) saturate(1.2)`,
        mixBlendMode: "screen",
        opacity: 0.95,
      }}
    />
  );
}

window.MapHeatmap = MapHeatmap;
