import React from "react";
import {
  PRE_GAME,
  PRE_ROUND,
  IN_ROUND,
  POST_ROUND,
  POST_GAME,
  ERROR,
} from "../domain/GameState";
import PreGame from "./screens/PreGame";
import Lobby from "./screens/Lobby";
import GamePanel from "./screens/GamePanel";
import RoundSummary from "./screens/RoundSummary";
import PlayerScores from "./screens/PlayerScores";
import { useGameState, dispatch } from "../domain/gameStore";

const componentMap = {
  [PRE_GAME]: PreGame,
  [PRE_ROUND]: Lobby,
  [IN_ROUND]: GamePanel,
  [POST_ROUND]: RoundSummary,
  [POST_GAME]: PlayerScores,
  [ERROR]: () => <p>Application encountered unrecoverable error, please refresh the page.</p>,
}

const paramRouter = {
  join: dispatch.goToLobby,
  summary: dispatch.goToSummary,
}

const Game = () => {
  const gameState = useGameState();
  
  const url = new URL(window.location.href);
  for (let [param, value] of url.searchParams.entries()) {
    const route = paramRouter[param];
    if (route) {
      url.searchParams.delete(param);
      window.history.replaceState({}, document.title, url.href);
      route(value);
      break;
    }
  }

  const Screen = componentMap[gameState];
  return <Screen />
}

export default Game;
