// Grid.jsx — renders the isometric ground plane grid.
// Rhombus cells at world z=0, from (0,0) to (GRID_W, GRID_H).

const GRID_W = 12;
const GRID_H = 12;

function IsoGrid({ hoverCell }) {
  const lines = [];

  // Lines along +x (for each y) and along +y (for each x).
  for (let y = 0; y <= GRID_H; y++) {
    const a = iso(0, y, 0);
    const b = iso(GRID_W, y, 0);
    const major = y % 4 === 0;
    lines.push(
      <line
        key={`h${y}`}
        x1={a.x} y1={a.y} x2={b.x} y2={b.y}
        stroke={major ? 'rgba(45, 212, 160, 0.22)' : 'rgba(255, 255, 255, 0.05)'}
        strokeWidth={major ? 1 : 1}
      />
    );
  }
  for (let x = 0; x <= GRID_W; x++) {
    const a = iso(x, 0, 0);
    const b = iso(x, GRID_H, 0);
    const major = x % 4 === 0;
    lines.push(
      <line
        key={`v${x}`}
        x1={a.x} y1={a.y} x2={b.x} y2={b.y}
        stroke={major ? 'rgba(45, 212, 160, 0.22)' : 'rgba(255, 255, 255, 0.05)'}
        strokeWidth={major ? 1 : 1}
      />
    );
  }

  // Ground diamond (outer border)
  const c0 = iso(0, 0, 0);
  const c1 = iso(GRID_W, 0, 0);
  const c2 = iso(GRID_W, GRID_H, 0);
  const c3 = iso(0, GRID_H, 0);
  const borderPts = `${c0.x},${c0.y} ${c1.x},${c1.y} ${c2.x},${c2.y} ${c3.x},${c3.y}`;

  // Hover cell highlight
  let hoverPoly = null;
  if (hoverCell && hoverCell.x >= 0 && hoverCell.y >= 0 && hoverCell.x < GRID_W && hoverCell.y < GRID_H) {
    const { x, y } = hoverCell;
    const p0 = iso(x,     y,     0);
    const p1 = iso(x + 1, y,     0);
    const p2 = iso(x + 1, y + 1, 0);
    const p3 = iso(x,     y + 1, 0);
    hoverPoly = (
      <polygon
        points={`${p0.x},${p0.y} ${p1.x},${p1.y} ${p2.x},${p2.y} ${p3.x},${p3.y}`}
        fill="rgba(45, 212, 160, 0.15)"
        stroke="rgba(45, 212, 160, 0.6)"
        strokeWidth="1.5"
      />
    );
  }

  return (
    <g className="iso-grid">
      {/* Ground fill */}
      <polygon points={borderPts} fill="rgba(11, 14, 19, 0.55)" />
      {lines}
      {hoverPoly}
      {/* Outer diamond */}
      <polygon
        points={borderPts}
        fill="none"
        stroke="rgba(45, 212, 160, 0.4)"
        strokeWidth="1.5"
      />
    </g>
  );
}

window.IsoGrid = IsoGrid;
window.GRID_W = GRID_W;
window.GRID_H = GRID_H;
