<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 { ref, onMounted, onUnmounted } from 'vue'        // <— sicher importieren
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 POLL_MS = 3000

const checkStatus = async () => {
  try {
    const res = await $fetch(`${window.location.origin}/api/status?name=${name}`, {
      method: 'GET',
      cache: 'no-store' // Browser-Cache umgehen
    })

    status.value = res.status
    ip.value = res.ip ?? ip.value

    // Optional: wenn der Container "aus" ist, hier Start triggern (API abhängig)
    // if (res.status === 'stopped' || res.status === 'not_found') {
    //   await $fetch(`${window.location.origin}/api/start?name=${name}`, { method: 'POST' })
    //   status.value = 'starting'
    // }

    if (res.status === 'ready') {
      // Polling nur bei success beenden
      if (interval.value) clearInterval(interval.value)

      loading.value = false
      ip.value = res.ip

      // Redirect-Logik: wenn redirect gesetzt -> dahin; sonst zur Root oder zur IP
      if (redirect) {
        window.location.href = redirect.toString();
      } else {
        // Entweder auf die IP oder auf die Host-Root
        // window.location.href = `http://${ip.value}`
        window.location.href = `http://${window.location.host}`
      }
    } else {
      // solange nicht ready: weiterladen anzeigen
      loading.value = true
    }
  } catch (error) {
    loading.value = false
    status.value = 'error'
    errorMessage.value = error?.data?.message || 'Internal server error!'

    if (interval.value) clearInterval(interval.value)

    // nach kurzer Pause zurück zur App (Redirect-Param übernehmen)
    setTimeout(() => {
      router.replace(`/app/?auth=ok&redirect=${redirect ?? ''}`)
    }, 5000)
  }
}

onMounted(() => {
  checkStatus()
  // WICHTIG: Intervall NICHT im checkStatus selbst löschen,
  // sondern nur bei ready/error oder beim Unmount.
  interval.value = setInterval(checkStatus, POLL_MS)
})

onUnmounted(() => {
  if (interval.value) 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);
}
.error-text { color: #b91c1c; }
</style> 