<script setup lang="ts">
import { RouterView } from 'vue-router'
import { onMounted, onUnmounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserInfo } from "@/composables/useUserInfo";
import { useIngame } from "@/composables/useIngame";
import { storeToRefs } from "pinia";
import { useWebSocket } from "@/composables/useWebsocket";
import { useQuasar } from "quasar";

const route = useRoute();
const router = useRouter();
const info = useUserInfo();

const handleOnlineStatusChange = () => {
  if (navigator.onLine) {
    if (route.name === 'offline') {
      window.location.reload();
    }
  }
};

let interval: number | null = null;

onMounted(() => {
  window.addEventListener('online', handleOnlineStatusChange);

  // Continuously check user state every 10 seconds
  interval = window.setInterval(async () => {
    if (navigator.onLine && route.name !== 'login' && route.name !== 'offline') {
      await info.requestState();
      if (!info.username && route.name !== 'login') {
        router.push({ name: 'login' });
      }
    }
  }, 10000);
});

onUnmounted(() => {
  window.removeEventListener('online', handleOnlineStatusChange);
  if (interval) {
    clearInterval(interval);
  }
});

watch(() => info.gameId, (newGameId) => {
  if (newGameId && route.name !== 'game') {
    router.push({ name: 'game' });
  }
});

const ig = useIngame()
const { isWsConnected } = storeToRefs(ig)
const wb = useWebSocket()
const $q = useQuasar();

watch(isWsConnected, (connected) => {
  if (!connected && info.gameId && route.name === 'game') {
    showReconnectDialog();
  }
});

function showReconnectDialog() {
  $q.dialog({
    title: 'Connection Lost',
    message: 'The connection to the game server was lost. Would you like to reconnect?',
    persistent: true,
    ok: {
      label: 'Reconnect',
      color: 'positive'
    },
    cancel: {
      label: 'Quit',
      color: 'negative'
    }
  }).onOk(() => {
    reconnect();
  }).onCancel(() => {
    router.replace("/");
  });
}

async function reconnect() {
  try {
    await wb.connect();
    $q.notify({
      message: 'Reconnected successfully!',
      color: 'positive',
      icon: 'check'
    });
  } catch (err) {
    $q.notify({
      message: 'Failed to reconnect. Please try again.',
      color: 'negative',
      icon: 'error'
    });
    showReconnectDialog();
  }
}
</script>

<template>
  <router-view />
</template>

<style scoped>
</style>
