/**
 * Animals disappear after a duration without any visitor on their cell.
 * Visitors are simulated at their current orbit position; cells under a visitor get lastVisitedAt updated.
 * Death removal is handled by checkDeathCauses in food.js.
 */

import { getVisitorCount } from "./income.js";
import { getAttractionCenter, getVisitorPosition, getCellKeyFromPixelPosition } from "./visitor-attraction.js";

/**
 * Update lastVisitedAt for animal cells when a visitor is on that cell.
 * Does not remove animals; checkDeathCauses(state, nowUnix) handles death from no visit.
 * @param {import("./types.js").GameState} state
 * @param {number} nowUnix
 * @param {number} nowMs
 */
export function tickAnimalVisits(state, nowUnix, nowMs) {
  const gridWidth = state.grid.width;
  const gridHeight = state.grid.height;
  const cells = state.grid.cells;

  const visitorCount = getVisitorCount(state);
  if (visitorCount > 0) {
    const { centerX, centerY } = getAttractionCenter(state, gridWidth, gridHeight);
    const t = nowMs / 1000;
    for (let i = 0; i < visitorCount; i++) {
      const { px, py } = getVisitorPosition({
        i,
        n: visitorCount,
        t,
        centerX,
        centerY,
        gridWidth,
        gridHeight,
      });
      const key = getCellKeyFromPixelPosition(px, py, gridWidth, gridHeight);
      if (key !== "") {
        const cell = cells[key];
        if (cell !== null && cell !== undefined && cell.kind === "animal") {
          cell.lastVisitedAt = nowUnix;
        }
      }
    }
  }
}
