/**
 * Nursery helpers: ordered keys and first free cell.
 */

/**
 * Ordered nursery cell keys (by row then column) for consistent token assignment.
 * @param {import("./types.js").GameState} state
 * @returns {string[]}
 */
export function getNurseryCellKeysOrdered(state) {
  const keys = [];
  for (const [key, cell] of Object.entries(state.grid.cells)) {
    if (cell && cell.kind === "nursery") keys.push(key);
  }
  keys.sort((a, b) => {
    const [ax, ay] = a.split("_").map(Number);
    const [bx, by] = b.split("_").map(Number);
    return ay !== by ? ay - by : ax - bx;
  });
  return keys;
}

/**
 * First nursery cell key that has no token and no pending baby. Returns null if none.
 * @param {import("./types.js").GameState} state
 * @returns {string | null}
 */
export function getFreeNurseryCellKey(state) {
  const keys = getNurseryCellKeysOrdered(state);
  const usedKeys = new Set((state.pendingBabies ?? []).map((p) => p.nurseryCellKey));
  for (const key of keys) {
    const cell = state.grid.cells[key];
    if (cell && cell.kind === "nursery" && (cell.tokenId === null || cell.tokenId === undefined) && !usedKeys.has(key)) return key;
  }
  return null;
}
