#!/usr/bin/env bash
# Wrapper: lmux-grid <rows> <cols>
# Creates an N-row x M-col grid of panes via repeated splits and emits a JSON
# array of the resulting surface refs (the new panes only, current pane first).
set -euo pipefail

if [ $# -ne 2 ]; then
  echo "usage: lmux-grid <rows> <cols>" >&2
  exit 2
fi

rows="$1"; cols="$2"
total=$((rows * cols))
if [ "$total" -lt 1 ]; then
  echo "[]"
  exit 0
fi

surfaces=()
# We need total-1 new splits to reach total panes from the current one.
# Strategy: alternate vertical (down) and horizontal (right) splits.
n=$((total - 1))
i=0
while [ "$i" -lt "$n" ]; do
  if [ $((i % 2)) -eq 0 ]; then
    s=$(lmux new-split right)
  else
    s=$(lmux new-split down)
  fi
  surfaces+=("$s")
  i=$((i + 1))
done

# Apply tiled layout for evenness (best-effort; mock tmux ignores).
tmux select-layout tiled >/dev/null 2>&1 || true

# Emit JSON.
printf '['
first=1
for s in "${surfaces[@]}"; do
  [ "$first" = "1" ] || printf ','
  first=0
  printf '"%s"' "$s"
done
printf ']\n'
