// pixel-sampler.jsx
// Rasterizes shapes (the mark, text) to a hidden canvas, then reads back
// the filled pixels as a grid of {x, y} centers. Cached by key.

const PixelSampler = (() => {
  const cache = new Map();

  // Sample a canvas-drawing callback into a grid of filled points.
  // drawFn(ctx, w, h) should paint opaque pixels on a transparent canvas.
  // cellSize: how coarse the pixelation is.
  // Returns: Array<{x, y}> with coordinates in the canvas's own pixel space.
  function sample(key, w, h, cellSize, drawFn) {
    const cacheKey = `${key}|${w}x${h}|c${cellSize}`;
    if (cache.has(cacheKey)) return cache.get(cacheKey);

    const canvas = document.createElement('canvas');
    canvas.width = w;
    canvas.height = h;
    const ctx = canvas.getContext('2d', { willReadFrequently: true });
    drawFn(ctx, w, h);

    const img = ctx.getImageData(0, 0, w, h).data;
    const pts = [];
    for (let gy = 0; gy < Math.floor(h / cellSize); gy++) {
      for (let gx = 0; gx < Math.floor(w / cellSize); gx++) {
        // Sample center of cell
        const cx = Math.floor(gx * cellSize + cellSize / 2);
        const cy = Math.floor(gy * cellSize + cellSize / 2);
        const idx = (cy * w + cx) * 4 + 3; // alpha
        if (img[idx] > 128) {
          pts.push({
            x: gx * cellSize,
            y: gy * cellSize,
            cx: cx,
            cy: cy,
          });
        }
      }
    }
    cache.set(cacheKey, pts);
    return pts;
  }

  // Draw the Foundry NX mark (triangle + bar) into the given rectangle.
  // Pure function of the rect so it can be cached.
  function drawMark(ctx, w, h) {
    // Mirror the viewBox of logo-mark.svg (0 0 200 200) inside w×h.
    // Triangle: M100 20 L182 160 L18 160, Rect: 18,172 164×12
    const s = Math.min(w, h) / 200;
    const ox = (w - 200 * s) / 2;
    const oy = (h - 200 * s) / 2;
    const px = (x) => ox + x * s;
    const py = (y) => oy + y * s;

    ctx.fillStyle = '#F5A537';
    ctx.beginPath();
    ctx.moveTo(px(100), py(20));
    ctx.lineTo(px(182), py(160));
    ctx.lineTo(px(18), py(160));
    ctx.closePath();
    ctx.fill();

    ctx.fillRect(px(18), py(172), 164 * s, 12 * s);
  }

  function drawText(ctx, w, h, text, fontSpec) {
    ctx.fillStyle = '#ffffff';
    ctx.font = fontSpec;
    ctx.textBaseline = 'middle';
    ctx.textAlign = 'center';
    ctx.fillText(text, w / 2, h / 2);
  }

  return { sample, drawMark, drawText };
})();

window.PixelSampler = PixelSampler;
