<template>
  <div class="overflow-hidden">
    <Notifications />
    <Login v-if="screen === 'login'" />
    <Register v-if="screen === 'register'" />
    <Characters v-if="screen === 'characters'" />
    <Game v-if="screen === 'game'" />
  </div>
</template>

<script setup lang="ts">
import { useGameStore } from '@/stores/game'
import Notifications from '@/components/utilities/Notifications.vue'
import Login from '@/screens/Login.vue'
import Register from '@/screens/Register.vue'
import Characters from '@/screens/Characters.vue'
import Game from '@/screens/Game.vue'
import { storeToRefs } from 'pinia'

const gameStore = useGameStore()
const { screen } = storeToRefs(gameStore)

gameStore.$subscribe(
  (mutation, state) => {
    let newScreen = screen.value

    if (!state.connection) {
      newScreen = 'login'
    } else if (state.token && state.connection) {
      newScreen = 'characters'

      if (state.character) {
        newScreen = 'game'
      }
    }

    // Update screen.value only if it's different from the new state
    if (screen.value !== newScreen) {
      screen.value = newScreen
    }
  },
  { detached: true }
)
</script>
