<script setup lang="ts">
import { ref, onMounted, onUnmounted, watchEffect } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';

const backendUrl: string = import.meta.env.VITE_BACKEND_URL;
const route = useRoute();

const serverName = ref<string>('Unknown Server');
const playerName = ref<string>('');
const showPlayerName = ref<boolean>(false);
const serverUpdateInterval = ref<number | null>(null);

function updatePlayerName(): void {
  const name: string = localStorage.getItem('playerName') || '';
  playerName.value = name;
  showPlayerName.value = !!name && route.name !== 'PlayerNameInput';
}

async function fetchServerName(): Promise<void> {
  try {
    const { data }: { data: string } = await axios.get(`${backendUrl}/server`, {
      timeout: 3000 // 3 seconds timeout
    });
    serverName.value = data;
  } catch (error: any) {
    if (error.code === 'ECONNABORTED' || (error.message && error.message.includes('timeout'))) {
      console.error('Server request timed out after 3 seconds, reloading page...');
      window.location.reload();
    } else {
      console.error('Failed to fetch server name:', error);
    }
  }
}

onMounted(async () => {
  // Fetch server name immediately
  await fetchServerName();
  
  // Set up interval to update server name every 2 seconds
  serverUpdateInterval.value = window.setInterval(fetchServerName, 2000);

  updatePlayerName();
  window.addEventListener('player-name-changed', updatePlayerName);
});

onUnmounted(() => {
  // Clean up interval when component is unmounted
  if (serverUpdateInterval.value !== null) {
    clearInterval(serverUpdateInterval.value);
  }
  window.removeEventListener('player-name-changed', updatePlayerName);
});

watchEffect(() => {
  updatePlayerName();
});
</script>

<template>
  <div class="relative min-h-screen flex flex-col">
    <!-- <div v-if="showPlayerName" class="player-name-display">
      {{ playerName }}
    </div> -->

    <router-view class="flex-grow" />

    <footer
      class="absolute bottom-2 right-4 text-xs text-gray-400 bg-gray-900 bg-opacity-80 px-3 py-1 rounded shadow-md"
    >
      Server: {{ serverName }}
    </footer>
  </div>
</template>
