import { createRouter, createWebHistory } from 'vue-router';
import SetupView from '../views/SetupView.vue';
import GameView from '../views/GameView.vue';
import InfoView from '../views/InfoView.vue';
import store from '../store';

const routes = [
  {
    path: '/',
    name: 'Setup',
    component: SetupView,
    beforeEnter: (to, from, next) => {
      // Check if we are navigating FROM the Game view.
      // If so, the user explicitly clicked the Setup button, so allow it.
      if (from.name === 'Game') {
        console.log('Router Guard: Allowing navigation from Game to Setup.');
        next(); // Allow navigation to Setup
        return; // Stop further processing of this guard
      }

      // Original logic for initial load or other navigations TO Setup:
      if (store.state.players && store.state.players.length >= 2) {
        // If 2 or more players exist (and not coming from Game), redirect to Game.
        console.log('Router Guard: Players found, redirecting to Game (not coming from Game).');
        next({ name: 'Game', replace: true });
      } else {
        // Otherwise (fewer than 2 players), allow navigation to the Setup view.
        console.log('Router Guard: Not enough players, proceeding to Setup.');
        next();
      }
    }
  },
  {
    path: '/game',
    name: 'Game',
    component: GameView,
    beforeEnter: (to, from, next) => {
      // Keep this guard: prevent direct access to /game without enough players
      if (!store.state.players || store.state.players.length < 2) {
        console.log('Router Guard: Attempted to access Game without enough players, redirecting to Setup.');
        next({ name: 'Setup' });
      } else {
        next();
      }
    }
  },
  {
    path: '/info',
    name: 'Info',
    component: InfoView
  }
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
});

export default router;