import { GameConfig } from "./config.js";
import { plotSizeFromLevel } from "./grid-utils.js";
import { buildDefaultRow1Cells, addStarterAnimals } from "./default-grid-layout.js";

/**
 * @param {import("./types.js").GameState} state
 * @returns {boolean}
 */
export function canPrestige(state) {
  return (state.coins ?? 0) >= GameConfig.Prestige.MinCoinsToReset;
}

/**
 * @param {import("./types.js").GameState} state
 * @returns {import("./types.js").GameState} new state after reset
 */
export function doPrestige(state) {
  if (!canPrestige(state)) return state;
  const newLevel = (state.prestigeLevel ?? 0) + 1;
  const [width, height] = plotSizeFromLevel(1);
  state.coins = 0;
  state.conveyorLevel = 1;
  state.plotLevel = 1;
  state.truckLevel = 1;
  const cells = buildDefaultRow1Cells();
  state.grid = { width, height, cells };
  addStarterAnimals(state);
  state.worldMapLevel = 1;
  state.pendingEggTokens = [];
  state.pendingBabies = [];
  state.receptionAnimals = [];
  state.nextTokenId = 1;
  state.conveyorOffers = [];
  state.lastOfferRefreshAt = 0;
  state.worldTruckSales = [];
  delete state.truckSale;
  state.laboratoryOffer = null;
  state.lastEvolutionAt = Math.floor(Date.now() / 1000);
  state.prestigeLevel = newLevel;
  state.timeOfDay = 6;
  state.weather = "sun";
  state.lastWeatherChangeAt = 0;
  state.quests = [];
  state.lastQuestDay = "";
  state.stats = { eggsPlaced: 0, animalsSold: 0, conveyorUpgrades: 0, plotUpgrades: 0, truckUpgrades: 0, coinsEarned: 0 };
  return state;
}

/**
 * @param {number} prestigeLevel
 * @returns {number}
 */
export function getPrestigeIncomeMultiplier(prestigeLevel) {
  const level = prestigeLevel ?? 0;
  return 1 + level * GameConfig.Prestige.IncomeBonusPerLevel;
}
