import { GameConfig } from "./config.js";

/**
 * @param {import("./types.js").GameState} state
 * @param {number} dtWallSeconds
 */
export function tickTime(state, dtWallSeconds) {
  const dayLength = GameConfig.Time.DayLengthSeconds;
  const phase = (state.timeOfDay ?? 6) + (dtWallSeconds * 24) / dayLength;
  if (phase >= 24) {
    state.timeOfDay = phase - 24;
    state.gameDayTotal = (state.gameDayTotal ?? 0) + 1;
  } else {
    state.timeOfDay = phase;
  }
}

/**
 * @param {import("./types.js").GameState} state
 * @param {number} nowUnix
 * @returns {string}
 */
export function tickWeather(state, nowUnix) {
  const last = state.lastWeatherChangeAt ?? 0;
  if (nowUnix - last < GameConfig.Weather.ChangeIntervalSeconds) return state.weather ?? "sun";
  state.lastWeatherChangeAt = nowUnix;
  const r = Math.random();
  if (r < GameConfig.Weather.RainChance) state.weather = "rain";
  else if (r < GameConfig.Weather.RainChance + GameConfig.Weather.CloudyChance) state.weather = "cloudy";
  else state.weather = "sun";
  return state.weather;
}

/**
 * @param {number} timeOfDay 0..24
 * @returns {{ phase: string, intensity: number }}
 */
export function getTimePhase(timeOfDay) {
  const t = timeOfDay % 24;
  if (t >= 5 && t < 8) return { phase: "dawn", intensity: (t - 5) / 3 };
  if (t >= 8 && t < 18) return { phase: "day", intensity: 1 };
  if (t >= 18 && t < 21) return { phase: "dusk", intensity: (21 - t) / 3 };
  return { phase: "night", intensity: 1 };
}
