<template>
  <div class="page-wrapper">
    <div class="waiting-container">
        <h2>Container Status: {{ status }}</h2>
        <p v-if="status === 'ready'">
        Your container is ready! <a :href="`http://${ip}`" target="_blank">Open it</a>
        </p>
        <p v-else-if="status === 'running'">Waiting for services to be ready...</p>
        <p v-else-if="status === 'starting'">Starting container...</p>
        <p v-else-if="status === 'error'" class="error-text">{{ errorMessage }}</p>
    </div>
    <Spinner :loading="loading" />
  </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const name = route.query.name;
const redirect = route.query.redirect;
const loading = ref(true);
const status = ref('starting');
const ip = ref(null);
const interval = ref(null);
const errorMessage = ref(null);

const checkStatus = async () => {
  try {
    const res = await $fetch(`${window.location.origin}/api/status?name=${name}`);
    status.value = res.status;

    if (res.status === 'ready') {
      ip.value = res.ip;
      clearInterval(interval.value);
      loading.value = false;
      // Redirect or show login link
      window.location.href= redirect ?? `http://${res.ip}`;
    }
  } catch (error) {
    loading.value = false;
    status.value = 'error';
    errorMessage.value = error?.data?.message || 'Internal server error!';
    clearInterval(interval.value);
    setTimeout( () => {
        router.replace(`/?auth=ok&redirect=${redirect}`);
    }, 3000);
    
  }
};

onMounted(() => {
  checkStatus();
  interval.value = setInterval(checkStatus, 3000); // Poll every 3s
});

onUnmounted(() => {
  clearInterval(interval.value);
});
</script>
<style scoped>
.waiting-container {
  max-width: 100%;
  width: 400px;
  margin: 5rem auto;
  padding: 2rem;
  border-radius: 8px;
  background: #f9fafb;
  box-shadow: 0 4px 10px rgb(0 0 0 / 0.1);
}
</style>


