<script setup lang="ts">
import {ref, onUnmounted} from "vue";
import { useRouter } from 'vue-router';
import {useQuasar} from "quasar";
import axios from "axios";
import {useUserInfo} from "@/composables/useUserInfo";
const router = useRouter();
const info = useUserInfo();
const lobbyCode = ref('');
const isLoading = ref(false);
const $q = useQuasar();
const api = window?.__RUNTIME_CONFIG__?.API_URL;

let pollInterval: number | null = null;

onUnmounted(() => {
  if (pollInterval) {
    clearInterval(pollInterval);
  }
});

const startGameQuasar = async() => {
  if (!lobbyCode.value) {
    $q.notify({ message: 'Lobby-Name wird benötigt', color: 'red', position: 'top', icon: 'cancel' });
    return;
  }
  isLoading.value = true;
  axios.post(`${api}/joinGame/${lobbyCode.value.toString()}`, {}, {withCredentials: true}).then(() => {
    $q.notify({
      message: `Lobby "${lobbyCode.value}" erfolgreich gefunden`,
      color: 'green-6',
      icon: 'check_circle',
      position: 'top'
    });

    // Start polling until gameId is set
    pollInterval = window.setInterval(async () => {
      await info.requestState();
      if (info.gameId) {
        if (pollInterval) {
          clearInterval(pollInterval);
          pollInterval = null;
        }
      }
    }, 100);

  }).catch(() => {
    $q.notify({
      message: `Lobby "${lobbyCode.value}" nicht gefunden`,
      color: 'red-6',
      icon: 'cancel',
      position: 'top'
    })
    isLoading.value = false
  })
}
</script>

<template>
        <header class="text-center q-mb-xl">
          <p
            class="text-h5 text-grey-4 q-mt-md"
            style="max-width: 900px; margin-left: auto; margin-right: auto;"
          >
            Enter the Lobbycode below to join your friend's game and you are ready to go!
          </p>
        </header>

        <div class="q-pa-md" style="width: 100%; max-width: 400px;">

          <div>
            <q-input
              v-model="lobbyCode"
              label="Lobbycode"
              placeholder="123abc"
              filled
              dark
              label-color="white"
              color="white"
              :rules="[val => !!val || 'Lobbycode is missing']"
            />
          </div>

          <div class="text-center q-mt-lg">
            <q-btn
              :loading="isLoading"
              label="Join Game"
              color="positive"
              rounded
              @click="startGameQuasar"
              size="lg"
              class="full-width"
            />
          </div>

        </div>
</template>

<style scoped>
.game-title {
  font-family: serif;


  font-size: 5rem;
  font-weight: 900;
  letter-spacing: 3px;
  color: #FFD700;

  text-shadow:
    2px 2px 0px #000000,
    4px 4px 0px #8B4513,
    6px 6px 12px rgba(0, 0, 0, 0.9);
}
</style>
