// ak-dotted-surface.jsx — 3D dotted wave plane in Canvas 2D, AK palette on white
// Recreates the "Dotted Surface" effect (sshahaider/21st.dev) without Three.js.
// Dark gray dots with subtle AK red accents, soft red glow underneath.

const AKDS_COLORS = {
  bg:        '#FFFFFF',
  dotDark:   '58, 58, 58',     // AK.gray1 — primary dot color
  dotMid:    '107, 107, 107',  // AK.gray2 — far dots
  red:       '230, 35, 33',    // AK.red — accent dots
  redDeep:   '184, 27, 25',
};

function AKDottedSurface({
  width = 1200,
  height = 720,
  cols = 60,
  rows = 60,
  spacing = 22,
  amplitude = 28,
  speed = 0.7,
  accentEvery = 18,        // every Nth dot in red
  cameraTilt = 0.55,       // radians, looking down toward the plane
  perspective = 700,
}) {
  const canvasRef = React.useRef(null);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    canvas.width  = width  * dpr;
    canvas.height = height * dpr;
    canvas.style.width  = width  + 'px';
    canvas.style.height = height + 'px';
    const ctx = canvas.getContext('2d');
    ctx.scale(dpr, dpr);

    // Pre-compute grid in world space, centered at origin on XZ plane
    const grid = [];
    const halfC = (cols - 1) / 2;
    const halfR = (rows - 1) / 2;
    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) {
        const x = (c - halfC) * spacing;
        const z = (r - halfR) * spacing;
        const accent = (((c * 73856093) ^ (r * 19349663)) % accentEvery) === 0;
        grid.push({ x, z, accent });
      }
    }

    // Camera params
    const ct = Math.cos(cameraTilt), st = Math.sin(cameraTilt);
    const cx = width / 2;
    const cy = height / 2 + 60;        // shift focal a bit lower
    const cameraZOffset = 380;          // pull camera back

    let raf, t0 = performance.now();
    function frame(now) {
      const t = (now - t0) / 1000 * speed;
      ctx.clearRect(0, 0, width, height);

      // Soft red wash beneath the plane for warmth
      const wash = ctx.createRadialGradient(cx, cy + 80, 40, cx, cy + 80, height * 0.7);
      wash.addColorStop(0, `rgba(${AKDS_COLORS.red}, 0.05)`);
      wash.addColorStop(1, `rgba(${AKDS_COLORS.red}, 0)`);
      ctx.fillStyle = wash;
      ctx.fillRect(0, 0, width, height);

      // Project + sort by depth, then draw back-to-front for proper layering
      const projected = [];
      for (let i = 0; i < grid.length; i++) {
        const g = grid[i];
        // Wave height — two crossing sine waves
        const y = Math.sin(g.x * 0.022 + t * 1.3) * amplitude
                + Math.sin(g.z * 0.027 - t * 0.9) * amplitude * 0.85
                + Math.sin((g.x + g.z) * 0.014 + t * 0.6) * amplitude * 0.4;

        // Camera transform: rotate around X by cameraTilt
        // (x stays, y' = y*cos - z*sin, z' = y*sin + z*cos)
        const yC = y * ct - g.z * st;
        const zC = y * st + g.z * ct + cameraZOffset;

        if (zC <= 1) continue;
        const scale = perspective / zC;
        const px = cx + g.x * scale;
        const py = cy - yC * scale;

        // Depth → opacity & dot size
        const depth = 1 - Math.min(1, (zC - 100) / 1400);
        const radius = 0.6 + 1.7 * depth;
        const alpha  = 0.18 + 0.72 * depth;

        projected.push({ px, py, radius, alpha, accent: g.accent, zC, y });
      }

      // Sort: deeper first
      projected.sort((a, b) => b.zC - a.zC);

      for (let i = 0; i < projected.length; i++) {
        const p = projected[i];
        const colorRgb = p.accent ? AKDS_COLORS.red : AKDS_COLORS.dotDark;
        // Slightly emphasize peaks (positive y) with stronger alpha
        const peakBoost = Math.max(0, p.y) * 0.004;
        const a = Math.min(1, p.alpha + peakBoost);
        ctx.fillStyle = `rgba(${colorRgb}, ${a})`;
        ctx.beginPath();
        ctx.arc(p.px, p.py, p.radius, 0, Math.PI * 2);
        ctx.fill();
      }

      raf = requestAnimationFrame(frame);
    }
    raf = requestAnimationFrame(frame);
    return () => cancelAnimationFrame(raf);
  }, [width, height, cols, rows, spacing, amplitude, speed, accentEvery, cameraTilt, perspective]);

  return (
    <canvas ref={canvasRef} style={{
      display: 'block',
      background: 'transparent',
      pointerEvents: 'none',
    }}/>
  );
}

window.AKDottedSurface = AKDottedSurface;
