<template>
  <div class="page-wrapper">
    <Spinner :loading="loading" />
    <div v-html="output" />
    <div v-if="!loading && status ==='starting'">
        <form name="loginForm" method="post" action="/login.php" @submit.prevent="submitForm" class="login-form" autocomplete="on">
          <input type="hidden" name="relocation" value="route=search/search&type=simple" />

          <h2 class="title">Login</h2>
          
          <div class="input-group">
            <input
              type="text"
              placeholder="Username"
              v-model="username"
              name="username"
              required
              autocomplete="username"
              inputmode="email"
            />
          </div>

          <div class="input-group">
            <input
              type="password"
              placeholder="Password"
              v-model="password"
              name="password"
              required
              autocomplete="current-password"
            />
          </div>

          <Captcha ref="captchaRef" v-model:captcha="captchaValue" />
          <button type="submit" :disabled="loading || !captchaValue" class="btn">
            <span v-if="!loading">Login</span>
            <span v-else>Loading...</span>
          </button>
          <p v-if="captchaError" class="error-text">{{ captchaError }}</p>
        </form>
    </div>
    <div v-else class="waiting-container">
      <h2>Container Status: {{ status }}</h2>
      <p v-if="status === 'running'">Waiting for services to be ready...</p>
      <p v-else-if="status === 'error'" class="error-text">{{ errorMessage }}</p>
    </div>
    <Spinner :loading="loading" />
  </div>
</template>

<script setup>
definePageMeta({
  // This is an example of inline middleware
  middleware: async nuxtApp => {
    const host = useRequestURL().origin
    console.log(useRequestURL())
    const res = await $fetch(host + '/api/status')
    if (res.status === 'ready') { 
      navigateTo(host, { external: true })
      return false;
    } 
    return true
  },
})

import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import Spinner from '@/components/Spinner.vue'
import Captcha from '@/components/Captcha.vue'

const output = ref('')
const router = useRouter()
const route = useRoute()
const loading = ref(true)
const username = ref('')
const password = ref('')
const captchaRef = ref(null)
const captchaValue = ref('')
const captchaError = ref('')
const allowAccess = ref(false)
const interval = ref(null)
const status = ref('starting')

const POLL_MS = 5000
const ALLOWED_REDIRECTS = new Set(['/', '/login', '/signin'])

async function checkStatus () {
  try {
    const res = await $fetch(`${window.location.origin}/api/status`, {
      method: 'GET',
      cache: 'no-store'
    })
    status.value = res.status

    if (res.status === 'ready') {
      if (interval.value) clearInterval(interval.value)
      loading.value = false
      if (username.value && password.value) {
        document.loginForm.submit()
      } else {
        navigateTo(window.location.origin + '/', { external: true })
      }
    }
  } catch (error) {
    loading.value = false
    status.value = 'error'
    errorMessage.value = error?.data?.message || 'Internal server error!'
  }
}

onMounted(() => {
  allowAccess.value = true
  loading.value = false
  checkStatus()
  interval.value = setInterval(checkStatus, POLL_MS)
})

onUnmounted(() => {
  if (interval.value) clearInterval(interval.value)
})

const submitForm = async () => {
  loading.value = true
  output.value = ''
  captchaError.value = ''

  try {
    const res = await $fetch(`${window.location.origin}/api/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: {
        panswer: captchaValue.value
      },
      throwHttpErrors: false
    })

    if (res?.status !== 'success') {
      captchaError.value = res?.message || 'Login failed'
    }
  } catch (error) {
    captchaError.value = error?.data?.message || 'Internal server error!'
  } finally {
    loading.value = false
    // scrub sensitive inputs
    captchaRef.value?.refreshCaptcha()
    captchaValue.value = ''
  }
}
</script>

<style scoped>
.login-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);
}
.input-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 1.2rem;
}
.btn {
  width: 100%;
  padding: 0.8rem;
  font-weight: 600;
  font-size: 1.1rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.btn:hover:not(:disabled) { background-color: #2563eb; }
.btn:disabled { background-color: #93c5fd; cursor: not-allowed; }
.input-group input {
  padding: 0.8rem;
  border: 1px solid #ccc;
  border-radius: 6px;
  font-size: 1rem;
}
.input-group input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59,130,246,.3);
}
.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; margin-top: .5rem; }
</style> 