// Hex grid for AWS services. Honeycomb layout via SVG.
const { useState, useMemo } = React;

function HexGrid({ services, layout = "honey" }) {
  const [active, setActive] = useState(0);
  const svc = services[active];

  // Honeycomb layout — 4-3-4-1 ish. We compute on the fly.
  const positions = useMemo(() => computeLayout(services.length, layout), [services.length, layout]);

  // SVG dimensions
  const size = 56; // hex "radius" (corner to center)
  const w = size * Math.sqrt(3);
  const h = size * 2;
  const xs = positions.map(p => p.x);
  const ys = positions.map(p => p.y);
  const minX = Math.min(...xs) - w/2 - 8;
  const maxX = Math.max(...xs) + w/2 + 8;
  const minY = Math.min(...ys) - h/2 - 8;
  const maxY = Math.max(...ys) + h/2 + 8;
  const vbW = maxX - minX;
  const vbH = maxY - minY;

  return (
    <div className="aws-wrap">
      <div>
        <svg
          className="hex-grid-svg"
          viewBox={`${minX} ${minY} ${vbW} ${vbH}`}
          preserveAspectRatio="xMidYMid meet"
        >
          {services.map((s, i) => {
            const { x, y } = positions[i];
            return (
              <g
                key={s.code}
                className={"hex-cell " + (i === active ? "active" : "")}
                transform={`translate(${x} ${y})`}
                onMouseEnter={() => setActive(i)}
                onClick={() => setActive(i)}
              >
                <polygon className="hex-shape" points={hexPoints(size)} />
                <text className="hex-code" y={6}>{s.code}</text>
              </g>
            );
          })}
        </svg>
      </div>

      <aside className="hex-detail">
        <div className="hex-detail-code">{svc.code}</div>
        <div className="hex-detail-name">aws::{svc.name.toLowerCase().replace(/[^a-z0-9]+/g, "_")}</div>
        <div className="hex-detail-desc">{svc.desc}</div>
        <div className="hex-detail-hint">
          $ hover · click any cell
        </div>
      </aside>
    </div>
  );
}

function hexPoints(r) {
  // pointy-top hexagon
  const pts = [];
  for (let i = 0; i < 6; i++) {
    const a = (Math.PI / 3) * i - Math.PI / 2;
    pts.push(`${(r * Math.cos(a)).toFixed(2)},${(r * Math.sin(a)).toFixed(2)}`);
  }
  return pts.join(" ");
}

function computeLayout(n, layout) {
  // pointy-top hex spacing: width = sqrt(3)*r, height = 2r, vertical step = 1.5r
  const r = 56;
  const w = r * Math.sqrt(3);
  const vstep = r * 1.5;

  if (layout === "linear") {
    // 7 across, 2 rows for 14 items
    const cols = 7;
    const out = [];
    for (let i = 0; i < n; i++) {
      const row = Math.floor(i / cols);
      const col = i % cols;
      const x = col * w + (row % 2 ? w / 2 : 0);
      const y = row * vstep;
      out.push({ x, y });
    }
    return out;
  }

  if (layout === "diamond") {
    // diamond pattern: 1-2-3-2-1 etc, centered
    // for 12 items: rows of [2,3,2,3,2] = 12
    const rows = [2, 3, 2, 3, 2];
    const out = [];
    let i = 0;
    rows.forEach((count, rIdx) => {
      const offset = (3 - count) / 2 * w;
      for (let c = 0; c < count && i < n; c++) {
        out.push({
          x: offset + c * w,
          y: rIdx * vstep,
        });
        i++;
      }
    });
    return out;
  }

  // honeycomb (default): 4-3-4-3 staggered → 14 capacity, 12 used
  const rows = [4, 3, 4, 1]; // 4+3+4+1 = 12
  const out = [];
  let i = 0;
  rows.forEach((count, rIdx) => {
    const offset = rIdx % 2 === 1 ? w / 2 : 0;
    const startX = offset;
    for (let c = 0; c < count && i < n; c++) {
      out.push({
        x: startX + c * w,
        y: rIdx * vstep,
      });
      i++;
    }
  });
  return out;
}

window.HexGrid = HexGrid;
