import { getDisplayBiome, getDisplayTemperature, getTemperatureBand } from "./biome-rules.js";
import { fillCellContent } from "./ui-grid-cells.js";
import { attachCellListeners } from "./ui-grid-handlers.js";

/**
 * @param {{ state: import("./types.js").GameState, setState: () => void, setError: (s: string) => void, playSound: (s: string) => void, gridEl: HTMLElement, getHatched: () => Array<{ x: number, y: number }>, selected: { x: number, y: number }, emptyCellChoice: { x: number, y: number } | null, selectedTokenId: number | null, lastActionWasDrop: boolean, clampSelection: () => void, animalEmoji: Record<string, string> }} ctx
 * @param {number} x
 * @param {number} y
 * @returns {HTMLElement}
 */
function buildOneCell(ctx, x, y) {
  const { state, getHatched, selected } = ctx;
  const key = `${x}_${y}`;
  const cell = state.grid.cells[key];
  const div = document.createElement("div");
  div.className = "cell";
  const biome = getDisplayBiome(x, y, state.grid);
  const temp = getDisplayTemperature(x, y, state.grid);
  const tempBand = getTemperatureBand(temp);
  div.classList.add(`biome-${biome.toLowerCase()}`, `temp-${tempBand}`);
  const hatchedList = getHatched();
  if (hatchedList.some((h) => h.x === x && h.y === y)) div.classList.add("just-hatched");
  div.setAttribute("role", "button");
  div.setAttribute("tabindex", "0");
  div.dataset.x = String(x);
  div.dataset.y = String(y);
  const isSelected = selected.x === x && selected.y === y;
  if (isSelected) div.classList.add("selected");
  fillCellContent(ctx, div, { cell, key, x, y });
  attachCellListeners(ctx, { div, cell, x, y, key });
  return div;
}

/**
 * @param {{ state: import("./types.js").GameState, setState: () => void, setError: (s: string) => void, playSound: (s: string) => void, gridEl: HTMLElement, getHatched: () => Array<{ x: number, y: number }>, selected: { x: number, y: number }, emptyCellChoice: { x: number, y: number } | null, selectedTokenId: number | null, lastActionWasDrop: boolean, clampSelection: () => void, animalEmoji: Record<string, string> }} ctx
 */
export function renderGrid(ctx) {
  const { state, gridEl } = ctx;
  gridEl.style.gridTemplateColumns = `repeat(${state.grid.width}, 48px)`;
  gridEl.style.gridTemplateRows = `repeat(${state.grid.height}, 48px)`;
  gridEl.innerHTML = "";
  for (let y = 1; y <= state.grid.height; y++) {
    for (let x = 1; x <= state.grid.width; x++) {
      gridEl.appendChild(buildOneCell(ctx, x, y));
    }
  }
}
