import type { Cell, Point } from './types';

export function cellKey(col: number, row: number): string {
  return `${col},${row}`;
}

export function parseCellKey(key: string): Cell {
  const [c, r] = key.split(',');
  return { col: Number(c), row: Number(r) };
}

/** Image-space pixel → grid cell. */
export function worldToCell(pt: Point, gridSize: number): Cell {
  return { col: Math.floor(pt.x / gridSize), row: Math.floor(pt.y / gridSize) };
}

/** Center of a cell in image-space pixels. */
export function cellCenter(col: number, row: number, gridSize: number): Point {
  return { x: (col + 0.5) * gridSize, y: (row + 0.5) * gridSize };
}

export function gridDims(naturalW: number, naturalH: number, gridSize: number): { cols: number; rows: number } {
  return { cols: Math.max(0, Math.ceil(naturalW / gridSize)), rows: Math.max(0, Math.ceil(naturalH / gridSize)) };
}

export function inBounds(col: number, row: number, cols: number, rows: number): boolean {
  return col >= 0 && row >= 0 && col < cols && row < rows;
}

/** Cells covered by an NxN token whose top-left is (col,row). */
export function tokenCells(token: { col: number; row: number; size: number }): string[] {
  const out: string[] = [];
  const n = Math.max(1, token.size);
  for (let c = token.col; c < token.col + n; c++) {
    for (let r = token.row; r < token.row + n; r++) out.push(cellKey(c, r));
  }
  return out;
}
