// Shared game state management
// interface GameState {
//   currentRound: number;
//   maxRounds: number;
//   /** Duration in ms to show results before starting next betting round */
//   resultsDisplayTime: number;
//   results: string[];
//   votes: { player: number; banker: number };
//   /** Timestamp when the current betting round started. null if not in a betting phase. */
//   roundStartTime: number | null;
//   /** Duration in seconds for the current betting round. null if not in a betting phase. */
//   bettingDurationSeconds: number | null;
//   // To keep track of timeouts
//   endOfBettingTimeoutId: NodeJS.Timeout | null;
//   startNextRoundTimeoutId: NodeJS.Timeout | null;
// }

// In-memory state, back to simple module-level variable
let gameState = {
  currentRound: 0, // Start at 0, will become 1 when first round starts
  maxRounds: 80,
  resultsDisplayTime: 5000, // 5 seconds to display results
  results: [],
  votes: { player: 0, banker: 0 },
  roundStartTime: null,
  bettingDurationSeconds: null,
  endOfBettingTimeoutId: null,
  startNextRoundTimeoutId: null,
};

function getGameState() {
  const { endOfBettingTimeoutId, startNextRoundTimeoutId, ...clientState } =
    gameState;
  return clientState;
}

function updateGameState(newState) {
  gameState = { ...gameState, ...newState };
}

function clearTimeouts() {
  if (gameState.endOfBettingTimeoutId) {
    clearTimeout(gameState.endOfBettingTimeoutId);
    gameState.endOfBettingTimeoutId = null;
  }
  if (gameState.startNextRoundTimeoutId) {
    clearTimeout(gameState.startNextRoundTimeoutId);
    gameState.startNextRoundTimeoutId = null;
  }
}

function handleEndOfBetting() {
  gameState.endOfBettingTimeoutId = null; // Clear self

  let result;
  const rand = Math.random();
  const probPlayer = 0.4;
  const probBanker = 0.4;
  const probTie = 0.08;
  const probDragon = 0.06;
  const probPanda = 0.06;

  if (rand < probPlayer) result = "PLAYER";
  else if (rand < probPlayer + probBanker) result = "BANKER";
  else if (rand < probPlayer + probBanker + probTie) result = "TIE";
  else if (rand < probPlayer + probBanker + probTie + probDragon)
    result = "DRAGON";
  else result = "PANDA";

  const originalRoundEnded = gameState.currentRound; // Capture before any update
  const newResults = [...gameState.results, result];

  // Update state for the ended round's result display
  gameState = {
    ...gameState,
    results: newResults,
    roundStartTime: null,
    bettingDurationSeconds: null,
  };
  console.log(`Round ${originalRoundEnded} result: ${result}`);

  // Determine next round and reset results if maxRounds reached
  let nextRoundNumber = originalRoundEnded + 1;
  let resultsForNextSetup = newResults;
  if (nextRoundNumber > gameState.maxRounds) {
    nextRoundNumber = 1;
    resultsForNextSetup = [];
  }

  // Update currentRound to the next round number for the upcoming betting phase
  // and prepare results (potentially cleared if maxRounds was hit)
  gameState = {
    ...gameState,
    currentRound: nextRoundNumber,
    results: resultsForNextSetup,
  };

  gameState.startNextRoundTimeoutId = setTimeout(
    startNextBettingRound,
    gameState.resultsDisplayTime
  );
}

function startNextBettingRound() {
  gameState.startNextRoundTimeoutId = null;

  let roundToStart = gameState.currentRound;
  if (roundToStart === 0) {
    // Handle initial game start, currentRound should be 0
    roundToStart = 1;
  }

  const newBettingDuration = Math.floor(Math.random() * (30 + 1)) + 60; // 60 to 90 seconds

  gameState = {
    ...gameState,
    currentRound: roundToStart,
    votes: { player: 0, banker: 0 },
    roundStartTime: Date.now(),
    bettingDurationSeconds: newBettingDuration,
  };

  console.log(
    `Round ${gameState.currentRound} started. Betting open for ${gameState.bettingDurationSeconds}s.`
  );

  gameState.endOfBettingTimeoutId = setTimeout(
    handleEndOfBetting,
    gameState.bettingDurationSeconds * 1000
  );
}

function startGameLoop() {
  stopGameLoop(); // Clear any existing timeouts before starting
  startNextBettingRound();
}

function stopGameLoop() {
  clearTimeouts();
}

// Initialize the game loop unconditionally when this module is loaded
// startGameLoop(); // We will call this from server.js after setting up the server

module.exports = {
  getGameState,
  updateGameState,
  startGameLoop,
  stopGameLoop,
  // We don't need to export gameState directly, or other internal functions
};
